@flarehr/apollo-benefits 0.1.109 → 0.3.53405

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