f599233d2082d01946565fb0b8f507c882b6172bc7c2d7f807e75e6ad61f090105815060eaec788f70cd1b04477e642bb2c30712e9c14e2c6c98b273658cea 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * Copyright (c) 2021 ESHA Research
  3. * Dual licensed under the MIT and GPL licenses:
  4. * http://www.opensource.org/licenses/mit-license.php
  5. * http://www.gnu.org/licenses/gpl.html
  6. *
  7. * Creates a store area that uses a single cookie as the backing storage.
  8. * This gives you the store API for a specific 'store' cookie that your backend
  9. * can access too. It could definitely use more testing.
  10. *
  11. * Status: BETA - unsupported, useful, needs testing
  12. */
  13. ;(function(window, document, store, _) {
  14. var C = _.cookie = {// and that's good enough for me
  15. name: 'store',
  16. maxAge: 60*60*24*365*10,
  17. suffix: ';path=/;sameSite=strict',
  18. encode: function(state) {
  19. return encodeURIComponent(JSON.stringify(state));
  20. },
  21. decode: function(state) {
  22. return JSON.parse(decodeURIComponent(state));
  23. }
  24. };
  25. C.all = function() {
  26. return C.read(C.name) || {};
  27. };
  28. C.read = function(name) {
  29. var match = document.cookie.match(new RegExp("(^| )"+(name||C.name)+"=([^;]+)"));
  30. return match ? C.decode(match[2]) : null;
  31. };
  32. C.write = function(state, name) {
  33. document.cookie = (name||C.name)+"="+C.encode(state)+";max-age="+C.maxAge+C.suffix;
  34. };
  35. C.remove = function(name) {
  36. document.cookie = (name||C.name)+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT"+C.suffix;
  37. };
  38. C.area = {
  39. key: function(i) {
  40. var c = 0,
  41. state = C.all();
  42. for (var k in state) {
  43. if (state.hasOwnProperty(k) && i === c++) {
  44. return k;
  45. }
  46. }
  47. },
  48. setItem: function(k, v) {
  49. var state = C.all();
  50. state[k] = v;
  51. C.write(state);
  52. },
  53. getItem: function(k) {
  54. var state = C.all();
  55. return state.hasOwnProperty(k) ? state[k] : null;
  56. },
  57. has: function(k) {
  58. return C.all().hasOwnProperty(k);
  59. },
  60. removeItem: function(k) {
  61. var state = C.read(C.name);
  62. delete state[k];
  63. C.write(state);
  64. },
  65. clear: C.remove
  66. };
  67. Object.defineProperty(C.area, "length", {
  68. get: function() {
  69. var ln = 0,
  70. state = C.all();
  71. for (var k in state) {
  72. if (state.hasOwnProperty(k)) {
  73. ln++;
  74. }
  75. }
  76. return ln;
  77. }
  78. });
  79. // create the store api for this storage
  80. store.area("cookie", C.area);
  81. })(window, document, window.store, window.store._);