UNPKG

@ngxs-labs/entity-state

Version:

This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.0.5.

1,315 lines (1,297 loc) 68.1 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@ngxs/store')) : typeof define === 'function' && define.amd ? define('@ngxs-labs/entity-state', ['exports', '@ngxs/store'], factory) : (factory((global['ngxs-labs'] = global['ngxs-labs'] || {}, global['ngxs-labs']['entity-state'] = {}),global['ngxs-store'])); }(this, (function (exports,store) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ var EntityStateError = /** @class */ (function (_super) { __extends(EntityStateError, _super); function EntityStateError(message) { return _super.call(this, message) || this; } return EntityStateError; }(Error)); var NoActiveEntityError = /** @class */ (function (_super) { __extends(NoActiveEntityError, _super); function NoActiveEntityError(additionalInformation) { if (additionalInformation === void 0) { additionalInformation = ''; } return _super.call(this, ('No active entity to affect. ' + additionalInformation).trim()) || this; } return NoActiveEntityError; }(EntityStateError)); var NoSuchEntityError = /** @class */ (function (_super) { __extends(NoSuchEntityError, _super); function NoSuchEntityError(id) { return _super.call(this, "No entity for ID " + id) || this; } return NoSuchEntityError; }(EntityStateError)); var InvalidIdError = /** @class */ (function (_super) { __extends(InvalidIdError, _super); function InvalidIdError(id) { return _super.call(this, "Invalid ID: " + id) || this; } return InvalidIdError; }(EntityStateError)); var InvalidIdOfError = /** @class */ (function (_super) { __extends(InvalidIdOfError, _super); function InvalidIdOfError() { return _super.call(this, "idOf returned undefined") || this; } return InvalidIdOfError; }(EntityStateError)); var UpdateFailedError = /** @class */ (function (_super) { __extends(UpdateFailedError, _super); function UpdateFailedError(cause) { return _super.call(this, "Updating entity failed.\n\tCause: " + cause) || this; } return UpdateFailedError; }(EntityStateError)); var UnableToGenerateIdError = /** @class */ (function (_super) { __extends(UnableToGenerateIdError, _super); function UnableToGenerateIdError(cause) { return _super.call(this, "Unable to generate an ID.\n\tCause: " + cause) || this; } return UnableToGenerateIdError; }(EntityStateError)); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @type {?} */ var NGXS_META_KEY = 'NGXS_META'; /** * This function generates a new object for the ngxs Action with the given fn name * @template T * @param {?} fn The name of the Action to simulate, e.g. "Remove" or "Update" * @param {?} store The class of the targeted entity state, e.g. ZooState * @param {?=} payload The payload for the created action object * @return {?} */ function generateActionObject(fn, store$$1, payload) { /** @type {?} */ var name = store$$1[NGXS_META_KEY].path; /** @type {?} */ var ReflectedAction = ( /** * @param {?} data * @return {?} */function (data) { this.payload = data; }); /** @type {?} */ var obj = new ReflectedAction(payload); Reflect.getPrototypeOf(obj).constructor['type'] = "[" + name + "] " + fn; return obj; } /** * Utility function that returns the active entity of the given state * @template T * @param {?} state the state of an entity state * @return {?} */ function getActive(state) { return state.entities[state.active]; } /** * Returns the active entity. If none is present an error will be thrown. * @template T * @param {?} state The state to act on * @return {?} */ function mustGetActive(state) { /** @type {?} */ var active = getActive(state); if (active === undefined) { throw new NoActiveEntityError(); } return { id: state.active, active: active }; } /** * Undefined-safe function to access the property given by path parameter * @param {?} object The object to read from * @param {?} path The path to the property * @return {?} */ function elvis(object, path) { return path ? path.split('.').reduce(( /** * @param {?} value * @param {?} key * @return {?} */function (value, key) { return value && value[key]; }), object) : object; } /** * Returns input as an array if it isn't one already * @template T * @param {?} input The input to make an array if necessary * @return {?} */ function asArray(input) { return Array.isArray(input) ? input : [input]; } /** * Limits a number to the given boundaries * @param {?} value The input value * @param {?} min The minimum value * @param {?} max The maximum value * @return {?} */ function clamp(value, min, max) { return Math.min(max, Math.max(min, value)); } /** * Uses the clamp function is wrap is false. * Else it wrap to the max or min value respectively. * @param {?} wrap Flag to indicate if value should be wrapped * @param {?} value The input value * @param {?} min The minimum value * @param {?} max The maximum value * @return {?} */ function wrapOrClamp(wrap, value, min, max) { if (!wrap) { return clamp(value, min, max); } else if (value < min) { return max; } else if (value > max) { return min; } else { return value; } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** @enum {string} */ var EntityActionType = { Add: 'add', CreateOrReplace: 'createOrReplace', Update: 'update', UpdateActive: 'updateActive', Remove: 'remove', RemoveActive: 'removeActive', SetLoading: 'setLoading', SetError: 'setError', SetActive: 'setActive', ClearActive: 'clearActive', Reset: 'reset', GoToPage: 'goToPage', SetPageSize: 'setPageSize', }; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @template T */ var /** * @template T */ Add = /** @class */ (function () { /** * Generates an action that will add the given entities to the state. * The entities given by the payload will be added. * For certain ID strategies this might fail, if it provides an existing ID. * In all other cases it will overwrite the ID value in the entity with the calculated ID. * @param target The targeted state class * @param payload An entity or an array of entities to be added * @see CreateOrReplace#constructor */ function Add(target, payload) { return generateActionObject(EntityActionType.Add, target, payload); } return Add; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @template T */ var /** * @template T */ CreateOrReplace = /** @class */ (function () { /** * Generates an action that will add the given entities to the state. * If an entity with the ID already exists, it will be overridden. * In all cases it will overwrite the ID value in the entity with the calculated ID. * @param target The targeted state class * @param payload An entity or an array of entities to be added * @see Add#constructor */ function CreateOrReplace(target, payload) { return generateActionObject(EntityActionType.CreateOrReplace, target, payload); } return CreateOrReplace; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @template T */ var /** * @template T */ Remove = /** @class */ (function () { /** * Generates an action that will remove the given entities from the state. * Put null if all entities should be removed. * @param target The targeted state class * @param payload An EntitySelector payload * @see EntitySelector */ function Remove(target, payload) { return generateActionObject(EntityActionType.Remove, target, payload); } return Remove; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @template T */ var /** * @template T */ Update = /** @class */ (function () { /** * Generates an action that will update the current active entity. * If no entity is active a runtime error will be thrown. * @param target The targeted state class * @param id An EntitySelector that determines the entities to update * @param data An Updater that will be applied to the selected entities * @see EntitySelector * @see Updater */ function Update(target, id, data) { return generateActionObject(EntityActionType.Update, target, { id: id, data: data }); } return Update; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ var SetLoading = /** @class */ (function () { /** * Generates an action that will set the loading state for the given state. * @param target The targeted state class * @param loading The loading state */ function SetLoading(target, loading) { return generateActionObject(EntityActionType.SetLoading, target, loading); } return SetLoading; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ var SetActive = /** @class */ (function () { /** * Generates an action that sets an ID that identifies the active entity * @param target The targeted state class * @param id The ID that identifies the active entity */ function SetActive(target, id) { return generateActionObject(EntityActionType.SetActive, target, id); } return SetActive; }()); var ClearActive = /** @class */ (function () { /** * Generates an action that clears the active entity in the given state * @param target The targeted state class */ function ClearActive(target) { return generateActionObject(EntityActionType.ClearActive, target); } return ClearActive; }()); var RemoveActive = /** @class */ (function () { /** * Generates an action that removes the active entity from the state and clears the active ID. * @param target The targeted state class */ function RemoveActive(target) { return generateActionObject(EntityActionType.RemoveActive, target); } return RemoveActive; }()); /** * @template T */ var /** * @template T */ UpdateActive = /** @class */ (function () { /** * Generates an action that will update the current active entity. * If no entity is active a runtime error will be thrown. * @param target The targeted state class * @param payload An Updater payload * @see Updater */ function UpdateActive(target, payload) { return generateActionObject(EntityActionType.UpdateActive, target, payload); } return UpdateActive; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ var SetError = /** @class */ (function () { /** * Generates an action that will set the error state for the given state. * Put undefined to clear the error state. * @param target The targeted state class * @param error The error that describes the error state */ function SetError(target, error) { return generateActionObject(EntityActionType.SetError, target, error); } return SetError; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ var Reset = /** @class */ (function () { /** * Resets the targeted store to the default state: no entities, loading is false, error is undefined, active is undefined. * @param target The targeted state class * @see defaultEntityState */ function Reset(target) { return generateActionObject(EntityActionType.Reset, target); } return Reset; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ var GoToPage = /** @class */ (function () { /** * Generates an action that changes the page index for pagination. * Page index starts at 0. * @param target The targeted state class * @param payload Payload to change the page index */ function GoToPage(target, payload) { return generateActionObject(EntityActionType.GoToPage, target, __assign({ wrap: false }, payload)); } return GoToPage; }()); var SetPageSize = /** @class */ (function () { /** * Generates an action that changes the page size * @param target The targeted state class * @param payload The page size */ function SetPageSize(target, payload) { return generateActionObject(EntityActionType.SetPageSize, target, payload); } return SetPageSize; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Returns a new object which serves as the default state. * No entities, loading is false, error is undefined, active is undefined. * pageSize is 10 and pageIndex is 0. * @template T * @param {?=} defaults * @return {?} */ function defaultEntityState(defaults) { if (defaults === void 0) { defaults = {}; } return __assign({ entities: {}, ids: [], loading: false, error: undefined, active: undefined, pageSize: 10, pageIndex: 0, lastUpdated: Date.now() }, defaults); } // @dynamic /** * @abstract * @template T */ var // @dynamic /** * @abstract * @template T */ EntityState = /** @class */ (function () { function EntityState(storeClass, _idKey, idStrategy) { this.idKey = ( /** @type {?} */(_idKey)); this.storePath = storeClass[NGXS_META_KEY].path; this.idGenerator = new idStrategy(_idKey); this.setup(storeClass, Object.values(EntityActionType)); } Object.defineProperty(EntityState, "staticStorePath", { get: /** * @private * @return {?} */ function () { /** @type {?} */ var that = this; return that[NGXS_META_KEY].path; }, enumerable: true, configurable: true }); /** * This function is called every time an entity is updated. * It receives the current entity and a partial entity that was either passed directly or generated with a function. * The default implementation uses the spread operator to create a new entity. * You must override this method if your entity type does not support the spread operator. * @see Updater * @param current The current entity, readonly * @param updated The new data as a partial entity * @example * // default behavior * onUpdate(current: Readonly<T updated: Partial<T>): T { return {...current, ...updated}; } */ /** * This function is called every time an entity is updated. * It receives the current entity and a partial entity that was either passed directly or generated with a function. * The default implementation uses the spread operator to create a new entity. * You must override this method if your entity type does not support the spread operator. * @see Updater * \@example * // default behavior * onUpdate(current: Readonly<T updated: Partial<T>): T { * return {...current, ...updated}; * } * @param {?} current The current entity, readonly * @param {?} updated The new data as a partial entity * @return {?} */ EntityState.prototype.onUpdate = /** * This function is called every time an entity is updated. * It receives the current entity and a partial entity that was either passed directly or generated with a function. * The default implementation uses the spread operator to create a new entity. * You must override this method if your entity type does not support the spread operator. * @see Updater * \@example * // default behavior * onUpdate(current: Readonly<T updated: Partial<T>): T { * return {...current, ...updated}; * } * @param {?} current The current entity, readonly * @param {?} updated The new data as a partial entity * @return {?} */ function (current, updated) { return ( /** @type {?} */(__assign({}, current, updated))); }; Object.defineProperty(EntityState, "activeId", { // ------------------- SELECTORS ------------------- /** * Returns a selector for the activeId */ get: // ------------------- SELECTORS ------------------- /** * Returns a selector for the activeId * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); return subState.active; }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "active", { /** * Returns a selector for the active entity */ get: /** * Returns a selector for the active entity * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); return getActive(subState); }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "keys", { /** * Returns a selector for the keys of all entities */ get: /** * Returns a selector for the keys of all entities * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); return Object.keys(subState.entities); }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "entities", { /** * Returns a selector for all entities, sorted by insertion order */ get: /** * Returns a selector for all entities, sorted by insertion order * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); return subState.ids.map(( /** * @param {?} id * @return {?} */function (id) { return subState.entities[id]; })); }); }, enumerable: true, configurable: true }); /** * Returns a selector for the nth entity, sorted by insertion order */ /** * Returns a selector for the nth entity, sorted by insertion order * @param {?} index * @return {?} */ EntityState.nthEntity = /** * Returns a selector for the nth entity, sorted by insertion order * @param {?} index * @return {?} */ function (index) { // tslint:disable-line:member-ordering /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); /** @type {?} */ var id = subState.ids[index]; return subState.entities[id]; }); }; Object.defineProperty(EntityState, "paginatedEntities", { /** * Returns a selector for paginated entities, sorted by insertion order */ get: /** * Returns a selector for paginated entities, sorted by insertion order * @return {?} */ function () { // tslint:disable-line:member-ordering /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); var ids = subState.ids, pageIndex = subState.pageIndex, pageSize = subState.pageSize; return ids .slice(pageIndex * pageSize, (pageIndex + 1) * pageSize) .map(( /** * @param {?} id * @return {?} */function (id) { return subState.entities[id]; })); }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "entitiesMap", { /** * Returns a selector for the map of entities */ get: /** * Returns a selector for the map of entities * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); return subState.entities; }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "size", { /** * Returns a selector for the size of the entity map */ get: /** * Returns a selector for the size of the entity map * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); return Object.keys(subState.entities).length; }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "error", { /** * Returns a selector for the error */ get: /** * Returns a selector for the error * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var name = that.staticStorePath; return elvis(state, name).error; }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "loading", { /** * Returns a selector for the loading state */ get: /** * Returns a selector for the loading state * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var name = that.staticStorePath; return elvis(state, name).loading; }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "latest", { /** * Returns a selector for the latest added entity */ get: /** * Returns a selector for the latest added entity * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); /** @type {?} */ var latestId = subState.ids[subState.ids.length - 1]; return subState.entities[latestId]; }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "latestId", { /** * Returns a selector for the latest added entity id */ get: /** * Returns a selector for the latest added entity id * @return {?} */ function () { /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); return subState.ids[subState.ids.length - 1]; }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "lastUpdated", { /** * Returns a selector for the update timestamp */ get: /** * Returns a selector for the update timestamp * @return {?} */ function () { // tslint:disable-line:member-ordering /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); return new Date(subState.lastUpdated); }); }, enumerable: true, configurable: true }); Object.defineProperty(EntityState, "age", { /** * Returns a selector for age, based on the update timestamp */ get: /** * Returns a selector for age, based on the update timestamp * @return {?} */ function () { // tslint:disable-line:member-ordering /** @type {?} */ var that = this; return ( /** * @param {?} state * @return {?} */function (state) { /** @type {?} */ var subState = ( /** @type {?} */(elvis(state, that.staticStorePath))); return Date.now() - subState.lastUpdated; }); }, enumerable: true, configurable: true }); // ------------------- ACTION HANDLERS ------------------- /** * The entities given by the payload will be added. * For certain ID strategies this might fail, if it provides an existing ID. * In all cases it will overwrite the ID value in the entity with the calculated ID. */ // ------------------- ACTION HANDLERS ------------------- /** * The entities given by the payload will be added. * For certain ID strategies this might fail, if it provides an existing ID. * In all cases it will overwrite the ID value in the entity with the calculated ID. * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.add = // ------------------- ACTION HANDLERS ------------------- /** * The entities given by the payload will be added. * For certain ID strategies this might fail, if it provides an existing ID. * In all cases it will overwrite the ID value in the entity with the calculated ID. * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var _this = this; var getState = _a.getState, patchState = _a.patchState; var payload = _b.payload; /** @type {?} */ var updated = this._addOrReplace(getState(), payload, ( // for automated ID strategies this mostly shouldn't throw an UnableToGenerateIdError error // for EntityIdGenerator it will throw an error if no ID is present // for automated ID strategies this mostly shouldn't throw an UnableToGenerateIdError error // for EntityIdGenerator it will throw an error if no ID is present /** * @param {?} p * @param {?} state * @return {?} */ function (p, state) { return _this.idGenerator.generateId(p, state); })); patchState(__assign({}, updated, { lastUpdated: Date.now() })); }; /** * The entities given by the payload will be added. * It first checks if the ID provided by each entity does exist. * If it does the current entity will be replaced. * In all cases it will overwrite the ID value in the entity with the calculated ID. */ /** * The entities given by the payload will be added. * It first checks if the ID provided by each entity does exist. * If it does the current entity will be replaced. * In all cases it will overwrite the ID value in the entity with the calculated ID. * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.createOrReplace = /** * The entities given by the payload will be added. * It first checks if the ID provided by each entity does exist. * If it does the current entity will be replaced. * In all cases it will overwrite the ID value in the entity with the calculated ID. * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var _this = this; var getState = _a.getState, patchState = _a.patchState; var payload = _b.payload; /** @type {?} */ var updated = this._addOrReplace(getState(), payload, ( /** * @param {?} p * @param {?} state * @return {?} */function (p, state) { return _this.idGenerator.getPresentIdOrGenerate(p, state); })); patchState(__assign({}, updated, { lastUpdated: Date.now() })); }; /** * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.update = /** * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var _this = this; var getState = _a.getState, patchState = _a.patchState; var payload = _b.payload; /** @type {?} */ var entities = __assign({}, getState().entities); // create copy /** @type {?} */ var affected; if (payload.id === null) { affected = Object.values(entities); } else if (typeof payload.id === 'function') { affected = Object.values(entities).filter(( /** * @param {?} e * @return {?} */function (e) { return (( /** @type {?} */(payload.id)))(e); })); } else { /** @type {?} */ var ids_1 = asArray(payload.id); affected = Object.values(entities).filter(( /** * @param {?} e * @return {?} */function (e) { return ids_1.includes(_this.idOf(e)); })); } if (typeof payload.data === 'function') { affected.forEach(( /** * @param {?} e * @return {?} */function (e) { entities = _this._update(entities, (( /** @type {?} */(payload.data)))(e), _this.idOf(e)); })); } else { affected.forEach(( /** * @param {?} e * @return {?} */function (e) { entities = _this._update(entities, ( /** @type {?} */(payload.data)), _this.idOf(e)); })); } patchState({ entities: entities, lastUpdated: Date.now() }); }; /** * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.updateActive = /** * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var getState = _a.getState, patchState = _a.patchState; var payload = _b.payload; /** @type {?} */ var state = getState(); var _c = mustGetActive(state), id = _c.id, active = _c.active; var entities = state.entities; if (typeof payload === 'function') { patchState({ entities: __assign({}, this._update(entities, payload(active), id)), lastUpdated: Date.now() }); } else { patchState({ entities: __assign({}, this._update(entities, payload, id)), lastUpdated: Date.now() }); } }; /** * @param {?} __0 * @return {?} */ EntityState.prototype.removeActive = /** * @param {?} __0 * @return {?} */ function (_a) { var getState = _a.getState, patchState = _a.patchState; var _b = getState(), entities = _b.entities, ids = _b.ids, active = _b.active; delete entities[active]; patchState({ entities: __assign({}, entities), ids: ids.filter(( /** * @param {?} id * @return {?} */function (id) { return id !== active; })), active: undefined, lastUpdated: Date.now() }); }; /** * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.remove = /** * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var _this = this; var getState = _a.getState, patchState = _a.patchState; var payload = _b.payload; var _c = getState(), entities = _c.entities, ids = _c.ids, active = _c.active; if (payload === null) { patchState({ entities: {}, ids: [], active: undefined, lastUpdated: Date.now() }); } else { /** @type {?} */ var deleteIds_1 = typeof payload === 'function' ? Object.values(entities) .filter(( /** * @param {?} e * @return {?} */function (e) { return payload(e); })) .map(( /** * @param {?} e * @return {?} */function (e) { return _this.idOf(e); })) : asArray(payload); /** @type {?} */ var wasActive = deleteIds_1.includes(active); deleteIds_1.forEach(( /** * @param {?} id * @return {?} */function (id) { return delete entities[id]; })); patchState({ entities: __assign({}, entities), ids: ids.filter(( /** * @param {?} id * @return {?} */function (id) { return !deleteIds_1.includes(id); })), active: wasActive ? undefined : active, lastUpdated: Date.now() }); } }; /** * @param {?} __0 * @return {?} */ EntityState.prototype.reset = /** * @param {?} __0 * @return {?} */ function (_a) { var setState = _a.setState; setState(defaultEntityState()); }; /** * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.setLoading = /** * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var patchState = _a.patchState; var payload = _b.payload; patchState({ loading: payload }); }; /** * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.setActive = /** * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var patchState = _a.patchState; var payload = _b.payload; patchState({ active: payload }); }; /** * @param {?} __0 * @return {?} */ EntityState.prototype.clearActive = /** * @param {?} __0 * @return {?} */ function (_a) { var patchState = _a.patchState; patchState({ active: undefined }); }; /** * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.setError = /** * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var patchState = _a.patchState; var payload = _b.payload; patchState({ error: payload }); }; /** * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.goToPage = /** * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var getState = _a.getState, patchState = _a.patchState; var payload = _b.payload; if ('page' in payload) { patchState({ pageIndex: payload.page }); return; } else if (payload['first']) { patchState({ pageIndex: 0 }); return; } var _c = getState(), pageSize = _c.pageSize, pageIndex = _c.pageIndex, ids = _c.ids; /** @type {?} */ var totalSize = ids.length; /** @type {?} */ var maxIndex = Math.floor(totalSize / pageSize); if ('last' in payload) { patchState({ pageIndex: maxIndex }); } else { /** @type {?} */ var step = payload['prev'] ? -1 : 1; /** @type {?} */ var index = pageIndex + step; index = wrapOrClamp(payload.wrap, index, 0, maxIndex); patchState({ pageIndex: index }); } }; /** * @param {?} __0 * @param {?} __1 * @return {?} */ EntityState.prototype.setPageSize = /** * @param {?} __0 * @param {?} __1 * @return {?} */ function (_a, _b) { var patchState = _a.patchState; var payload = _b.payload; patchState({ pageSize: payload }); }; // ------------------- UTILITY ------------------- /** * A utility function to update the given state with the given entities. * It returns a state model with the new entities map and IDs. * For each given entity an ID will be generated. The generated ID will overwrite the current value: * <code>entity[this.idKey] = generatedId(entity, state);</code> * If the ID wasn't present, it will be added to the state's IDs array. * @param state The current state to act on * @param payload One or multiple partial entities * @param generateId A function to generate an ID for each given entity */ // ------------------- UTILITY ------------------- /** * A utility function to update the given state with the given entities. * It returns a state model with the new entities map and IDs. * For each given entity an ID will be generated. The generated ID will overwrite the current value: * <code>entity[this.idKey] = generatedId(entity, state);</code> * If the ID wasn't present, it will be added to the state's IDs array. * @private * @param {?} state The current state to act on * @param {?} payload One or multiple partial entities * @param {?} generateId A function to generate an ID for each given entity * @return {?} */ EntityState.prototype._addOrReplace = // ------------------- UTILITY ------------------- /** * A utility function to update the given state with the given entities. * It returns a state model with the new entities map and IDs. * For each given entity an ID will be generated. The generated ID will overwrite the current value: