@flarehr/apollo-benefits 0.1.106 → 0.3.53396

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/README.md +19 -0
  2. package/dist/assets/@splitsoftware-7d799540.js +18 -0
  3. package/dist/assets/all_tab_color-548783b9.svg +21 -0
  4. package/dist/assets/all_tab_gray-a5051313.svg +6 -0
  5. package/dist/assets/check-57fe1dcb.svg +15 -0
  6. package/dist/assets/datadog-c7ede347.js +5 -0
  7. package/dist/assets/date-fns-c5d8fbc0.js +1 -0
  8. package/dist/assets/default_backdrop-fdd955b8.png +0 -0
  9. package/dist/assets/external_link-599a0aec.svg +3 -0
  10. package/dist/assets/external_link_white-55111b2e.svg +3 -0
  11. package/dist/assets/framer-motion-bb8d6b82.js +1 -0
  12. package/dist/assets/index-87923fdc.js +35 -0
  13. package/dist/assets/index-cfa25e28.css +1 -0
  14. package/dist/assets/index-ee9d2045.js +5 -0
  15. package/dist/assets/lodash-5d893f8c.js +1 -0
  16. package/dist/assets/logo-a34e9b4b.png +0 -0
  17. package/dist/assets/oidc-client-6f6e47c2.js +101 -0
  18. package/dist/assets/padlock-8c081120.svg +26 -0
  19. package/dist/assets/suitcase-6471ad05.svg +17 -0
  20. package/dist/assets/vendor-2d0139ca.js +788 -0
  21. package/dist/assets/warning-a7f1af23.svg +14 -0
  22. package/dist/assets/welcome_image_mobile-dbde6c80.png +0 -0
  23. package/dist/assets/welcome_image_v2-869c59e4.png +0 -0
  24. package/dist/assets/wellbeing_banner-6903d615.png +0 -0
  25. package/dist/assets/workplace_link_banner_mobile-6ebaa24b.png +0 -0
  26. package/dist/assets/workplace_link_banner_v2-c81ed849.png +0 -0
  27. package/dist/config.json +14 -0
  28. package/dist/favicon.ico +0 -0
  29. package/dist/icons/android-chrome-192x192.png +0 -0
  30. package/dist/icons/android-chrome-512x512.png +0 -0
  31. package/dist/icons/apple-touch-icon.png +0 -0
  32. package/dist/icons/favicon-16x16.png +0 -0
  33. package/dist/icons/favicon-32x32.png +0 -0
  34. package/dist/index.html +114 -0
  35. package/dist/manifest.json +21 -0
  36. package/dist/sw-esm.js +16 -0
  37. package/package.json +129 -60
  38. package/LICENSE +0 -21
  39. package/dist/lib/apollo-benefits/apollo-benefits.esm.js +0 -1
  40. package/dist/lib/apollo-benefits/assets/car-placeholder.svg +0 -5
  41. package/dist/lib/apollo-benefits/assets/check.svg +0 -13
  42. package/dist/lib/apollo-benefits/index.esm.js +0 -0
  43. package/dist/lib/apollo-benefits/p-06a1f65f.js +0 -1
  44. package/dist/lib/apollo-benefits/p-077d7f8d.entry.js +0 -1
  45. package/dist/lib/apollo-benefits/p-0a21a709.entry.js +0 -1
  46. package/dist/lib/apollo-benefits/p-14054f15.js +0 -1
  47. package/dist/lib/apollo-benefits/p-24a37d64.js +0 -1
  48. package/dist/lib/apollo-benefits/p-2b3f3b72.entry.js +0 -1
  49. package/dist/lib/apollo-benefits/p-3111d565.entry.js +0 -1
  50. package/dist/lib/apollo-benefits/p-327396fa.entry.js +0 -1
  51. package/dist/lib/apollo-benefits/p-3af26279.entry.js +0 -1
  52. package/dist/lib/apollo-benefits/p-3d4d2683.js +0 -1
  53. package/dist/lib/apollo-benefits/p-4474bcf8.entry.js +0 -1
  54. package/dist/lib/apollo-benefits/p-50fe790f.js +0 -1
  55. package/dist/lib/apollo-benefits/p-53bcbd1d.js +0 -1
  56. package/dist/lib/apollo-benefits/p-64a2b03a.entry.js +0 -1
  57. package/dist/lib/apollo-benefits/p-68c136da.js +0 -1
  58. package/dist/lib/apollo-benefits/p-6bd16f5b.js +0 -1
  59. package/dist/lib/apollo-benefits/p-71dbc8ff.entry.js +0 -1
  60. package/dist/lib/apollo-benefits/p-774d9bc5.entry.js +0 -1
  61. package/dist/lib/apollo-benefits/p-7a2ca86d.entry.js +0 -1
  62. package/dist/lib/apollo-benefits/p-7a572b50.js +0 -1
  63. package/dist/lib/apollo-benefits/p-7c2cd94a.entry.js +0 -1
  64. package/dist/lib/apollo-benefits/p-839493d7.entry.js +0 -1
  65. package/dist/lib/apollo-benefits/p-acf61bdc.js +0 -1
  66. package/dist/lib/apollo-benefits/p-b33fc683.js +0 -1
  67. package/dist/lib/apollo-benefits/p-beb8f728.entry.js +0 -1
  68. package/dist/lib/apollo-benefits/p-d7bea1d9.entry.js +0 -1
  69. package/dist/lib/apollo-benefits/p-ddb176cb.entry.js +0 -1
  70. package/dist/lib/apollo-benefits/p-e241f55b.entry.js +0 -1
  71. package/dist/lib/apollo-benefits/p-ef8ea713.entry.js +0 -1
  72. package/dist/lib/apollo-benefits/p-f603197d.js +0 -15
  73. package/dist/lib/cjs/active-router-0ecaf2b8.js +0 -75
  74. package/dist/lib/cjs/ap-ben-choose-vehicle-section_4.cjs.entry.js +0 -2684
  75. package/dist/lib/cjs/ap-ben-complete-section_4.cjs.entry.js +0 -108
  76. package/dist/lib/cjs/ap-ben-notifications-section.cjs.entry.js +0 -238
  77. package/dist/lib/cjs/apollo-benefits.cjs.js +0 -25
  78. package/dist/lib/cjs/app-globals-67583b8b.js +0 -12
  79. package/dist/lib/cjs/async-6a7926f0.js +0 -753
  80. package/dist/lib/cjs/cars-calculator-app.cjs.entry.js +0 -52
  81. package/dist/lib/cjs/cars-calculator.service-11b0cd88.js +0 -901
  82. package/dist/lib/cjs/context-consumer.cjs.entry.js +0 -29
  83. package/dist/lib/cjs/datorama-akita-31d23240.js +0 -2551
  84. package/dist/lib/cjs/delay-d31618c3.js +0 -206
  85. package/dist/lib/cjs/distinctUntilChanged-e8538790.js +0 -371
  86. package/dist/lib/cjs/dom-utils-b8befdd5.js +0 -63
  87. package/dist/lib/cjs/fl-button.cjs.entry.js +0 -30
  88. package/dist/lib/cjs/fl-dropdown-async_2.cjs.entry.js +0 -467
  89. package/dist/lib/cjs/fl-dropdown.cjs.entry.js +0 -232
  90. package/dist/lib/cjs/fl-loading-indicator.cjs.entry.js +0 -26
  91. package/dist/lib/cjs/fl-style-guide.cjs.entry.js +0 -91
  92. package/dist/lib/cjs/index-f1fadf90.js +0 -1735
  93. package/dist/lib/cjs/index.cjs.js +0 -2
  94. package/dist/lib/cjs/loader.cjs.js +0 -27
  95. package/dist/lib/cjs/location-utils-36fe7e5e.js +0 -237
  96. package/dist/lib/cjs/match-path-be4ea5f6.js +0 -279
  97. package/dist/lib/cjs/session.query-d61ba7ec.js +0 -1731
  98. package/dist/lib/cjs/stencil-async-content.cjs.entry.js +0 -32
  99. package/dist/lib/cjs/stencil-route-link.cjs.entry.js +0 -78
  100. package/dist/lib/cjs/stencil-route-switch.cjs.entry.js +0 -104
  101. package/dist/lib/cjs/stencil-route-title.cjs.entry.js +0 -32
  102. package/dist/lib/cjs/stencil-route.cjs.entry.js +0 -97
  103. package/dist/lib/cjs/stencil-router-prompt.cjs.entry.js +0 -59
  104. package/dist/lib/cjs/stencil-router-redirect.cjs.entry.js +0 -32
  105. package/dist/lib/cjs/stencil-router.cjs.entry.js +0 -640
  106. package/dist/lib/collection/assets/image/complete.svg +0 -122
  107. package/dist/lib/collection/collection-manifest.json +0 -53
  108. package/dist/lib/collection/components/cars-calculator-app/api/api-client.js +0 -5
  109. package/dist/lib/collection/components/cars-calculator-app/api/cars-calculator.api.js +0 -45
  110. package/dist/lib/collection/components/cars-calculator-app/cars-calculator-app.css +0 -22
  111. package/dist/lib/collection/components/cars-calculator-app/cars-calculator-app.js +0 -93
  112. package/dist/lib/collection/components/cars-calculator-app/modal-section/modal-section.css +0 -0
  113. package/dist/lib/collection/components/cars-calculator-app/modal-section/modal-section.js +0 -144
  114. package/dist/lib/collection/components/cars-calculator-app/notifications-section/notifications-section.js +0 -25
  115. package/dist/lib/collection/components/cars-calculator-app/pages/assets/car-placeholder.svg +0 -5
  116. package/dist/lib/collection/components/cars-calculator-app/pages/assets/check.svg +0 -13
  117. package/dist/lib/collection/components/cars-calculator-app/pages/choose-vehicle-section.component.js +0 -193
  118. package/dist/lib/collection/components/cars-calculator-app/pages/complete-section.component.js +0 -38
  119. package/dist/lib/collection/components/cars-calculator-app/pages/cost-breakdown-section.component.js +0 -47
  120. package/dist/lib/collection/components/cars-calculator-app/pages/model-variants-section.component.css +0 -34
  121. package/dist/lib/collection/components/cars-calculator-app/pages/model-variants-section.component.js +0 -64
  122. package/dist/lib/collection/components/cars-calculator-app/pages/personal-info-section.component.js +0 -66
  123. package/dist/lib/collection/components/cars-calculator-app/pages/quote-result-section.component.js +0 -86
  124. package/dist/lib/collection/components/cars-calculator-app/pages/submit-quote-section.component.js +0 -75
  125. package/dist/lib/collection/components/cars-calculator-app/services/app-configuration.service.js +0 -13
  126. package/dist/lib/collection/components/cars-calculator-app/services/cars-calculator.service.js +0 -103
  127. package/dist/lib/collection/components/cars-calculator-app/services/notifications.service.js +0 -37
  128. package/dist/lib/collection/components/cars-calculator-app/services/notifications.store.js +0 -3
  129. package/dist/lib/collection/components/cars-calculator-app/services/session.query.js +0 -35
  130. package/dist/lib/collection/components/cars-calculator-app/services/session.store.js +0 -78
  131. package/dist/lib/collection/global/config.js +0 -2
  132. package/dist/lib/collection/global/main.dev.js +0 -5
  133. package/dist/lib/collection/global/main.js +0 -5
  134. package/dist/lib/collection/index.js +0 -2
  135. package/dist/lib/collection/utils/config.js +0 -2
  136. package/dist/lib/collection/utils/index.js +0 -15
  137. package/dist/lib/collection/utils/lazy.js +0 -29
  138. package/dist/lib/esm/active-router-7c2ca849.js +0 -73
  139. package/dist/lib/esm/ap-ben-choose-vehicle-section_4.entry.js +0 -2677
  140. package/dist/lib/esm/ap-ben-complete-section_4.entry.js +0 -101
  141. package/dist/lib/esm/ap-ben-notifications-section.entry.js +0 -234
  142. package/dist/lib/esm/apollo-benefits.js +0 -23
  143. package/dist/lib/esm/app-globals-65714cca.js +0 -10
  144. package/dist/lib/esm/async-68e9cad7.js +0 -738
  145. package/dist/lib/esm/cars-calculator-app.entry.js +0 -48
  146. package/dist/lib/esm/cars-calculator.service-2cde6288.js +0 -894
  147. package/dist/lib/esm/context-consumer.entry.js +0 -25
  148. package/dist/lib/esm/datorama-akita-c87196a0.js +0 -2545
  149. package/dist/lib/esm/delay-115d4292.js +0 -200
  150. package/dist/lib/esm/distinctUntilChanged-bf69e0f8.js +0 -363
  151. package/dist/lib/esm/dom-utils-109a7d75.js +0 -55
  152. package/dist/lib/esm/fl-button.entry.js +0 -26
  153. package/dist/lib/esm/fl-dropdown-async_2.entry.js +0 -462
  154. package/dist/lib/esm/fl-dropdown.entry.js +0 -228
  155. package/dist/lib/esm/fl-loading-indicator.entry.js +0 -22
  156. package/dist/lib/esm/fl-style-guide.entry.js +0 -87
  157. package/dist/lib/esm/index-19c4d245.js +0 -1703
  158. package/dist/lib/esm/index.js +0 -1
  159. package/dist/lib/esm/loader.js +0 -23
  160. package/dist/lib/esm/location-utils-312665d3.js +0 -226
  161. package/dist/lib/esm/match-path-4b5c7d98.js +0 -276
  162. package/dist/lib/esm/polyfills/core-js.js +0 -11
  163. package/dist/lib/esm/polyfills/css-shim.js +0 -1
  164. package/dist/lib/esm/polyfills/dom.js +0 -79
  165. package/dist/lib/esm/polyfills/es5-html-element.js +0 -1
  166. package/dist/lib/esm/polyfills/index.js +0 -34
  167. package/dist/lib/esm/polyfills/system.js +0 -6
  168. package/dist/lib/esm/session.query-0f1c9503.js +0 -1719
  169. package/dist/lib/esm/stencil-async-content.entry.js +0 -28
  170. package/dist/lib/esm/stencil-route-link.entry.js +0 -74
  171. package/dist/lib/esm/stencil-route-switch.entry.js +0 -100
  172. package/dist/lib/esm/stencil-route-title.entry.js +0 -28
  173. package/dist/lib/esm/stencil-route.entry.js +0 -93
  174. package/dist/lib/esm/stencil-router-prompt.entry.js +0 -55
  175. package/dist/lib/esm/stencil-router-redirect.entry.js +0 -28
  176. package/dist/lib/esm/stencil-router.entry.js +0 -636
  177. package/dist/lib/index.cjs.js +0 -1
  178. package/dist/lib/index.js +0 -1
  179. package/dist/lib/loader/cdn.js +0 -3
  180. package/dist/lib/loader/index.cjs.js +0 -3
  181. package/dist/lib/loader/index.d.ts +0 -13
  182. package/dist/lib/loader/index.es2017.js +0 -3
  183. package/dist/lib/loader/index.js +0 -4
  184. package/dist/lib/loader/package.json +0 -10
  185. package/dist/lib/node_modules/@flarehr/beacon/dist/collection/components/button/button.css +0 -45
  186. package/dist/lib/node_modules/@flarehr/beacon/dist/collection/components/dropdown/dropdown.css +0 -9
  187. package/dist/lib/node_modules/@flarehr/beacon/dist/collection/components/dropdown-async/dropdown-async.css +0 -9
  188. package/dist/lib/node_modules/@flarehr/beacon/dist/collection/components/loading-indicator/loading-indicator.css +0 -141
  189. package/dist/lib/node_modules/@flarehr/beacon/dist/collection/components/promise-button/promise-button.css +0 -5
  190. package/dist/lib/node_modules/@flarehr/beacon/dist/collection/components/style-guide/style-guide.css +0 -0
  191. package/dist/lib/node_modules/@stencil/router/dist/collection/components/route/route.css +0 -3
  192. package/dist/lib/types/components/cars-calculator-app/api/api-client.d.ts +0 -2
  193. package/dist/lib/types/components/cars-calculator-app/api/cars-calculator.api.d.ts +0 -96
  194. package/dist/lib/types/components/cars-calculator-app/cars-calculator-app.d.ts +0 -15
  195. package/dist/lib/types/components/cars-calculator-app/modal-section/modal-section.d.ts +0 -16
  196. package/dist/lib/types/components/cars-calculator-app/notifications-section/notifications-section.d.ts +0 -5
  197. package/dist/lib/types/components/cars-calculator-app/pages/choose-vehicle-section.component.d.ts +0 -23
  198. package/dist/lib/types/components/cars-calculator-app/pages/complete-section.component.d.ts +0 -5
  199. package/dist/lib/types/components/cars-calculator-app/pages/cost-breakdown-section.component.d.ts +0 -6
  200. package/dist/lib/types/components/cars-calculator-app/pages/model-variants-section.component.d.ts +0 -12
  201. package/dist/lib/types/components/cars-calculator-app/pages/personal-info-section.component.d.ts +0 -10
  202. package/dist/lib/types/components/cars-calculator-app/pages/quote-result-section.component.d.ts +0 -13
  203. package/dist/lib/types/components/cars-calculator-app/pages/submit-quote-section.component.d.ts +0 -10
  204. package/dist/lib/types/components/cars-calculator-app/services/app-configuration.service.d.ts +0 -7
  205. package/dist/lib/types/components/cars-calculator-app/services/cars-calculator.service.d.ts +0 -11
  206. package/dist/lib/types/components/cars-calculator-app/services/notifications.service.d.ts +0 -15
  207. package/dist/lib/types/components/cars-calculator-app/services/notifications.store.d.ts +0 -14
  208. package/dist/lib/types/components/cars-calculator-app/services/session.query.d.ts +0 -25
  209. package/dist/lib/types/components/cars-calculator-app/services/session.store.d.ts +0 -74
  210. package/dist/lib/types/components.d.ts +0 -170
  211. package/dist/lib/types/global/config.d.ts +0 -2
  212. package/dist/lib/types/global/main.d.ts +0 -1
  213. package/dist/lib/types/global/main.dev.d.ts +0 -1
  214. package/dist/lib/types/index.d.ts +0 -2
  215. package/dist/lib/types/stencil-public-runtime.d.ts +0 -1555
  216. package/dist/lib/types/utils/config.d.ts +0 -2
  217. package/dist/lib/types/utils/index.d.ts +0 -7
  218. package/dist/lib/types/utils/lazy.d.ts +0 -12
  219. package/readme.md +0 -1
@@ -1,2545 +0,0 @@
1
- import { S as Subscription, O as Observable, r as rxSubscriber, a as Subscriber, A as AsyncAction, b as AsyncScheduler } from './async-68e9cad7.js';
2
- import { N as Notification, e as empty, o as of, d as delay } from './delay-115d4292.js';
3
- import { S as SimpleOuterSubscriber, a as SimpleInnerSubscriber, i as innerSubscribe, f as from, m as map, d as distinctUntilChanged, b as filter } from './distinctUntilChanged-bf69e0f8.js';
4
-
5
- /*! *****************************************************************************
6
- Copyright (c) Microsoft Corporation.
7
-
8
- Permission to use, copy, modify, and/or distribute this software for any
9
- purpose with or without fee is hereby granted.
10
-
11
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
- PERFORMANCE OF THIS SOFTWARE.
18
- ***************************************************************************** */
19
-
20
- function __rest(s, e) {
21
- var t = {};
22
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
23
- t[p] = s[p];
24
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
25
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
26
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
27
- t[p[i]] = s[p[i]];
28
- }
29
- return t;
30
- }
31
-
32
- function __decorate(decorators, target, key, desc) {
33
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
34
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
35
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
36
- return c > 3 && r && Object.defineProperty(target, key, r), r;
37
- }
38
-
39
- function __metadata(metadataKey, metadataValue) {
40
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
41
- }
42
-
43
- const ObjectUnsubscribedErrorImpl = (() => {
44
- function ObjectUnsubscribedErrorImpl() {
45
- Error.call(this);
46
- this.message = 'object unsubscribed';
47
- this.name = 'ObjectUnsubscribedError';
48
- return this;
49
- }
50
- ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);
51
- return ObjectUnsubscribedErrorImpl;
52
- })();
53
- const ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;
54
-
55
- class SubjectSubscription extends Subscription {
56
- constructor(subject, subscriber) {
57
- super();
58
- this.subject = subject;
59
- this.subscriber = subscriber;
60
- this.closed = false;
61
- }
62
- unsubscribe() {
63
- if (this.closed) {
64
- return;
65
- }
66
- this.closed = true;
67
- const subject = this.subject;
68
- const observers = subject.observers;
69
- this.subject = null;
70
- if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
71
- return;
72
- }
73
- const subscriberIndex = observers.indexOf(this.subscriber);
74
- if (subscriberIndex !== -1) {
75
- observers.splice(subscriberIndex, 1);
76
- }
77
- }
78
- }
79
-
80
- class SubjectSubscriber extends Subscriber {
81
- constructor(destination) {
82
- super(destination);
83
- this.destination = destination;
84
- }
85
- }
86
- class Subject extends Observable {
87
- constructor() {
88
- super();
89
- this.observers = [];
90
- this.closed = false;
91
- this.isStopped = false;
92
- this.hasError = false;
93
- this.thrownError = null;
94
- }
95
- [rxSubscriber]() {
96
- return new SubjectSubscriber(this);
97
- }
98
- lift(operator) {
99
- const subject = new AnonymousSubject(this, this);
100
- subject.operator = operator;
101
- return subject;
102
- }
103
- next(value) {
104
- if (this.closed) {
105
- throw new ObjectUnsubscribedError();
106
- }
107
- if (!this.isStopped) {
108
- const { observers } = this;
109
- const len = observers.length;
110
- const copy = observers.slice();
111
- for (let i = 0; i < len; i++) {
112
- copy[i].next(value);
113
- }
114
- }
115
- }
116
- error(err) {
117
- if (this.closed) {
118
- throw new ObjectUnsubscribedError();
119
- }
120
- this.hasError = true;
121
- this.thrownError = err;
122
- this.isStopped = true;
123
- const { observers } = this;
124
- const len = observers.length;
125
- const copy = observers.slice();
126
- for (let i = 0; i < len; i++) {
127
- copy[i].error(err);
128
- }
129
- this.observers.length = 0;
130
- }
131
- complete() {
132
- if (this.closed) {
133
- throw new ObjectUnsubscribedError();
134
- }
135
- this.isStopped = true;
136
- const { observers } = this;
137
- const len = observers.length;
138
- const copy = observers.slice();
139
- for (let i = 0; i < len; i++) {
140
- copy[i].complete();
141
- }
142
- this.observers.length = 0;
143
- }
144
- unsubscribe() {
145
- this.isStopped = true;
146
- this.closed = true;
147
- this.observers = null;
148
- }
149
- _trySubscribe(subscriber) {
150
- if (this.closed) {
151
- throw new ObjectUnsubscribedError();
152
- }
153
- else {
154
- return super._trySubscribe(subscriber);
155
- }
156
- }
157
- _subscribe(subscriber) {
158
- if (this.closed) {
159
- throw new ObjectUnsubscribedError();
160
- }
161
- else if (this.hasError) {
162
- subscriber.error(this.thrownError);
163
- return Subscription.EMPTY;
164
- }
165
- else if (this.isStopped) {
166
- subscriber.complete();
167
- return Subscription.EMPTY;
168
- }
169
- else {
170
- this.observers.push(subscriber);
171
- return new SubjectSubscription(this, subscriber);
172
- }
173
- }
174
- asObservable() {
175
- const observable = new Observable();
176
- observable.source = this;
177
- return observable;
178
- }
179
- }
180
- Subject.create = (destination, source) => {
181
- return new AnonymousSubject(destination, source);
182
- };
183
- class AnonymousSubject extends Subject {
184
- constructor(destination, source) {
185
- super();
186
- this.destination = destination;
187
- this.source = source;
188
- }
189
- next(value) {
190
- const { destination } = this;
191
- if (destination && destination.next) {
192
- destination.next(value);
193
- }
194
- }
195
- error(err) {
196
- const { destination } = this;
197
- if (destination && destination.error) {
198
- this.destination.error(err);
199
- }
200
- }
201
- complete() {
202
- const { destination } = this;
203
- if (destination && destination.complete) {
204
- this.destination.complete();
205
- }
206
- }
207
- _subscribe(subscriber) {
208
- const { source } = this;
209
- if (source) {
210
- return this.source.subscribe(subscriber);
211
- }
212
- else {
213
- return Subscription.EMPTY;
214
- }
215
- }
216
- }
217
-
218
- class BehaviorSubject extends Subject {
219
- constructor(_value) {
220
- super();
221
- this._value = _value;
222
- }
223
- get value() {
224
- return this.getValue();
225
- }
226
- _subscribe(subscriber) {
227
- const subscription = super._subscribe(subscriber);
228
- if (subscription && !subscription.closed) {
229
- subscriber.next(this._value);
230
- }
231
- return subscription;
232
- }
233
- getValue() {
234
- if (this.hasError) {
235
- throw this.thrownError;
236
- }
237
- else if (this.closed) {
238
- throw new ObjectUnsubscribedError();
239
- }
240
- else {
241
- return this._value;
242
- }
243
- }
244
- next(value) {
245
- super.next(this._value = value);
246
- }
247
- }
248
-
249
- class QueueAction extends AsyncAction {
250
- constructor(scheduler, work) {
251
- super(scheduler, work);
252
- this.scheduler = scheduler;
253
- this.work = work;
254
- }
255
- schedule(state, delay = 0) {
256
- if (delay > 0) {
257
- return super.schedule(state, delay);
258
- }
259
- this.delay = delay;
260
- this.state = state;
261
- this.scheduler.flush(this);
262
- return this;
263
- }
264
- execute(state, delay) {
265
- return (delay > 0 || this.closed) ?
266
- super.execute(state, delay) :
267
- this._execute(state, delay);
268
- }
269
- requestAsyncId(scheduler, id, delay = 0) {
270
- if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
271
- return super.requestAsyncId(scheduler, id, delay);
272
- }
273
- return scheduler.flush(this);
274
- }
275
- }
276
-
277
- class QueueScheduler extends AsyncScheduler {
278
- }
279
-
280
- const queueScheduler = new QueueScheduler(QueueAction);
281
- const queue = queueScheduler;
282
-
283
- class ObserveOnSubscriber extends Subscriber {
284
- constructor(destination, scheduler, delay = 0) {
285
- super(destination);
286
- this.scheduler = scheduler;
287
- this.delay = delay;
288
- }
289
- static dispatch(arg) {
290
- const { notification, destination } = arg;
291
- notification.observe(destination);
292
- this.unsubscribe();
293
- }
294
- scheduleMessage(notification) {
295
- const destination = this.destination;
296
- destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
297
- }
298
- _next(value) {
299
- this.scheduleMessage(Notification.createNext(value));
300
- }
301
- _error(err) {
302
- this.scheduleMessage(Notification.createError(err));
303
- this.unsubscribe();
304
- }
305
- _complete() {
306
- this.scheduleMessage(Notification.createComplete());
307
- this.unsubscribe();
308
- }
309
- }
310
- class ObserveOnMessage {
311
- constructor(notification, destination) {
312
- this.notification = notification;
313
- this.destination = destination;
314
- }
315
- }
316
-
317
- class ReplaySubject extends Subject {
318
- constructor(bufferSize = Number.POSITIVE_INFINITY, windowTime = Number.POSITIVE_INFINITY, scheduler) {
319
- super();
320
- this.scheduler = scheduler;
321
- this._events = [];
322
- this._infiniteTimeWindow = false;
323
- this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
324
- this._windowTime = windowTime < 1 ? 1 : windowTime;
325
- if (windowTime === Number.POSITIVE_INFINITY) {
326
- this._infiniteTimeWindow = true;
327
- this.next = this.nextInfiniteTimeWindow;
328
- }
329
- else {
330
- this.next = this.nextTimeWindow;
331
- }
332
- }
333
- nextInfiniteTimeWindow(value) {
334
- if (!this.isStopped) {
335
- const _events = this._events;
336
- _events.push(value);
337
- if (_events.length > this._bufferSize) {
338
- _events.shift();
339
- }
340
- }
341
- super.next(value);
342
- }
343
- nextTimeWindow(value) {
344
- if (!this.isStopped) {
345
- this._events.push(new ReplayEvent(this._getNow(), value));
346
- this._trimBufferThenGetEvents();
347
- }
348
- super.next(value);
349
- }
350
- _subscribe(subscriber) {
351
- const _infiniteTimeWindow = this._infiniteTimeWindow;
352
- const _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
353
- const scheduler = this.scheduler;
354
- const len = _events.length;
355
- let subscription;
356
- if (this.closed) {
357
- throw new ObjectUnsubscribedError();
358
- }
359
- else if (this.isStopped || this.hasError) {
360
- subscription = Subscription.EMPTY;
361
- }
362
- else {
363
- this.observers.push(subscriber);
364
- subscription = new SubjectSubscription(this, subscriber);
365
- }
366
- if (scheduler) {
367
- subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler));
368
- }
369
- if (_infiniteTimeWindow) {
370
- for (let i = 0; i < len && !subscriber.closed; i++) {
371
- subscriber.next(_events[i]);
372
- }
373
- }
374
- else {
375
- for (let i = 0; i < len && !subscriber.closed; i++) {
376
- subscriber.next(_events[i].value);
377
- }
378
- }
379
- if (this.hasError) {
380
- subscriber.error(this.thrownError);
381
- }
382
- else if (this.isStopped) {
383
- subscriber.complete();
384
- }
385
- return subscription;
386
- }
387
- _getNow() {
388
- return (this.scheduler || queue).now();
389
- }
390
- _trimBufferThenGetEvents() {
391
- const now = this._getNow();
392
- const _bufferSize = this._bufferSize;
393
- const _windowTime = this._windowTime;
394
- const _events = this._events;
395
- const eventsCount = _events.length;
396
- let spliceCount = 0;
397
- while (spliceCount < eventsCount) {
398
- if ((now - _events[spliceCount].time) < _windowTime) {
399
- break;
400
- }
401
- spliceCount++;
402
- }
403
- if (eventsCount > _bufferSize) {
404
- spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
405
- }
406
- if (spliceCount > 0) {
407
- _events.splice(0, spliceCount);
408
- }
409
- return _events;
410
- }
411
- }
412
- class ReplayEvent {
413
- constructor(time, value) {
414
- this.time = time;
415
- this.value = value;
416
- }
417
- }
418
-
419
- function isObservable(obj) {
420
- return !!obj && (obj instanceof Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));
421
- }
422
-
423
- const ArgumentOutOfRangeErrorImpl = (() => {
424
- function ArgumentOutOfRangeErrorImpl() {
425
- Error.call(this);
426
- this.message = 'argument out of range';
427
- this.name = 'ArgumentOutOfRangeError';
428
- return this;
429
- }
430
- ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);
431
- return ArgumentOutOfRangeErrorImpl;
432
- })();
433
- const ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;
434
-
435
- function take(count) {
436
- return (source) => {
437
- if (count === 0) {
438
- return empty();
439
- }
440
- else {
441
- return source.lift(new TakeOperator(count));
442
- }
443
- };
444
- }
445
- class TakeOperator {
446
- constructor(total) {
447
- this.total = total;
448
- if (this.total < 0) {
449
- throw new ArgumentOutOfRangeError;
450
- }
451
- }
452
- call(subscriber, source) {
453
- return source.subscribe(new TakeSubscriber(subscriber, this.total));
454
- }
455
- }
456
- class TakeSubscriber extends Subscriber {
457
- constructor(destination, total) {
458
- super(destination);
459
- this.total = total;
460
- this.count = 0;
461
- }
462
- _next(value) {
463
- const total = this.total;
464
- const count = ++this.count;
465
- if (count <= total) {
466
- this.destination.next(value);
467
- if (count === total) {
468
- this.destination.complete();
469
- this.unsubscribe();
470
- }
471
- }
472
- }
473
- }
474
-
475
- function skip(count) {
476
- return (source) => source.lift(new SkipOperator(count));
477
- }
478
- class SkipOperator {
479
- constructor(total) {
480
- this.total = total;
481
- }
482
- call(subscriber, source) {
483
- return source.subscribe(new SkipSubscriber(subscriber, this.total));
484
- }
485
- }
486
- class SkipSubscriber extends Subscriber {
487
- constructor(destination, total) {
488
- super(destination);
489
- this.total = total;
490
- this.count = 0;
491
- }
492
- _next(x) {
493
- if (++this.count > this.total) {
494
- this.destination.next(x);
495
- }
496
- }
497
- }
498
-
499
- function switchMap(project, resultSelector) {
500
- if (typeof resultSelector === 'function') {
501
- return (source) => source.pipe(switchMap((a, i) => from(project(a, i)).pipe(map((b, ii) => resultSelector(a, b, i, ii)))));
502
- }
503
- return (source) => source.lift(new SwitchMapOperator(project));
504
- }
505
- class SwitchMapOperator {
506
- constructor(project) {
507
- this.project = project;
508
- }
509
- call(subscriber, source) {
510
- return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));
511
- }
512
- }
513
- class SwitchMapSubscriber extends SimpleOuterSubscriber {
514
- constructor(destination, project) {
515
- super(destination);
516
- this.project = project;
517
- this.index = 0;
518
- }
519
- _next(value) {
520
- let result;
521
- const index = this.index++;
522
- try {
523
- result = this.project(value, index);
524
- }
525
- catch (error) {
526
- this.destination.error(error);
527
- return;
528
- }
529
- this._innerSub(result);
530
- }
531
- _innerSub(result) {
532
- const innerSubscription = this.innerSubscription;
533
- if (innerSubscription) {
534
- innerSubscription.unsubscribe();
535
- }
536
- const innerSubscriber = new SimpleInnerSubscriber(this);
537
- const destination = this.destination;
538
- destination.add(innerSubscriber);
539
- this.innerSubscription = innerSubscribe(result, innerSubscriber);
540
- if (this.innerSubscription !== innerSubscriber) {
541
- destination.add(this.innerSubscription);
542
- }
543
- }
544
- _complete() {
545
- const { innerSubscription } = this;
546
- if (!innerSubscription || innerSubscription.closed) {
547
- super._complete();
548
- }
549
- this.unsubscribe();
550
- }
551
- _unsubscribe() {
552
- this.innerSubscription = undefined;
553
- }
554
- notifyComplete() {
555
- this.innerSubscription = undefined;
556
- if (this.isStopped) {
557
- super._complete();
558
- }
559
- }
560
- notifyNext(innerValue) {
561
- this.destination.next(innerValue);
562
- }
563
- }
564
-
565
- const currentAction = {
566
- type: null,
567
- entityIds: null,
568
- skip: false,
569
- payload: null
570
- };
571
- let customActionActive = false;
572
- function resetCustomAction() {
573
- customActionActive = false;
574
- }
575
- // public API for custom actions. Custom action always wins
576
- function logAction(type, entityIds, payload) {
577
- setAction(type, entityIds, payload);
578
- customActionActive = true;
579
- }
580
- function setAction(type, entityIds, payload) {
581
- if (customActionActive === false) {
582
- currentAction.type = type;
583
- currentAction.entityIds = entityIds;
584
- currentAction.payload = payload;
585
- }
586
- }
587
- function action(action, entityIds) {
588
- return function (target, propertyKey, descriptor) {
589
- const originalMethod = descriptor.value;
590
- descriptor.value = function (...args) {
591
- logAction(action, entityIds);
592
- return originalMethod.apply(this, args);
593
- };
594
- return descriptor;
595
- };
596
- }
597
-
598
- // @internal
599
- function hasEntity(entities, id) {
600
- return entities.hasOwnProperty(id);
601
- }
602
-
603
- // @internal
604
- function addEntities({ state, entities, idKey, options = {}, preAddEntity }) {
605
- let newEntities = {};
606
- let newIds = [];
607
- let hasNewEntities = false;
608
- for (const entity of entities) {
609
- if (hasEntity(state.entities, entity[idKey]) === false) {
610
- // evaluate the middleware first to support dynamic ids
611
- const current = preAddEntity(entity);
612
- const entityId = current[idKey];
613
- newEntities[entityId] = current;
614
- if (options.prepend)
615
- newIds.unshift(entityId);
616
- else
617
- newIds.push(entityId);
618
- hasNewEntities = true;
619
- }
620
- }
621
- return hasNewEntities
622
- ? {
623
- newState: Object.assign(Object.assign({}, state), { entities: Object.assign(Object.assign({}, state.entities), newEntities), ids: options.prepend ? [...newIds, ...state.ids] : [...state.ids, ...newIds] }),
624
- newIds
625
- }
626
- : null;
627
- }
628
-
629
- // @internal
630
- function isNil(v) {
631
- return v === null || v === undefined;
632
- }
633
-
634
- // @internal
635
- function coerceArray(value) {
636
- if (isNil(value)) {
637
- return [];
638
- }
639
- return Array.isArray(value) ? value : [value];
640
- }
641
-
642
- const DEFAULT_ID_KEY = 'id';
643
-
644
- var EntityActions;
645
- (function (EntityActions) {
646
- EntityActions["Set"] = "Set";
647
- EntityActions["Add"] = "Add";
648
- EntityActions["Update"] = "Update";
649
- EntityActions["Remove"] = "Remove";
650
- })(EntityActions || (EntityActions = {}));
651
-
652
- const isBrowser = typeof window !== 'undefined';
653
- const isNotBrowser = !isBrowser;
654
- // export const isNativeScript = typeof global !== 'undefined' && (<any>global).__runtimeVersion !== 'undefined'; TODO is this used?
655
- const hasLocalStorage = () => {
656
- try {
657
- return typeof localStorage !== 'undefined';
658
- }
659
- catch (_a) {
660
- return false;
661
- }
662
- };
663
- const hasSessionStorage = () => {
664
- try {
665
- return typeof sessionStorage !== 'undefined';
666
- }
667
- catch (_a) {
668
- return false;
669
- }
670
- };
671
-
672
- let __DEV__ = true;
673
- function enableAkitaProdMode() {
674
- __DEV__ = false;
675
- if (isBrowser) {
676
- delete window.$$stores;
677
- delete window.$$queries;
678
- }
679
- }
680
- // @internal
681
- function isDev() {
682
- return __DEV__;
683
- }
684
-
685
- // @internal
686
- function isObject(value) {
687
- const type = typeof value;
688
- return value != null && (type == 'object' || type == 'function');
689
- }
690
-
691
- // @internal
692
- function isArray(value) {
693
- return Array.isArray(value);
694
- }
695
-
696
- // @internal
697
- function getActiveEntities(idOrOptions, ids, currentActive) {
698
- let result;
699
- if (isArray(idOrOptions)) {
700
- result = idOrOptions;
701
- }
702
- else {
703
- if (isObject(idOrOptions)) {
704
- if (isNil(currentActive))
705
- return;
706
- idOrOptions = Object.assign({ wrap: true }, idOrOptions);
707
- const currentIdIndex = ids.indexOf(currentActive);
708
- if (idOrOptions.prev) {
709
- const isFirst = currentIdIndex === 0;
710
- if (isFirst && !idOrOptions.wrap)
711
- return;
712
- result = isFirst ? ids[ids.length - 1] : ids[currentIdIndex - 1];
713
- }
714
- else if (idOrOptions.next) {
715
- const isLast = ids.length === currentIdIndex + 1;
716
- if (isLast && !idOrOptions.wrap)
717
- return;
718
- result = isLast ? ids[0] : ids[currentIdIndex + 1];
719
- }
720
- }
721
- else {
722
- if (idOrOptions === currentActive)
723
- return;
724
- result = idOrOptions;
725
- }
726
- }
727
- return result;
728
- }
729
-
730
- // @internal
731
- const getInitialEntitiesState = () => ({
732
- entities: {},
733
- ids: [],
734
- loading: true,
735
- error: null
736
- });
737
-
738
- // @internal
739
- function isDefined(val) {
740
- return isNil(val) === false;
741
- }
742
-
743
- // @internal
744
- function isEmpty(arr) {
745
- if (isArray(arr)) {
746
- return arr.length === 0;
747
- }
748
- return false;
749
- }
750
-
751
- // @internal
752
- function isFunction(value) {
753
- return typeof value === 'function';
754
- }
755
-
756
- // @internal
757
- function isUndefined(value) {
758
- return value === undefined;
759
- }
760
-
761
- // @internal
762
- function hasActiveState(state) {
763
- return state.hasOwnProperty('active');
764
- }
765
- // @internal
766
- function isMultiActiveState(active) {
767
- return isArray(active);
768
- }
769
- // @internal
770
- function resolveActiveEntity({ active, ids, entities }) {
771
- if (isMultiActiveState(active)) {
772
- return getExitingActives(active, ids);
773
- }
774
- if (hasEntity(entities, active) === false) {
775
- return null;
776
- }
777
- return active;
778
- }
779
- // @internal
780
- function getExitingActives(currentActivesIds, newIds) {
781
- const filtered = currentActivesIds.filter(id => newIds.indexOf(id) > -1);
782
- /** Return the same reference if nothing has changed */
783
- if (filtered.length === currentActivesIds.length) {
784
- return currentActivesIds;
785
- }
786
- return filtered;
787
- }
788
-
789
- // @internal
790
- function removeEntities({ state, ids }) {
791
- if (isNil(ids))
792
- return removeAllEntities(state);
793
- const entities = state.entities;
794
- let newEntities = {};
795
- for (const id of state.ids) {
796
- if (ids.includes(id) === false) {
797
- newEntities[id] = entities[id];
798
- }
799
- }
800
- const newState = Object.assign(Object.assign({}, state), { entities: newEntities, ids: state.ids.filter(current => ids.includes(current) === false) });
801
- if (hasActiveState(state)) {
802
- newState.active = resolveActiveEntity(newState);
803
- }
804
- return newState;
805
- }
806
- // @internal
807
- function removeAllEntities(state) {
808
- return Object.assign(Object.assign({}, state), { entities: {}, ids: [], active: isMultiActiveState(state.active) ? [] : null });
809
- }
810
-
811
- // @internal
812
- function toEntitiesObject(entities, idKey, preAddEntity) {
813
- const acc = {
814
- entities: {},
815
- ids: []
816
- };
817
- for (const entity of entities) {
818
- // evaluate the middleware first to support dynamic ids
819
- const current = preAddEntity(entity);
820
- acc.entities[current[idKey]] = current;
821
- acc.ids.push(current[idKey]);
822
- }
823
- return acc;
824
- }
825
-
826
- // @internal
827
- function isEntityState(state) {
828
- return state.entities && state.ids;
829
- }
830
- // @internal
831
- function applyMiddleware(entities, preAddEntity) {
832
- let mapped = {};
833
- for (const id of Object.keys(entities)) {
834
- mapped[id] = preAddEntity(entities[id]);
835
- }
836
- return mapped;
837
- }
838
- // @internal
839
- function setEntities({ state, entities, idKey, preAddEntity, isNativePreAdd }) {
840
- let newEntities;
841
- let newIds;
842
- if (isArray(entities)) {
843
- const resolve = toEntitiesObject(entities, idKey, preAddEntity);
844
- newEntities = resolve.entities;
845
- newIds = resolve.ids;
846
- }
847
- else if (isEntityState(entities)) {
848
- newEntities = isNativePreAdd ? entities.entities : applyMiddleware(entities.entities, preAddEntity);
849
- newIds = entities.ids;
850
- }
851
- else {
852
- // it's an object
853
- newEntities = isNativePreAdd ? entities : applyMiddleware(entities, preAddEntity);
854
- newIds = Object.keys(newEntities).map(id => (isNaN(id) ? id : Number(id)));
855
- }
856
- const newState = Object.assign(Object.assign({}, state), { entities: newEntities, ids: newIds, loading: false });
857
- if (hasActiveState(state)) {
858
- newState.active = resolveActiveEntity(newState);
859
- }
860
- return newState;
861
- }
862
-
863
- let CONFIG = {
864
- resettable: false,
865
- ttl: null,
866
- producerFn: undefined
867
- };
868
- // @internal
869
- function getAkitaConfig() {
870
- return CONFIG;
871
- }
872
- function getGlobalProducerFn() {
873
- return CONFIG.producerFn;
874
- }
875
-
876
- // @internal
877
- function deepFreeze(o) {
878
- Object.freeze(o);
879
- const oIsFunction = typeof o === 'function';
880
- const hasOwnProp = Object.prototype.hasOwnProperty;
881
- Object.getOwnPropertyNames(o).forEach(function (prop) {
882
- if (hasOwnProp.call(o, prop) &&
883
- (oIsFunction ? prop !== 'caller' && prop !== 'callee' && prop !== 'arguments' : true) &&
884
- o[prop] !== null &&
885
- (typeof o[prop] === 'object' || typeof o[prop] === 'function') &&
886
- !Object.isFrozen(o[prop])) {
887
- deepFreeze(o[prop]);
888
- }
889
- });
890
- return o;
891
- }
892
-
893
- // @internal
894
- const $$deleteStore = new Subject();
895
- // @internal
896
- const $$addStore = new ReplaySubject(50, 5000);
897
- // @internal
898
- const $$updateStore = new Subject();
899
- // @internal
900
- function dispatchDeleted(storeName) {
901
- $$deleteStore.next(storeName);
902
- }
903
- // @internal
904
- function dispatchAdded(storeName) {
905
- $$addStore.next(storeName);
906
- }
907
- // @internal
908
- function dispatchUpdate(storeName, action) {
909
- $$updateStore.next({ storeName, action });
910
- }
911
- // @internal
912
- function assertStoreHasName(name, className) {
913
- if (!name) {
914
- console.error(`@StoreConfig({ name }) is missing in ${className}`);
915
- }
916
- }
917
-
918
- // @internal
919
- function toBoolean(value) {
920
- return value != null && `${value}` !== 'false';
921
- }
922
-
923
- // @internal
924
- function isPlainObject(value) {
925
- return toBoolean(value) && value.constructor.name === 'Object';
926
- }
927
-
928
- const configKey = 'akitaConfig';
929
- function StoreConfig(metadata) {
930
- return function (constructor) {
931
- constructor[configKey] = { idKey: 'id' };
932
- for (let i = 0, keys = Object.keys(metadata); i < keys.length; i++) {
933
- const key = keys[i];
934
- /* name is preserved read only key */
935
- if (key === 'name') {
936
- constructor[configKey]['storeName'] = metadata[key];
937
- }
938
- else {
939
- constructor[configKey][key] = metadata[key];
940
- }
941
- }
942
- };
943
- }
944
-
945
- // @internal
946
- const __stores__ = {};
947
- // @internal
948
- const __queries__ = {};
949
- if (isBrowser) {
950
- window.$$stores = __stores__;
951
- window.$$queries = __queries__;
952
- }
953
-
954
- // @internal
955
- const transactionFinished = new Subject();
956
- // @internal
957
- const transactionInProcess = new BehaviorSubject(false);
958
- // @internal
959
- const transactionManager = {
960
- activeTransactions: 0,
961
- batchTransaction: null
962
- };
963
- // @internal
964
- function startBatch() {
965
- if (!isTransactionInProcess()) {
966
- transactionManager.batchTransaction = new Subject();
967
- }
968
- transactionManager.activeTransactions++;
969
- transactionInProcess.next(true);
970
- }
971
- // @internal
972
- function endBatch() {
973
- if (--transactionManager.activeTransactions === 0) {
974
- transactionManager.batchTransaction.next(true);
975
- transactionManager.batchTransaction.complete();
976
- transactionInProcess.next(false);
977
- transactionFinished.next(true);
978
- }
979
- }
980
- // @internal
981
- function isTransactionInProcess() {
982
- return transactionManager.activeTransactions > 0;
983
- }
984
- // @internal
985
- function commit() {
986
- return transactionManager.batchTransaction ? transactionManager.batchTransaction.asObservable() : of(true);
987
- }
988
- /**
989
- * A logical transaction.
990
- * Use this transaction to optimize the dispatch of all the stores.
991
- * The following code will update the store, BUT emits only once
992
- *
993
- * @example
994
- * applyTransaction(() => {
995
- * this.todosStore.add(new Todo(1, title));
996
- * this.todosStore.add(new Todo(2, title));
997
- * });
998
- *
999
- */
1000
- function applyTransaction(action, thisArg = undefined) {
1001
- startBatch();
1002
- try {
1003
- return action.apply(thisArg);
1004
- }
1005
- finally {
1006
- logAction('@Transaction');
1007
- endBatch();
1008
- }
1009
- }
1010
- /**
1011
- * A logical transaction.
1012
- * Use this transaction to optimize the dispatch of all the stores.
1013
- *
1014
- * The following code will update the store, BUT emits only once.
1015
- *
1016
- * @example
1017
- * @transaction
1018
- * addTodos() {
1019
- * this.todosStore.add(new Todo(1, title));
1020
- * this.todosStore.add(new Todo(2, title));
1021
- * }
1022
- *
1023
- *
1024
- */
1025
- function transaction() {
1026
- return function (target, propertyKey, descriptor) {
1027
- const originalMethod = descriptor.value;
1028
- descriptor.value = function (...args) {
1029
- return applyTransaction(() => {
1030
- return originalMethod.apply(this, args);
1031
- }, this);
1032
- };
1033
- return descriptor;
1034
- };
1035
- }
1036
-
1037
- /**
1038
- *
1039
- * Store for managing any type of data
1040
- *
1041
- * @example
1042
- *
1043
- * export interface SessionState {
1044
- * token: string;
1045
- * userDetails: UserDetails
1046
- * }
1047
- *
1048
- * export function createInitialState(): SessionState {
1049
- * return {
1050
- * token: '',
1051
- * userDetails: null
1052
- * };
1053
- * }
1054
- *
1055
- * @StoreConfig({ name: 'session' })
1056
- * export class SessionStore extends Store<SessionState> {
1057
- * constructor() {
1058
- * super(createInitialState());
1059
- * }
1060
- * }
1061
- */
1062
- class Store {
1063
- constructor(initialState, options = {}) {
1064
- this.options = options;
1065
- this.inTransaction = false;
1066
- this.cache = {
1067
- active: new BehaviorSubject(false),
1068
- ttl: null,
1069
- };
1070
- this.onInit(initialState);
1071
- }
1072
- /**
1073
- * Set the loading state
1074
- *
1075
- * @example
1076
- *
1077
- * store.setLoading(true)
1078
- *
1079
- */
1080
- setLoading(loading = false) {
1081
- if (loading !== this._value().loading) {
1082
- isDev() && setAction('Set Loading');
1083
- this._setState((state) => (Object.assign(Object.assign({}, state), { loading })));
1084
- }
1085
- }
1086
- /**
1087
- *
1088
- * Set whether the data is cached
1089
- *
1090
- * @example
1091
- *
1092
- * store.setHasCache(true)
1093
- * store.setHasCache(false)
1094
- * store.setHasCache(true, { restartTTL: true })
1095
- *
1096
- */
1097
- setHasCache(hasCache, options = { restartTTL: false }) {
1098
- if (hasCache !== this.cache.active.value) {
1099
- this.cache.active.next(hasCache);
1100
- }
1101
- if (options.restartTTL) {
1102
- const ttlConfig = this.getCacheTTL();
1103
- if (ttlConfig) {
1104
- if (this.cache.ttl !== null) {
1105
- clearTimeout(this.cache.ttl);
1106
- }
1107
- this.cache.ttl = setTimeout(() => this.setHasCache(false), ttlConfig);
1108
- }
1109
- }
1110
- }
1111
- /**
1112
- *
1113
- * Sometimes we need to access the store value from a store
1114
- *
1115
- * @example middleware
1116
- *
1117
- */
1118
- getValue() {
1119
- return this.storeValue;
1120
- }
1121
- /**
1122
- * Set the error state
1123
- *
1124
- * @example
1125
- *
1126
- * store.setError({text: 'unable to load data' })
1127
- *
1128
- */
1129
- setError(error) {
1130
- if (error !== this._value().error) {
1131
- isDev() && setAction('Set Error');
1132
- this._setState((state) => (Object.assign(Object.assign({}, state), { error })));
1133
- }
1134
- }
1135
- // @internal
1136
- _select(project) {
1137
- return this.store.asObservable().pipe(map((snapshot) => project(snapshot.state)), distinctUntilChanged());
1138
- }
1139
- // @internal
1140
- _value() {
1141
- return this.storeValue;
1142
- }
1143
- // @internal
1144
- _cache() {
1145
- return this.cache.active;
1146
- }
1147
- // @internal
1148
- get config() {
1149
- return this.constructor[configKey] || {};
1150
- }
1151
- // @internal
1152
- get storeName() {
1153
- return this.config.storeName || this.options.storeName || this.options.name;
1154
- }
1155
- // @internal
1156
- get deepFreeze() {
1157
- return this.config.deepFreezeFn || this.options.deepFreezeFn || deepFreeze;
1158
- }
1159
- // @internal
1160
- get cacheConfig() {
1161
- return this.config.cache || this.options.cache;
1162
- }
1163
- get _producerFn() {
1164
- return this.config.producerFn || this.options.producerFn || getGlobalProducerFn();
1165
- }
1166
- // @internal
1167
- get resettable() {
1168
- return isDefined(this.config.resettable) ? this.config.resettable : this.options.resettable;
1169
- }
1170
- // @internal
1171
- _setState(newState, _dispatchAction = true) {
1172
- if (isFunction(newState)) {
1173
- const _newState = newState(this._value());
1174
- this.storeValue = __DEV__ ? this.deepFreeze(_newState) : _newState;
1175
- }
1176
- else {
1177
- this.storeValue = newState;
1178
- }
1179
- if (!this.store) {
1180
- this.store = new BehaviorSubject({ state: this.storeValue });
1181
- if (isDev()) {
1182
- this.store.subscribe(({ action }) => {
1183
- if (action) {
1184
- dispatchUpdate(this.storeName, action);
1185
- }
1186
- });
1187
- }
1188
- return;
1189
- }
1190
- if (isTransactionInProcess()) {
1191
- this.handleTransaction();
1192
- return;
1193
- }
1194
- this.dispatch(this.storeValue, _dispatchAction);
1195
- }
1196
- /**
1197
- *
1198
- * Reset the current store back to the initial value
1199
- *
1200
- * @example
1201
- *
1202
- * store.reset()
1203
- *
1204
- */
1205
- reset() {
1206
- if (this.isResettable()) {
1207
- isDev() && setAction('Reset');
1208
- this._setState(() => Object.assign({}, this._initialState));
1209
- this.setHasCache(false);
1210
- }
1211
- else {
1212
- isDev() && console.warn(`You need to enable the reset functionality`);
1213
- }
1214
- }
1215
- update(stateOrCallback) {
1216
- isDev() && setAction('Update');
1217
- let newState;
1218
- const currentState = this._value();
1219
- if (isFunction(stateOrCallback)) {
1220
- newState = isFunction(this._producerFn) ? this._producerFn(currentState, stateOrCallback) : stateOrCallback(currentState);
1221
- }
1222
- else {
1223
- newState = stateOrCallback;
1224
- }
1225
- const withHook = this.akitaPreUpdate(currentState, Object.assign(Object.assign({}, currentState), newState));
1226
- const resolved = isPlainObject(currentState) ? withHook : new currentState.constructor(withHook);
1227
- this._setState(resolved);
1228
- }
1229
- updateStoreConfig(newOptions) {
1230
- this.options = Object.assign(Object.assign({}, this.options), newOptions);
1231
- }
1232
- // @internal
1233
- akitaPreUpdate(_, nextState) {
1234
- return nextState;
1235
- }
1236
- ngOnDestroy() {
1237
- this.destroy();
1238
- }
1239
- /**
1240
- *
1241
- * Destroy the store
1242
- *
1243
- * @example
1244
- *
1245
- * store.destroy()
1246
- *
1247
- */
1248
- destroy() {
1249
- const hmrEnabled = isBrowser ? window.hmrEnabled : false;
1250
- if (!hmrEnabled && this === __stores__[this.storeName]) {
1251
- delete __stores__[this.storeName];
1252
- dispatchDeleted(this.storeName);
1253
- this.setHasCache(false);
1254
- this.cache.active.complete();
1255
- this.store.complete();
1256
- }
1257
- }
1258
- onInit(initialState) {
1259
- __stores__[this.storeName] = this;
1260
- this._setState(() => initialState);
1261
- dispatchAdded(this.storeName);
1262
- if (this.isResettable()) {
1263
- this._initialState = initialState;
1264
- }
1265
- isDev() && assertStoreHasName(this.storeName, this.constructor.name);
1266
- }
1267
- dispatch(state, _dispatchAction = true) {
1268
- let action = undefined;
1269
- if (_dispatchAction) {
1270
- action = currentAction;
1271
- resetCustomAction();
1272
- }
1273
- this.store.next({ state, action });
1274
- }
1275
- watchTransaction() {
1276
- commit().subscribe(() => {
1277
- this.inTransaction = false;
1278
- this.dispatch(this._value());
1279
- });
1280
- }
1281
- isResettable() {
1282
- if (this.resettable === false) {
1283
- return false;
1284
- }
1285
- return this.resettable || getAkitaConfig().resettable;
1286
- }
1287
- handleTransaction() {
1288
- if (!this.inTransaction) {
1289
- this.watchTransaction();
1290
- this.inTransaction = true;
1291
- }
1292
- }
1293
- getCacheTTL() {
1294
- return (this.cacheConfig && this.cacheConfig.ttl) || getAkitaConfig().ttl;
1295
- }
1296
- }
1297
-
1298
- // @internal
1299
- function updateEntities({ state, ids, idKey, newStateOrFn, preUpdateEntity, producerFn, onEntityIdChanges }) {
1300
- const updatedEntities = {};
1301
- let isUpdatingIdKey = false;
1302
- let idToUpdate;
1303
- for (const id of ids) {
1304
- // if the entity doesn't exist don't do anything
1305
- if (hasEntity(state.entities, id) === false) {
1306
- continue;
1307
- }
1308
- const oldEntity = state.entities[id];
1309
- let newState;
1310
- if (isFunction(newStateOrFn)) {
1311
- newState = isFunction(producerFn) ? producerFn(oldEntity, newStateOrFn) : newStateOrFn(oldEntity);
1312
- }
1313
- else {
1314
- newState = newStateOrFn;
1315
- }
1316
- const isIdChanged = newState.hasOwnProperty(idKey) && newState[idKey] !== oldEntity[idKey];
1317
- let newEntity;
1318
- idToUpdate = id;
1319
- if (isIdChanged) {
1320
- isUpdatingIdKey = true;
1321
- idToUpdate = newState[idKey];
1322
- }
1323
- const merged = Object.assign(Object.assign({}, oldEntity), newState);
1324
- if (isPlainObject(oldEntity)) {
1325
- newEntity = merged;
1326
- }
1327
- else {
1328
- /**
1329
- * In case that new state is class of it's own, there's
1330
- * a possibility that it will be different than the old
1331
- * class.
1332
- * For example, Old state is an instance of animal class
1333
- * and new state is instance of person class.
1334
- * To avoid run over new person class with the old animal
1335
- * class we check if the new state is a class of it's own.
1336
- * If so, use it. Otherwise, use the old state class
1337
- */
1338
- if (isPlainObject(newState)) {
1339
- newEntity = new oldEntity.constructor(merged);
1340
- }
1341
- else {
1342
- newEntity = new newState.constructor(merged);
1343
- }
1344
- }
1345
- updatedEntities[idToUpdate] = preUpdateEntity(oldEntity, newEntity);
1346
- }
1347
- let updatedIds = state.ids;
1348
- let stateEntities = state.entities;
1349
- if (isUpdatingIdKey) {
1350
- const [id] = ids;
1351
- const _a = state.entities, _b = id, rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
1352
- stateEntities = rest;
1353
- updatedIds = state.ids.map((current) => (current === id ? idToUpdate : current));
1354
- onEntityIdChanges(id, idToUpdate);
1355
- }
1356
- return Object.assign(Object.assign({}, state), { entities: Object.assign(Object.assign({}, stateEntities), updatedEntities), ids: updatedIds });
1357
- }
1358
-
1359
- var _b;
1360
- /**
1361
- *
1362
- * Store for managing a collection of entities
1363
- *
1364
- * @example
1365
- *
1366
- * export interface WidgetsState extends EntityState<Widget> { }
1367
- *
1368
- * @StoreConfig({ name: 'widgets' })
1369
- * export class WidgetsStore extends EntityStore<WidgetsState> {
1370
- * constructor() {
1371
- * super();
1372
- * }
1373
- * }
1374
- *
1375
- *
1376
- */
1377
- class EntityStore extends Store {
1378
- constructor(initialState = {}, options = {}) {
1379
- super(Object.assign(Object.assign({}, getInitialEntitiesState()), initialState), options);
1380
- this.options = options;
1381
- this.entityActions = new Subject();
1382
- this.entityIdChanges = new Subject();
1383
- }
1384
- // @internal
1385
- get selectEntityAction$() {
1386
- return this.entityActions.asObservable();
1387
- }
1388
- // @internal
1389
- get selectEntityIdChanges$() {
1390
- return this.entityIdChanges.asObservable();
1391
- }
1392
- // @internal
1393
- get idKey() {
1394
- return this.config.idKey || this.options.idKey || DEFAULT_ID_KEY;
1395
- }
1396
- /**
1397
- *
1398
- * Replace current collection with provided collection
1399
- *
1400
- * @example
1401
- *
1402
- * this.store.set([Entity, Entity])
1403
- * this.store.set({ids: [], entities: {}})
1404
- * this.store.set({ 1: {}, 2: {}})
1405
- *
1406
- */
1407
- set(entities, options = {}) {
1408
- if (isNil(entities))
1409
- return;
1410
- isDev() && setAction('Set Entity');
1411
- const isNativePreAdd = this.akitaPreAddEntity === EntityStore.prototype.akitaPreAddEntity;
1412
- this.setHasCache(true, { restartTTL: true });
1413
- this._setState((state) => {
1414
- const newState = setEntities({
1415
- state,
1416
- entities,
1417
- idKey: this.idKey,
1418
- preAddEntity: this.akitaPreAddEntity,
1419
- isNativePreAdd,
1420
- });
1421
- if (isUndefined(options.activeId) === false) {
1422
- newState.active = options.activeId;
1423
- }
1424
- return newState;
1425
- });
1426
- if (this.hasInitialUIState()) {
1427
- this.handleUICreation();
1428
- }
1429
- this.entityActions.next({ type: EntityActions.Set, ids: this.ids });
1430
- }
1431
- /**
1432
- * Add entities
1433
- *
1434
- * @example
1435
- *
1436
- * this.store.add([Entity, Entity])
1437
- * this.store.add(Entity)
1438
- * this.store.add(Entity, { prepend: true })
1439
- *
1440
- * this.store.add(Entity, { loading: false })
1441
- */
1442
- add(entities, options = { loading: false }) {
1443
- const collection = coerceArray(entities);
1444
- if (isEmpty(collection))
1445
- return;
1446
- const data = addEntities({
1447
- state: this._value(),
1448
- preAddEntity: this.akitaPreAddEntity,
1449
- entities: collection,
1450
- idKey: this.idKey,
1451
- options,
1452
- });
1453
- if (data) {
1454
- isDev() && setAction('Add Entity');
1455
- data.newState.loading = options.loading;
1456
- this._setState(() => data.newState);
1457
- if (this.hasInitialUIState()) {
1458
- this.handleUICreation(true);
1459
- }
1460
- this.entityActions.next({ type: EntityActions.Add, ids: data.newIds });
1461
- }
1462
- }
1463
- update(idsOrFnOrState, newStateOrFn) {
1464
- if (isUndefined(newStateOrFn)) {
1465
- super.update(idsOrFnOrState);
1466
- return;
1467
- }
1468
- let ids = [];
1469
- if (isFunction(idsOrFnOrState)) {
1470
- // We need to filter according the predicate function
1471
- ids = this.ids.filter((id) => idsOrFnOrState(this.entities[id]));
1472
- }
1473
- else {
1474
- // If it's nil we want all of them
1475
- ids = isNil(idsOrFnOrState) ? this.ids : coerceArray(idsOrFnOrState);
1476
- }
1477
- if (isEmpty(ids))
1478
- return;
1479
- isDev() && setAction('Update Entity', ids);
1480
- let entityIdChanged;
1481
- this._setState((state) => updateEntities({
1482
- idKey: this.idKey,
1483
- ids,
1484
- preUpdateEntity: this.akitaPreUpdateEntity,
1485
- state,
1486
- newStateOrFn,
1487
- producerFn: this._producerFn,
1488
- onEntityIdChanges: (oldId, newId) => {
1489
- entityIdChanged = { oldId, newId };
1490
- this.entityIdChanges.next(Object.assign(Object.assign({}, entityIdChanged), { pending: true }));
1491
- },
1492
- }));
1493
- if (entityIdChanged) {
1494
- this.entityIdChanges.next(Object.assign(Object.assign({}, entityIdChanged), { pending: false }));
1495
- }
1496
- this.entityActions.next({ type: EntityActions.Update, ids });
1497
- }
1498
- upsert(ids, newState, onCreate, options = {}) {
1499
- const toArray = coerceArray(ids);
1500
- const predicate = (isUpdate) => (id) => hasEntity(this.entities, id) === isUpdate;
1501
- const baseClass = isFunction(onCreate) ? options.baseClass : onCreate ? onCreate.baseClass : undefined;
1502
- const isClassBased = isFunction(baseClass);
1503
- const updateIds = toArray.filter(predicate(true));
1504
- const newEntities = toArray.filter(predicate(false)).map((id) => {
1505
- const newStateObj = typeof newState === 'function' ? newState({}) : newState;
1506
- const entity = isFunction(onCreate) ? onCreate(id, newStateObj) : newStateObj;
1507
- const withId = Object.assign(Object.assign({}, entity), { [this.idKey]: id });
1508
- if (isClassBased) {
1509
- return new baseClass(withId);
1510
- }
1511
- return withId;
1512
- });
1513
- // it can be any of the three types
1514
- this.update(updateIds, newState);
1515
- this.add(newEntities);
1516
- isDev() && logAction('Upsert Entity');
1517
- }
1518
- /**
1519
- *
1520
- * Upsert entity collection (idKey must be present)
1521
- *
1522
- * @example
1523
- *
1524
- * store.upsertMany([ { id: 1 }, { id: 2 }]);
1525
- *
1526
- * store.upsertMany([ { id: 1 }, { id: 2 }], { loading: true });
1527
- * store.upsertMany([ { id: 1 }, { id: 2 }], { baseClass: Todo });
1528
- *
1529
- */
1530
- upsertMany(entities, options = {}) {
1531
- const addedIds = [];
1532
- const updatedIds = [];
1533
- const updatedEntities = {};
1534
- // Update the state directly to optimize performance
1535
- for (const entity of entities) {
1536
- const withPreCheckHook = this.akitaPreCheckEntity(entity);
1537
- const id = withPreCheckHook[this.idKey];
1538
- if (hasEntity(this.entities, id)) {
1539
- const prev = this._value().entities[id];
1540
- const merged = Object.assign(Object.assign({}, this._value().entities[id]), withPreCheckHook);
1541
- const next = options.baseClass ? new options.baseClass(merged) : merged;
1542
- const withHook = this.akitaPreUpdateEntity(prev, next);
1543
- const nextId = withHook[this.idKey];
1544
- updatedEntities[nextId] = withHook;
1545
- updatedIds.push(nextId);
1546
- }
1547
- else {
1548
- const newEntity = options.baseClass ? new options.baseClass(withPreCheckHook) : withPreCheckHook;
1549
- const withHook = this.akitaPreAddEntity(newEntity);
1550
- const nextId = withHook[this.idKey];
1551
- addedIds.push(nextId);
1552
- updatedEntities[nextId] = withHook;
1553
- }
1554
- }
1555
- isDev() && logAction('Upsert Many');
1556
- this._setState((state) => (Object.assign(Object.assign({}, state), { ids: addedIds.length ? [...state.ids, ...addedIds] : state.ids, entities: Object.assign(Object.assign({}, state.entities), updatedEntities), loading: !!options.loading })));
1557
- updatedIds.length && this.entityActions.next({ type: EntityActions.Update, ids: updatedIds });
1558
- addedIds.length && this.entityActions.next({ type: EntityActions.Add, ids: addedIds });
1559
- if (addedIds.length && this.hasUIStore()) {
1560
- this.handleUICreation(true);
1561
- }
1562
- }
1563
- /**
1564
- *
1565
- * Replace one or more entities (except the id property)
1566
- *
1567
- *
1568
- * @example
1569
- *
1570
- * this.store.replace(5, newEntity)
1571
- * this.store.replace([1,2,3], newEntity)
1572
- */
1573
- replace(ids, newState) {
1574
- const toArray = coerceArray(ids);
1575
- if (isEmpty(toArray))
1576
- return;
1577
- let replaced = {};
1578
- for (const id of toArray) {
1579
- newState[this.idKey] = id;
1580
- replaced[id] = newState;
1581
- }
1582
- isDev() && setAction('Replace Entity', ids);
1583
- this._setState((state) => (Object.assign(Object.assign({}, state), { entities: Object.assign(Object.assign({}, state.entities), replaced) })));
1584
- }
1585
- /**
1586
- *
1587
- * Move entity inside the collection
1588
- *
1589
- *
1590
- * @example
1591
- *
1592
- * this.store.move(fromIndex, toIndex)
1593
- */
1594
- move(from, to) {
1595
- const ids = this.ids.slice();
1596
- ids.splice(to < 0 ? ids.length + to : to, 0, ids.splice(from, 1)[0]);
1597
- isDev() && setAction('Move Entity');
1598
- this._setState((state) => (Object.assign(Object.assign({}, state), {
1599
- // Change the entities reference so that selectAll emit
1600
- entities: Object.assign({}, state.entities), ids })));
1601
- }
1602
- remove(idsOrFn) {
1603
- if (isEmpty(this.ids))
1604
- return;
1605
- const idPassed = isDefined(idsOrFn);
1606
- // null means remove all
1607
- let ids = [];
1608
- if (isFunction(idsOrFn)) {
1609
- ids = this.ids.filter((entityId) => idsOrFn(this.entities[entityId]));
1610
- }
1611
- else {
1612
- ids = idPassed ? coerceArray(idsOrFn) : this.ids;
1613
- }
1614
- if (isEmpty(ids))
1615
- return;
1616
- isDev() && setAction('Remove Entity', ids);
1617
- this._setState((state) => removeEntities({ state, ids }));
1618
- if (!idPassed) {
1619
- this.setHasCache(false);
1620
- }
1621
- this.handleUIRemove(ids);
1622
- this.entityActions.next({ type: EntityActions.Remove, ids });
1623
- }
1624
- /**
1625
- *
1626
- * Update the active entity
1627
- *
1628
- * @example
1629
- *
1630
- * this.store.updateActive({ completed: true })
1631
- * this.store.updateActive(active => {
1632
- * return {
1633
- * config: {
1634
- * ..active.config,
1635
- * date
1636
- * }
1637
- * }
1638
- * })
1639
- */
1640
- updateActive(newStateOrCallback) {
1641
- const ids = coerceArray(this.active);
1642
- isDev() && setAction('Update Active', ids);
1643
- this.update(ids, newStateOrCallback);
1644
- }
1645
- setActive(idOrOptions) {
1646
- const active = getActiveEntities(idOrOptions, this.ids, this.active);
1647
- if (active === undefined) {
1648
- return;
1649
- }
1650
- isDev() && setAction('Set Active', active);
1651
- this._setActive(active);
1652
- }
1653
- /**
1654
- * Add active entities
1655
- *
1656
- * @example
1657
- *
1658
- * store.addActive(2);
1659
- * store.addActive([3, 4, 5]);
1660
- */
1661
- addActive(ids) {
1662
- const toArray = coerceArray(ids);
1663
- if (isEmpty(toArray))
1664
- return;
1665
- const everyExist = toArray.every((id) => this.active.indexOf(id) > -1);
1666
- if (everyExist)
1667
- return;
1668
- isDev() && setAction('Add Active', ids);
1669
- this._setState((state) => {
1670
- /** Protect against case that one of the items in the array exist */
1671
- const uniques = Array.from(new Set([...state.active, ...toArray]));
1672
- return Object.assign(Object.assign({}, state), { active: uniques });
1673
- });
1674
- }
1675
- /**
1676
- * Remove active entities
1677
- *
1678
- * @example
1679
- *
1680
- * store.removeActive(2)
1681
- * store.removeActive([3, 4, 5])
1682
- */
1683
- removeActive(ids) {
1684
- const toArray = coerceArray(ids);
1685
- if (isEmpty(toArray))
1686
- return;
1687
- const someExist = toArray.some((id) => this.active.indexOf(id) > -1);
1688
- if (!someExist)
1689
- return;
1690
- isDev() && setAction('Remove Active', ids);
1691
- this._setState((state) => {
1692
- return Object.assign(Object.assign({}, state), { active: Array.isArray(state.active) ? state.active.filter((currentId) => toArray.indexOf(currentId) === -1) : null });
1693
- });
1694
- }
1695
- /**
1696
- * Toggle active entities
1697
- *
1698
- * @example
1699
- *
1700
- * store.toggle(2)
1701
- * store.toggle([3, 4, 5])
1702
- */
1703
- toggleActive(ids) {
1704
- const toArray = coerceArray(ids);
1705
- const filterExists = (remove) => (id) => this.active.includes(id) === remove;
1706
- const remove = toArray.filter(filterExists(true));
1707
- const add = toArray.filter(filterExists(false));
1708
- this.removeActive(remove);
1709
- this.addActive(add);
1710
- isDev() && logAction('Toggle Active');
1711
- }
1712
- /**
1713
- *
1714
- * Create sub UI store for managing Entity's UI state
1715
- *
1716
- * @example
1717
- *
1718
- * export type ProductUI = {
1719
- * isLoading: boolean;
1720
- * isOpen: boolean
1721
- * }
1722
- *
1723
- * interface ProductsUIState extends EntityState<ProductUI> {}
1724
- *
1725
- * export class ProductsStore EntityStore<ProductsState, Product> {
1726
- * ui: EntityUIStore<ProductsUIState, ProductUI>;
1727
- *
1728
- * constructor() {
1729
- * super();
1730
- * this.createUIStore();
1731
- * }
1732
- *
1733
- * }
1734
- */
1735
- createUIStore(initialState = {}, storeConfig = {}) {
1736
- const defaults = { name: `UI/${this.storeName}`, idKey: this.idKey };
1737
- this.ui = new EntityUIStore(initialState, Object.assign(Object.assign({}, defaults), storeConfig));
1738
- return this.ui;
1739
- }
1740
- // @internal
1741
- destroy() {
1742
- super.destroy();
1743
- if (this.ui instanceof EntityStore) {
1744
- this.ui.destroy();
1745
- }
1746
- this.entityActions.complete();
1747
- }
1748
- // @internal
1749
- akitaPreUpdateEntity(_, nextEntity) {
1750
- return nextEntity;
1751
- }
1752
- // @internal
1753
- akitaPreAddEntity(newEntity) {
1754
- return newEntity;
1755
- }
1756
- // @internal
1757
- akitaPreCheckEntity(newEntity) {
1758
- return newEntity;
1759
- }
1760
- get ids() {
1761
- return this._value().ids;
1762
- }
1763
- get entities() {
1764
- return this._value().entities;
1765
- }
1766
- get active() {
1767
- return this._value().active;
1768
- }
1769
- _setActive(ids) {
1770
- this._setState((state) => {
1771
- return Object.assign(Object.assign({}, state), { active: ids });
1772
- });
1773
- }
1774
- handleUICreation(add = false) {
1775
- const ids = this.ids;
1776
- const isFunc = isFunction(this.ui._akitaCreateEntityFn);
1777
- let uiEntities;
1778
- const createFn = (id) => {
1779
- const current = this.entities[id];
1780
- const ui = isFunc ? this.ui._akitaCreateEntityFn(current) : this.ui._akitaCreateEntityFn;
1781
- return Object.assign({ [this.idKey]: current[this.idKey] }, ui);
1782
- };
1783
- if (add) {
1784
- uiEntities = this.ids.filter((id) => isUndefined(this.ui.entities[id])).map(createFn);
1785
- }
1786
- else {
1787
- uiEntities = ids.map(createFn);
1788
- }
1789
- add ? this.ui.add(uiEntities) : this.ui.set(uiEntities);
1790
- }
1791
- hasInitialUIState() {
1792
- return this.hasUIStore() && isUndefined(this.ui._akitaCreateEntityFn) === false;
1793
- }
1794
- handleUIRemove(ids) {
1795
- if (this.hasUIStore()) {
1796
- this.ui.remove(ids);
1797
- }
1798
- }
1799
- hasUIStore() {
1800
- return this.ui instanceof EntityUIStore;
1801
- }
1802
- }
1803
- __decorate([
1804
- transaction(),
1805
- __metadata("design:type", Function),
1806
- __metadata("design:paramtypes", [Object, Object, Object, Object]),
1807
- __metadata("design:returntype", void 0)
1808
- ], EntityStore.prototype, "upsert", null);
1809
- __decorate([
1810
- transaction(),
1811
- __metadata("design:type", Function),
1812
- __metadata("design:paramtypes", [typeof (_b = typeof T !== "undefined" && T) === "function" ? _b : Object]),
1813
- __metadata("design:returntype", void 0)
1814
- ], EntityStore.prototype, "toggleActive", null);
1815
- // @internal
1816
- class EntityUIStore extends EntityStore {
1817
- constructor(initialState = {}, storeConfig = {}) {
1818
- super(initialState, storeConfig);
1819
- }
1820
- /**
1821
- *
1822
- * Set the initial UI entity state. This function will determine the entity's
1823
- * initial state when we call `set()` or `add()`.
1824
- *
1825
- * @example
1826
- *
1827
- * constructor() {
1828
- * super();
1829
- * this.createUIStore().setInitialEntityState(entity => ({ isLoading: false, isOpen: true }));
1830
- * this.createUIStore().setInitialEntityState({ isLoading: false, isOpen: true });
1831
- * }
1832
- *
1833
- */
1834
- setInitialEntityState(createFn) {
1835
- this._akitaCreateEntityFn = createFn;
1836
- }
1837
- }
1838
-
1839
- var Order;
1840
- (function (Order) {
1841
- Order["ASC"] = "asc";
1842
- Order["DESC"] = "desc";
1843
- })(Order || (Order = {}));
1844
-
1845
- // @internal
1846
- function isString(value) {
1847
- return typeof value === 'string';
1848
- }
1849
-
1850
- const queryConfigKey = 'akitaQueryConfig';
1851
-
1852
- function compareKeys(keysOrFuncs) {
1853
- return function (prevState, currState) {
1854
- const isFns = isFunction(keysOrFuncs[0]);
1855
- // Return when they are NOT changed
1856
- return keysOrFuncs.some(keyOrFunc => {
1857
- if (isFns) {
1858
- return keyOrFunc(prevState) !== keyOrFunc(currState);
1859
- }
1860
- return prevState[keyOrFunc] !== currState[keyOrFunc];
1861
- }) === false;
1862
- };
1863
- }
1864
-
1865
- class Query {
1866
- constructor(store) {
1867
- this.store = store;
1868
- this.__store__ = store;
1869
- if (isDev()) {
1870
- // @internal
1871
- __queries__[store.storeName] = this;
1872
- }
1873
- }
1874
- select(project) {
1875
- let mapFn;
1876
- if (isFunction(project)) {
1877
- mapFn = project;
1878
- }
1879
- else if (isString(project)) {
1880
- mapFn = state => state[project];
1881
- }
1882
- else if (Array.isArray(project)) {
1883
- return this.store
1884
- ._select(state => state)
1885
- .pipe(distinctUntilChanged(compareKeys(project)), map(state => {
1886
- if (isFunction(project[0])) {
1887
- return project.map(func => func(state));
1888
- }
1889
- return project.reduce((acc, k) => {
1890
- acc[k] = state[k];
1891
- return acc;
1892
- }, {});
1893
- }));
1894
- }
1895
- else {
1896
- mapFn = state => state;
1897
- }
1898
- return this.store._select(mapFn);
1899
- }
1900
- /**
1901
- * Select the loading state
1902
- *
1903
- * @example
1904
- *
1905
- * this.query.selectLoading().subscribe(isLoading => {})
1906
- */
1907
- selectLoading() {
1908
- return this.select(state => state.loading);
1909
- }
1910
- /**
1911
- * Select the error state
1912
- *
1913
- * @example
1914
- *
1915
- * this.query.selectError().subscribe(error => {})
1916
- */
1917
- selectError() {
1918
- return this.select(state => state.error);
1919
- }
1920
- /**
1921
- * Get the store's value
1922
- *
1923
- * @example
1924
- *
1925
- * this.query.getValue()
1926
- *
1927
- */
1928
- getValue() {
1929
- return this.store._value();
1930
- }
1931
- /**
1932
- * Select the cache state
1933
- *
1934
- * @example
1935
- *
1936
- * this.query.selectHasCache().pipe(
1937
- * switchMap(hasCache => {
1938
- * return hasCache ? of() : http().pipe(res => store.set(res))
1939
- * })
1940
- * )
1941
- */
1942
- selectHasCache() {
1943
- return this.store._cache().asObservable();
1944
- }
1945
- /**
1946
- * Whether we've cached data
1947
- *
1948
- * @example
1949
- *
1950
- * this.query.getHasCache()
1951
- *
1952
- */
1953
- getHasCache() {
1954
- return this.store._cache().value;
1955
- }
1956
- // @internal
1957
- get config() {
1958
- return this.constructor[queryConfigKey];
1959
- }
1960
- }
1961
-
1962
- /**
1963
- * @example
1964
- *
1965
- * query.selectEntity(2).pipe(filterNil)
1966
- */
1967
- const filterNil = (source) => source.pipe(filter((value) => value !== null && typeof value !== 'undefined'));
1968
-
1969
- /**
1970
- * @internal
1971
- *
1972
- * @example
1973
- *
1974
- * getValue(state, 'todos.ui')
1975
- *
1976
- */
1977
- function getValue(obj, prop) {
1978
- /** return the whole state */
1979
- if (prop.split('.').length === 1) {
1980
- return obj;
1981
- }
1982
- const removeStoreName = prop
1983
- .split('.')
1984
- .slice(1)
1985
- .join('.');
1986
- return removeStoreName.split('.').reduce((acc, part) => acc && acc[part], obj);
1987
- }
1988
-
1989
- /**
1990
- * @internal
1991
- *
1992
- * @example
1993
- * setValue(state, 'todos.ui', { filter: {} })
1994
- */
1995
- function setValue(obj, prop, val) {
1996
- const split = prop.split('.');
1997
- if (split.length === 1) {
1998
- return Object.assign(Object.assign({}, obj), val);
1999
- }
2000
- obj = Object.assign({}, obj);
2001
- const lastIndex = split.length - 2;
2002
- const removeStoreName = prop.split('.').slice(1);
2003
- removeStoreName.reduce((acc, part, index) => {
2004
- if (index !== lastIndex) {
2005
- acc[part] = Object.assign({}, acc[part]);
2006
- return acc && acc[part];
2007
- }
2008
- acc[part] = Array.isArray(acc[part]) || !isObject(acc[part]) ? val : Object.assign(Object.assign({}, acc[part]), val);
2009
- return acc && acc[part];
2010
- }, obj);
2011
- return obj;
2012
- }
2013
-
2014
- let skipStorageUpdate = false;
2015
- const _persistStateInit = new ReplaySubject(1);
2016
- function getSkipStorageUpdate() {
2017
- return skipStorageUpdate;
2018
- }
2019
- function isPromise(v) {
2020
- return v && isFunction(v.then);
2021
- }
2022
- function observify(asyncOrValue) {
2023
- if (isPromise(asyncOrValue) || isObservable(asyncOrValue)) {
2024
- return from(asyncOrValue);
2025
- }
2026
- return of(asyncOrValue);
2027
- }
2028
- function persistState(params) {
2029
- const defaults = {
2030
- key: 'AkitaStores',
2031
- enableInNonBrowser: false,
2032
- storage: !hasLocalStorage() ? params.storage : localStorage,
2033
- deserialize: JSON.parse,
2034
- serialize: JSON.stringify,
2035
- include: [],
2036
- select: [],
2037
- persistOnDestroy: false,
2038
- preStorageUpdate: function (storeName, state) {
2039
- return state;
2040
- },
2041
- preStoreUpdate: function (storeName, state) {
2042
- return state;
2043
- },
2044
- skipStorageUpdate: getSkipStorageUpdate,
2045
- preStorageUpdateOperator: () => (source) => source,
2046
- };
2047
- const { storage, enableInNonBrowser, deserialize, serialize, include, select, key, preStorageUpdate, persistOnDestroy, preStorageUpdateOperator, preStoreUpdate, skipStorageUpdate } = Object.assign({}, defaults, params);
2048
- if ((isNotBrowser && !enableInNonBrowser) || !storage)
2049
- return;
2050
- const hasInclude = include.length > 0;
2051
- const hasSelect = select.length > 0;
2052
- let includeStores;
2053
- let selectStores;
2054
- if (hasInclude) {
2055
- includeStores = include.reduce((acc, path) => {
2056
- if (isFunction(path)) {
2057
- acc.fns.push(path);
2058
- }
2059
- else {
2060
- const storeName = path.split('.')[0];
2061
- acc[storeName] = path;
2062
- }
2063
- return acc;
2064
- }, { fns: [] });
2065
- }
2066
- if (hasSelect) {
2067
- selectStores = select.reduce((acc, selectFn) => {
2068
- acc[selectFn.storeName] = selectFn;
2069
- return acc;
2070
- }, {});
2071
- }
2072
- let stores = {};
2073
- let acc = {};
2074
- let subscriptions = [];
2075
- const buffer = [];
2076
- function _save(v) {
2077
- observify(v).subscribe(() => {
2078
- const next = buffer.shift();
2079
- next && _save(next);
2080
- });
2081
- }
2082
- // when we use the local/session storage we perform the serialize, otherwise we let the passed storage implementation to do it
2083
- const isLocalStorage = (hasLocalStorage() && storage === localStorage) || (hasSessionStorage() && storage === sessionStorage);
2084
- observify(storage.getItem(key)).subscribe((value) => {
2085
- let storageState = isObject(value) ? value : deserialize(value || '{}');
2086
- function save(storeCache) {
2087
- storageState['$cache'] = Object.assign(Object.assign({}, (storageState['$cache'] || {})), storeCache);
2088
- storageState = Object.assign({}, storageState, acc);
2089
- buffer.push(storage.setItem(key, isLocalStorage ? serialize(storageState) : storageState));
2090
- _save(buffer.shift());
2091
- }
2092
- function subscribe(storeName, path) {
2093
- stores[storeName] = __stores__[storeName]
2094
- ._select((state) => getValue(state, path))
2095
- .pipe(skip(1), map((store) => {
2096
- if (hasSelect && selectStores[storeName]) {
2097
- return selectStores[storeName](store);
2098
- }
2099
- return store;
2100
- }), filter(() => skipStorageUpdate() === false), preStorageUpdateOperator())
2101
- .subscribe((data) => {
2102
- acc[storeName] = preStorageUpdate(storeName, data);
2103
- Promise.resolve().then(() => save({ [storeName]: __stores__[storeName]._cache().getValue() }));
2104
- });
2105
- }
2106
- function setInitial(storeName, store, path) {
2107
- if (storeName in storageState) {
2108
- setAction('@PersistState');
2109
- store._setState((state) => {
2110
- return setValue(state, path, preStoreUpdate(storeName, storageState[storeName], state));
2111
- });
2112
- const hasCache = storageState['$cache'] ? storageState['$cache'][storeName] : false;
2113
- __stores__[storeName].setHasCache(hasCache, { restartTTL: true });
2114
- }
2115
- }
2116
- subscriptions.push($$deleteStore.subscribe((storeName) => {
2117
- if (stores[storeName]) {
2118
- if (persistOnDestroy === false) {
2119
- save({ [storeName]: false });
2120
- }
2121
- stores[storeName].unsubscribe();
2122
- delete stores[storeName];
2123
- }
2124
- }));
2125
- subscriptions.push($$addStore.subscribe((storeName) => {
2126
- if (storeName === 'router') {
2127
- return;
2128
- }
2129
- const store = __stores__[storeName];
2130
- if (hasInclude) {
2131
- let path = includeStores[storeName];
2132
- if (!path) {
2133
- const passPredicate = includeStores.fns.some((fn) => fn(storeName));
2134
- if (passPredicate) {
2135
- path = storeName;
2136
- }
2137
- else {
2138
- return;
2139
- }
2140
- }
2141
- setInitial(storeName, store, path);
2142
- subscribe(storeName, path);
2143
- }
2144
- else {
2145
- setInitial(storeName, store, storeName);
2146
- subscribe(storeName, storeName);
2147
- }
2148
- }));
2149
- _persistStateInit.next();
2150
- });
2151
- return {
2152
- destroy() {
2153
- subscriptions.forEach((s) => s.unsubscribe());
2154
- for (let i = 0, keys = Object.keys(stores); i < keys.length; i++) {
2155
- const storeName = keys[i];
2156
- stores[storeName].unsubscribe();
2157
- }
2158
- stores = {};
2159
- },
2160
- clear() {
2161
- storage.clear();
2162
- },
2163
- clearStore(storeName) {
2164
- if (isNil(storeName)) {
2165
- const value = observify(storage.setItem(key, '{}'));
2166
- value.subscribe();
2167
- return;
2168
- }
2169
- const value = storage.getItem(key);
2170
- observify(value).subscribe((v) => {
2171
- const storageState = deserialize(v || '{}');
2172
- if (storageState[storeName]) {
2173
- delete storageState[storeName];
2174
- const value = observify(storage.setItem(key, serialize(storageState)));
2175
- value.subscribe();
2176
- }
2177
- });
2178
- },
2179
- };
2180
- }
2181
-
2182
- class AkitaPlugin {
2183
- constructor(query, config) {
2184
- this.query = query;
2185
- if (config && config.resetFn) {
2186
- if (getAkitaConfig().resettable) {
2187
- this.onReset(config.resetFn);
2188
- }
2189
- }
2190
- }
2191
- /** This method is responsible for getting access to the query. */
2192
- getQuery() {
2193
- return this.query;
2194
- }
2195
- /** This method is responsible for getting access to the store. */
2196
- getStore() {
2197
- return this.getQuery().__store__;
2198
- }
2199
- /** This method is responsible tells whether the plugin is entityBased or not. */
2200
- isEntityBased(entityId) {
2201
- return toBoolean(entityId);
2202
- }
2203
- /** This method is responsible for selecting the source; it can be the whole store or one entity. */
2204
- selectSource(entityId, property) {
2205
- if (this.isEntityBased(entityId)) {
2206
- return this.getQuery().selectEntity(entityId).pipe(filterNil);
2207
- }
2208
- if (property) {
2209
- return this.getQuery().select(state => getValue(state, this.withStoreName(property)));
2210
- }
2211
- return this.getQuery().select();
2212
- }
2213
- getSource(entityId, property) {
2214
- if (this.isEntityBased(entityId)) {
2215
- return this.getQuery().getEntity(entityId);
2216
- }
2217
- const state = this.getQuery().getValue();
2218
- if (property) {
2219
- return getValue(state, this.withStoreName(property));
2220
- }
2221
- return state;
2222
- }
2223
- withStoreName(prop) {
2224
- return `${this.storeName}.${prop}`;
2225
- }
2226
- get storeName() {
2227
- return this.getStore().storeName;
2228
- }
2229
- /** This method is responsible for updating the store or one entity; it can be the whole store or one entity. */
2230
- updateStore(newState, entityId, property) {
2231
- if (this.isEntityBased(entityId)) {
2232
- this.getStore().update(entityId, newState);
2233
- }
2234
- else {
2235
- if (property) {
2236
- this.getStore()._setState(state => {
2237
- return setValue(state, this.withStoreName(property), newState);
2238
- });
2239
- return;
2240
- }
2241
- this.getStore()._setState(state => (Object.assign(Object.assign({}, state), newState)));
2242
- }
2243
- }
2244
- /**
2245
- * Function to invoke upon reset
2246
- */
2247
- onReset(fn) {
2248
- const original = this.getStore().reset;
2249
- this.getStore().reset = (...params) => {
2250
- /** It should run after the plugin destroy method */
2251
- setTimeout(() => {
2252
- original.apply(this.getStore(), params);
2253
- fn();
2254
- });
2255
- };
2256
- }
2257
- }
2258
-
2259
- const paginatorDefaults = {
2260
- pagesControls: false,
2261
- range: false,
2262
- startWith: 1,
2263
- cacheTimeout: undefined,
2264
- clearStoreWithCache: true
2265
- };
2266
- class PaginatorPlugin extends AkitaPlugin {
2267
- constructor(query, config = {}) {
2268
- super(query, {
2269
- resetFn: () => {
2270
- this.initial = false;
2271
- this.destroy({ clearCache: true, currentPage: 1 });
2272
- }
2273
- });
2274
- this.query = query;
2275
- this.config = config;
2276
- /** Save current filters, sorting, etc. in cache */
2277
- this.metadata = new Map();
2278
- this.pages = new Map();
2279
- this.pagination = {
2280
- currentPage: 1,
2281
- perPage: 0,
2282
- total: 0,
2283
- lastPage: 0,
2284
- data: []
2285
- };
2286
- /**
2287
- * When the user navigates to a different page and return
2288
- * we don't want to call `clearCache` on first time.
2289
- */
2290
- this.initial = true;
2291
- /**
2292
- * Proxy to the query loading
2293
- */
2294
- this.isLoading$ = this.query.selectLoading().pipe(delay(0));
2295
- this.config = Object.assign(paginatorDefaults, config);
2296
- const { startWith, cacheTimeout } = this.config;
2297
- this.page = new BehaviorSubject(startWith);
2298
- if (isObservable(cacheTimeout)) {
2299
- this.clearCacheSubscription = cacheTimeout.subscribe(() => this.clearCache());
2300
- }
2301
- }
2302
- /**
2303
- * Listen to page changes
2304
- */
2305
- get pageChanges() {
2306
- return this.page.asObservable();
2307
- }
2308
- /**
2309
- * Get the current page number
2310
- */
2311
- get currentPage() {
2312
- return this.pagination.currentPage;
2313
- }
2314
- /**
2315
- * Check if current page is the first one
2316
- */
2317
- get isFirst() {
2318
- return this.currentPage === 1;
2319
- }
2320
- /**
2321
- * Check if current page is the last one
2322
- */
2323
- get isLast() {
2324
- return this.currentPage === this.pagination.lastPage;
2325
- }
2326
- /**
2327
- * Whether to generate an array of pages for *ngFor
2328
- * [1, 2, 3, 4]
2329
- */
2330
- withControls() {
2331
- this.config.pagesControls = true;
2332
- return this;
2333
- }
2334
- /**
2335
- * Whether to generate the `from` and `to` keys
2336
- * [1, 2, 3, 4]
2337
- */
2338
- withRange() {
2339
- this.config.range = true;
2340
- return this;
2341
- }
2342
- /**
2343
- * Set the loading state
2344
- */
2345
- setLoading(value = true) {
2346
- this.getStore().setLoading(value);
2347
- }
2348
- /**
2349
- * Update the pagination object and add the page
2350
- */
2351
- update(response) {
2352
- this.pagination = response;
2353
- this.addPage(response.data);
2354
- }
2355
- /**
2356
- *
2357
- * Set the ids and add the page to store
2358
- */
2359
- addPage(data) {
2360
- this.pages.set(this.currentPage, { ids: data.map(entity => entity[this.getStore().idKey]) });
2361
- this.getStore().upsertMany(data);
2362
- }
2363
- /**
2364
- * Clear the cache.
2365
- */
2366
- clearCache(options = {}) {
2367
- if (!this.initial) {
2368
- logAction('@Pagination - Clear Cache');
2369
- if (options.clearStore !== false && (this.config.clearStoreWithCache || options.clearStore)) {
2370
- this.getStore().remove();
2371
- }
2372
- this.pages = new Map();
2373
- this.metadata = new Map();
2374
- }
2375
- this.initial = false;
2376
- }
2377
- clearPage(page) {
2378
- this.pages.delete(page);
2379
- }
2380
- /**
2381
- * Clear the cache timeout and optionally the pages
2382
- */
2383
- destroy({ clearCache, currentPage } = {}) {
2384
- if (this.clearCacheSubscription) {
2385
- this.clearCacheSubscription.unsubscribe();
2386
- }
2387
- if (clearCache) {
2388
- this.clearCache();
2389
- }
2390
- if (!isUndefined(currentPage)) {
2391
- this.setPage(currentPage);
2392
- }
2393
- this.initial = true;
2394
- }
2395
- /**
2396
- * Whether the provided page is active
2397
- */
2398
- isPageActive(page) {
2399
- return this.currentPage === page;
2400
- }
2401
- /**
2402
- * Set the current page
2403
- */
2404
- setPage(page) {
2405
- if (page !== this.currentPage || !this.hasPage(page)) {
2406
- this.page.next((this.pagination.currentPage = page));
2407
- }
2408
- }
2409
- /**
2410
- * Increment current page
2411
- */
2412
- nextPage() {
2413
- if (this.currentPage !== this.pagination.lastPage) {
2414
- this.setPage(this.pagination.currentPage + 1);
2415
- }
2416
- }
2417
- /**
2418
- * Decrement current page
2419
- */
2420
- prevPage() {
2421
- if (this.pagination.currentPage > 1) {
2422
- this.setPage(this.pagination.currentPage - 1);
2423
- }
2424
- }
2425
- /**
2426
- * Set current page to last
2427
- */
2428
- setLastPage() {
2429
- this.setPage(this.pagination.lastPage);
2430
- }
2431
- /**
2432
- * Set current page to first
2433
- */
2434
- setFirstPage() {
2435
- this.setPage(1);
2436
- }
2437
- /**
2438
- * Check if page exists in cache
2439
- */
2440
- hasPage(page) {
2441
- return this.pages.has(page);
2442
- }
2443
- /**
2444
- * Get the current page if it's in cache, otherwise invoke the request
2445
- */
2446
- getPage(req) {
2447
- let page = this.pagination.currentPage;
2448
- if (this.hasPage(page)) {
2449
- return this.selectPage(page);
2450
- }
2451
- else {
2452
- this.setLoading(true);
2453
- return from(req()).pipe(switchMap((config) => {
2454
- page = config.currentPage;
2455
- applyTransaction(() => {
2456
- this.setLoading(false);
2457
- this.update(config);
2458
- });
2459
- return this.selectPage(page);
2460
- }));
2461
- }
2462
- }
2463
- getQuery() {
2464
- return this.query;
2465
- }
2466
- refreshCurrentPage() {
2467
- if (isNil(this.currentPage) === false) {
2468
- this.clearPage(this.currentPage);
2469
- this.setPage(this.currentPage);
2470
- }
2471
- }
2472
- getFrom() {
2473
- if (this.isFirst) {
2474
- return 1;
2475
- }
2476
- return (this.currentPage - 1) * this.pagination.perPage + 1;
2477
- }
2478
- getTo() {
2479
- if (this.isLast) {
2480
- return this.pagination.total;
2481
- }
2482
- return this.currentPage * this.pagination.perPage;
2483
- }
2484
- /**
2485
- * Select the page
2486
- */
2487
- selectPage(page) {
2488
- return this.query.selectAll({ asObject: true }).pipe(take(1), map(entities => {
2489
- let response = Object.assign(Object.assign({}, this.pagination), { data: this.pages.get(page).ids.map(id => entities[id]) });
2490
- const { range, pagesControls } = this.config;
2491
- /** If no total - calc it */
2492
- if (isNaN(this.pagination.total)) {
2493
- if (response.lastPage === 1) {
2494
- response.total = response.data ? response.data.length : 0;
2495
- }
2496
- else {
2497
- response.total = response.perPage * response.lastPage;
2498
- }
2499
- this.pagination.total = response.total;
2500
- }
2501
- if (range) {
2502
- response.from = this.getFrom();
2503
- response.to = this.getTo();
2504
- }
2505
- if (pagesControls) {
2506
- response.pageControls = generatePages(this.pagination.total, this.pagination.perPage);
2507
- }
2508
- return response;
2509
- }));
2510
- }
2511
- }
2512
- __decorate([
2513
- action('@Pagination - New Page'),
2514
- __metadata("design:type", Function),
2515
- __metadata("design:paramtypes", [Object]),
2516
- __metadata("design:returntype", void 0)
2517
- ], PaginatorPlugin.prototype, "update", null);
2518
- /**
2519
- * Generate an array so we can ngFor them to navigate between pages
2520
- */
2521
- function generatePages(total, perPage) {
2522
- const len = Math.ceil(total / perPage);
2523
- let arr = [];
2524
- for (let i = 0; i < len; i++) {
2525
- arr.push(i + 1);
2526
- }
2527
- return arr;
2528
- }
2529
-
2530
- var StoreAction;
2531
- (function (StoreAction) {
2532
- StoreAction["Update"] = "UPDATE";
2533
- })(StoreAction || (StoreAction = {}));
2534
- var EntityStoreAction;
2535
- (function (EntityStoreAction) {
2536
- EntityStoreAction["Update"] = "UPDATE";
2537
- EntityStoreAction["AddEntities"] = "ADD_ENTITIES";
2538
- EntityStoreAction["SetEntities"] = "SET_ENTITIES";
2539
- EntityStoreAction["UpdateEntities"] = "UPDATE_ENTITIES";
2540
- EntityStoreAction["RemoveEntities"] = "REMOVE_ENTITIES";
2541
- EntityStoreAction["UpsertEntities"] = "UPSERT_ENTITIES";
2542
- EntityStoreAction["UpsertManyEntities"] = "UPSERT_MANY_ENTITIES";
2543
- })(EntityStoreAction || (EntityStoreAction = {}));
2544
-
2545
- export { Query as Q, StoreConfig as S, Store as a, enableAkitaProdMode as e, persistState as p };