bootstrap-table-cookie.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v1.2.0
  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. $.extend($.fn.bootstrapTable.defaults, {
  113. cookie: false,
  114. cookieExpire: '2h',
  115. cookiePath: null,
  116. cookieDomain: null,
  117. cookieSecure: null,
  118. cookieIdTable: '',
  119. cookiesEnabled: ['bs.table.sortOrder', 'bs.table.sortName', 'bs.table.pageNumber', 'bs.table.pageList', 'bs.table.columns', 'bs.table.searchText', 'bs.table.filterControl'],
  120. //internal variable
  121. filterControls: [],
  122. filterControlValuesLoaded: false
  123. });
  124. $.fn.bootstrapTable.methods.push('deleteCookie');
  125. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  126. _init = BootstrapTable.prototype.init,
  127. _initTable = BootstrapTable.prototype.initTable,
  128. _initServer = BootstrapTable.prototype.initServer,
  129. _onSort = BootstrapTable.prototype.onSort,
  130. _onPageNumber = BootstrapTable.prototype.onPageNumber,
  131. _onPageListChange = BootstrapTable.prototype.onPageListChange,
  132. _onPageFirst = BootstrapTable.prototype.onPageFirst,
  133. _onPagePre = BootstrapTable.prototype.onPagePre,
  134. _onPageNext = BootstrapTable.prototype.onPageNext,
  135. _onPageLast = BootstrapTable.prototype.onPageLast,
  136. _toggleColumn = BootstrapTable.prototype.toggleColumn,
  137. _selectPage = BootstrapTable.prototype.selectPage,
  138. _onSearch = BootstrapTable.prototype.onSearch;
  139. BootstrapTable.prototype.init = function () {
  140. var timeoutId = 0;
  141. this.options.filterControls = [];
  142. this.options.filterControlValuesLoaded = false;
  143. this.options.cookiesEnabled = typeof this.options.cookiesEnabled === 'string' ?
  144. this.options.cookiesEnabled.replace('[', '').replace(']', '').replace(/ /g, '').toLowerCase().split(',') : this.options.cookiesEnabled;
  145. if (this.options.filterControl) {
  146. var that = this;
  147. this.$el.on('column-search.bs.table', function (e, field, text) {
  148. var isNewField = true;
  149. for (var i = 0; i < that.options.filterControls.length; i++) {
  150. if (that.options.filterControls[i].field === field) {
  151. that.options.filterControls[i].text = text;
  152. isNewField = false;
  153. break;
  154. }
  155. }
  156. if (isNewField) {
  157. that.options.filterControls.push({
  158. field: field,
  159. text: text
  160. });
  161. }
  162. setCookie(that, cookieIds.filterControl, JSON.stringify(that.options.filterControls));
  163. }).on('post-body.bs.table', function () {
  164. setTimeout(function () {
  165. if (!that.options.filterControlValuesLoaded) {
  166. that.options.filterControlValuesLoaded = true;
  167. var filterControl = JSON.parse(getCookie(that, that.options.cookieIdTable, cookieIds.filterControl));
  168. if (filterControl) {
  169. var field = null,
  170. result = [],
  171. header = getCurrentHeader(that),
  172. searchControls = getCurrentSearchControls(that);
  173. header.find(searchControls).each(function (index, ele) {
  174. field = $(this).closest('[data-field]').data('field');
  175. result = $.grep(filterControl, function (valueObj) {
  176. return valueObj.field === field;
  177. });
  178. if (result.length > 0) {
  179. $(this).val(result[0].text);
  180. that.onColumnSearch({currentTarget: $(this)});
  181. }
  182. });
  183. }
  184. }
  185. }, 250);
  186. });
  187. }
  188. _init.apply(this, Array.prototype.slice.apply(arguments));
  189. };
  190. BootstrapTable.prototype.initServer = function () {
  191. var bootstrapTable = this,
  192. selectsWithoutDefaults = [],
  193. columnHasSelectControl = function (column) {
  194. return column.filterControl && column.filterControl === 'select';
  195. },
  196. columnHasDefaultSelectValues = function (column) {
  197. return column.filterData && column.filterData !== 'column';
  198. },
  199. cookiesPresent = function() {
  200. return bootstrapTable.options.cookie && bootstrapTable.getCookies(bootstrapTable);
  201. };
  202. selectsWithoutDefaults = $.grep(bootstrapTable.columns, function(column) {
  203. return columnHasSelectControl(column) && !columnHasDefaultSelectValues(column);
  204. });
  205. // reset variable to original initServer function, so that future calls to initServer
  206. // use the original function from this point on.
  207. BootstrapTable.prototype.initServer = _initServer;
  208. // early return if we don't need to populate any select values with cookie values
  209. if (cookiesPresent() && selectsWithoutDefaults.length === 0) {
  210. return;
  211. }
  212. // call BootstrapTable.prototype.initServer
  213. _initServer.apply(this, Array.prototype.slice.apply(arguments));
  214. }
  215. BootstrapTable.prototype.initTable = function () {
  216. _initTable.apply(this, Array.prototype.slice.apply(arguments));
  217. this.initCookie();
  218. };
  219. BootstrapTable.prototype.initCookie = function () {
  220. if (!this.options.cookie) {
  221. return;
  222. }
  223. if ((this.options.cookieIdTable === '') || (this.options.cookieExpire === '') || (!cookieEnabled())) {
  224. throw new Error("Configuration error. Please review the cookieIdTable, cookieExpire properties, if those properties are ok, then this browser does not support the cookies");
  225. return;
  226. }
  227. var sortOrderCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortOrder),
  228. sortOrderNameCookie = getCookie(this, this.options.cookieIdTable, cookieIds.sortName),
  229. pageNumberCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageNumber),
  230. pageListCookie = getCookie(this, this.options.cookieIdTable, cookieIds.pageList),
  231. columnsCookie = JSON.parse(getCookie(this, this.options.cookieIdTable, cookieIds.columns)),
  232. searchTextCookie = getCookie(this, this.options.cookieIdTable, cookieIds.searchText);
  233. //sortOrder
  234. this.options.sortOrder = sortOrderCookie ? sortOrderCookie : this.options.sortOrder;
  235. //sortName
  236. this.options.sortName = sortOrderNameCookie ? sortOrderNameCookie : this.options.sortName;
  237. //pageNumber
  238. this.options.pageNumber = pageNumberCookie ? +pageNumberCookie : this.options.pageNumber;
  239. //pageSize
  240. this.options.pageSize = pageListCookie ? pageListCookie === this.options.formatAllRows() ? pageListCookie : +pageListCookie : this.options.pageSize;
  241. //searchText
  242. this.options.searchText = searchTextCookie ? searchTextCookie : '';
  243. if (columnsCookie) {
  244. $.each(this.columns, function (i, column) {
  245. column.visible = $.inArray(column.field, columnsCookie) !== -1;
  246. });
  247. }
  248. };
  249. BootstrapTable.prototype.onSort = function () {
  250. _onSort.apply(this, Array.prototype.slice.apply(arguments));
  251. setCookie(this, cookieIds.sortOrder, this.options.sortOrder);
  252. setCookie(this, cookieIds.sortName, this.options.sortName);
  253. };
  254. BootstrapTable.prototype.onPageNumber = function () {
  255. _onPageNumber.apply(this, Array.prototype.slice.apply(arguments));
  256. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  257. };
  258. BootstrapTable.prototype.onPageListChange = function () {
  259. _onPageListChange.apply(this, Array.prototype.slice.apply(arguments));
  260. setCookie(this, cookieIds.pageList, this.options.pageSize);
  261. };
  262. BootstrapTable.prototype.onPageFirst = function () {
  263. _onPageFirst.apply(this, Array.prototype.slice.apply(arguments));
  264. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  265. };
  266. BootstrapTable.prototype.onPagePre = function () {
  267. _onPagePre.apply(this, Array.prototype.slice.apply(arguments));
  268. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  269. };
  270. BootstrapTable.prototype.onPageNext = function () {
  271. _onPageNext.apply(this, Array.prototype.slice.apply(arguments));
  272. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  273. };
  274. BootstrapTable.prototype.onPageLast = function () {
  275. _onPageLast.apply(this, Array.prototype.slice.apply(arguments));
  276. setCookie(this, cookieIds.pageNumber, this.options.pageNumber);
  277. };
  278. BootstrapTable.prototype.toggleColumn = function () {
  279. _toggleColumn.apply(this, Array.prototype.slice.apply(arguments));
  280. var visibleColumns = [];
  281. $.each(this.columns, function (i, column) {
  282. if (column.visible) {
  283. visibleColumns.push(column.field);
  284. }
  285. });
  286. setCookie(this, cookieIds.columns, JSON.stringify(visibleColumns));
  287. };
  288. BootstrapTable.prototype.selectPage = function (page) {
  289. _selectPage.apply(this, Array.prototype.slice.apply(arguments));
  290. setCookie(this, cookieIds.pageNumber, page);
  291. };
  292. BootstrapTable.prototype.onSearch = function () {
  293. var target = Array.prototype.slice.apply(arguments);
  294. _onSearch.apply(this, target);
  295. if ($(target[0].currentTarget).parent().hasClass('search')) {
  296. setCookie(this, cookieIds.searchText, this.searchText);
  297. }
  298. };
  299. BootstrapTable.prototype.getCookies = function(bootstrapTable) {
  300. var cookies = [];
  301. $.each( cookieIds, function( key, value ) {
  302. var cookie = JSON.parse(getCookie(bootstrapTable, bootstrapTable.options.cookieIdTable, cookieIds.filterControl));
  303. cookies.concat(cookie);
  304. });
  305. return cookies;
  306. };
  307. BootstrapTable.prototype.deleteCookie = function (cookieName) {
  308. if ((cookieName === '') || (!cookieEnabled())) {
  309. return;
  310. }
  311. deleteCookie(this.options.cookieIdTable, cookieIds[cookieName], this.options.cookiePath, this.options.cookieDomain);
  312. };
  313. })(jQuery);