@lomray/react-mobx-manager 3.6.1-beta.1 → 3.7.0-beta.1
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.
- package/manager.js +1 -1
- package/manager.js.map +1 -1
- package/package.json +1 -1
- package/types.d.ts +8 -0
- package/with-stores.js +1 -1
- package/with-stores.js.map +1 -1
package/manager.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"@lomray/event-manager";import{toJS as e,isObservableProp as s}from"mobx";import{ROOT_CONTEXT_ID as o}from"./constants.js";import r from"./deep-merge.js";import i from"./events.js";import n from"./logger.js";import{isPropExcludedFromExport as a,isPropSimpleExported as l,isPropObservableExported as h}from"./make-exported.js";import d from"./on-change-listener.js";import p from"./storages/combined-storage.js";import S from"./store-status.js";import c from"./wakeup.js";class u{static instance;stores=new Map;storesRelations=new Map;static persistedStores=new Set;initState;storage;storesParams;options={shouldDisablePersist:!1,shouldRemoveInitState:!0};suspenseRelations=new Map;logger;constructor({initState:t,storesParams:e,storage:s,options:o,logger:r}={}){if(this.initState=t||{},this.storesParams=e||{},this.logger=r&&"log"in r?r:new n({level:3,...r??{},manager:this}),this.storage=s instanceof p?s:s?new p({default:s}):void 0,Object.assign(this.options,o||{}),u.instance=this,"undefined"!=typeof window){const t=window.mbxM;window.mbxM={push:this.pushInitState},(Array.isArray(t)?t:[]).forEach(this.pushInitState)}}async init(){try{this.storage&&await this.storage.get()}catch(t){this.logger.err("Failed initialized store manager: ",t)}return this}static get(){if(!u.instance)throw new Error("Store manager is not initialized.");return u.instance}getStores(){return this.stores}getStoresRelations(){return this.storesRelations}getSuspenseRelations(){return this.suspenseRelations}static getPersistedStoresIds(){return u.persistedStores}pushInitState=(t={})=>{for(const[e,s]of Object.entries(t))this.initState[e]=s};getStoreId(t,e={}){const{id:s,contextId:o,key:r}=e;if(s)return s;if(t.libStoreId)return t.libStoreId;let i=t.id||t.name||t.constructor.name;return t.isGlobal?i:(i=`${i}--${o}`,r?`${i}--${r}`:i)}getStore(t,e={}){const s=this.getStoreId(t,e);return this.stores.has(s)?this.stores.get(s):t.isGlobal?this.createStore(t,{id:s,contextId:"global",parentId:o,suspenseId:"",componentName:"root-app",componentProps:{}}):this.lookupStore(s,e)}lookupStore(t,e){const{contextId:s,parentId:r}=e,i=t.split("--")?.[0],{ids:n,parentId:a}=this.storesRelations.get(s)??{ids:new Set,parentId:r},l=[...n].filter((t=>t.startsWith(`${i}--`)));if(1===l.length)return this.stores.get(l[0]);if(l.length>1)this.logger.err("Parent context has multiple stores with the same id, please pass key to getStore function.");else if(a&&a!==o)return this.lookupStore(t,{contextId:this.getBiggerContext(a,r)})}getBiggerContext(t,e){if(!t)return e;if(!e)return t;const s=/[^a-zA-Z]/g;return t.replace(s,"")>e.replace(s,"")?t:e}createStore(e,s){const{id:r,contextId:n,parentId:a,suspenseId:l,componentName:h,componentProps:d}=s;if(this.stores.has(r))return this.stores.get(r);const p=new e({...this.storesParams,storeManager:this,getStore:(t,e={contextId:n,parentId:a})=>this.getStore(t,e),componentProps:d,initState:this.initState[r]});return p.libStoreId=r,p.isGlobal=e.isGlobal,p.libStoreContextId=e.isGlobal?"global":n,p.libStoreParentId=e.isGlobal||!a||a===n?o:a,p.libStoreSuspenseId=l,p.libStoreComponentName=h,this.setStoreStatus(p,e.isGlobal?S.inUse:S.init),this.prepareStore(p),t.publish(i.CREATE_STORE,{store:e}),p}createStores(t,e,s,o,r,i={}){const
|
|
1
|
+
import t from"@lomray/event-manager";import{toJS as e,isObservableProp as s}from"mobx";import{ROOT_CONTEXT_ID as o}from"./constants.js";import r from"./deep-merge.js";import i from"./events.js";import n from"./logger.js";import{isPropExcludedFromExport as a,isPropSimpleExported as l,isPropObservableExported as h}from"./make-exported.js";import d from"./on-change-listener.js";import p from"./storages/combined-storage.js";import S from"./store-status.js";import c from"./wakeup.js";class u{static instance;stores=new Map;storesRelations=new Map;static persistedStores=new Set;initState;storage;storesParams;options={shouldDisablePersist:!1,shouldRemoveInitState:!0,failedCreationStrategy:"empty"};suspenseRelations=new Map;logger;constructor({initState:t,storesParams:e,storage:s,options:o,logger:r}={}){if(this.initState=t||{},this.storesParams=e||{},this.logger=r&&"log"in r?r:new n({level:3,...r??{},manager:this}),this.storage=s instanceof p?s:s?new p({default:s}):void 0,Object.assign(this.options,o||{}),u.instance=this,"undefined"!=typeof window){const t=window.mbxM;window.mbxM={push:this.pushInitState},(Array.isArray(t)?t:[]).forEach(this.pushInitState)}}async init(){try{this.storage&&await this.storage.get()}catch(t){this.logger.err("Failed initialized store manager: ",t)}return this}static get(){if(!u.instance)throw new Error("Store manager is not initialized.");return u.instance}getStores(){return this.stores}getStoresRelations(){return this.storesRelations}getSuspenseRelations(){return this.suspenseRelations}static getPersistedStoresIds(){return u.persistedStores}pushInitState=(t={})=>{for(const[e,s]of Object.entries(t))this.initState[e]=s};getStoreId(t,e={}){const{id:s,contextId:o,key:r}=e;if(s)return s;if(t.libStoreId)return t.libStoreId;let i=t.id||t.name||t.constructor.name;return t.isGlobal?i:(i=`${i}--${o}`,r?`${i}--${r}`:i)}getStore(t,e={}){const s=this.getStoreId(t,e);return this.stores.has(s)?this.stores.get(s):t.isGlobal?this.createStore(t,{id:s,contextId:"global",parentId:o,suspenseId:"",componentName:"root-app",componentProps:{}}):this.lookupStore(s,e)}lookupStore(t,e){const{contextId:s,parentId:r}=e,i=t.split("--")?.[0],{ids:n,parentId:a}=this.storesRelations.get(s)??{ids:new Set,parentId:r},l=[...n].filter((t=>t.startsWith(`${i}--`)));if(1===l.length)return this.stores.get(l[0]);if(l.length>1)this.logger.err("Parent context has multiple stores with the same id, please pass key to getStore function.");else if(a&&a!==o)return this.lookupStore(t,{contextId:this.getBiggerContext(a,r)})}getBiggerContext(t,e){if(!t)return e;if(!e)return t;const s=/[^a-zA-Z]/g;return t.replace(s,"")>e.replace(s,"")?t:e}createStore(e,s){const{id:r,contextId:n,parentId:a,suspenseId:l,componentName:h,componentProps:d}=s;if(this.stores.has(r))return this.stores.get(r);const p=new e({...this.storesParams,storeManager:this,getStore:(t,e={contextId:n,parentId:a})=>this.getStore(t,e),componentProps:d,initState:this.initState[r]});return p.libStoreId=r,p.isGlobal=e.isGlobal,p.libStoreContextId=e.isGlobal?"global":n,p.libStoreParentId=e.isGlobal||!a||a===n?o:a,p.libStoreSuspenseId=l,p.libStoreComponentName=h,this.setStoreStatus(p,e.isGlobal?S.inUse:S.init),this.prepareStore(p),t.publish(i.CREATE_STORE,{store:e}),p}createStores(t,e,s,o,r,i={}){const{failedCreationStrategy:n}=this.options,a=t.reduce(((t,[a,l])=>{const{id:h,store:d,isParent:p=!1}="store"in l?l:{store:l,id:void 0,isParent:!1};let S=h||(p?this.getStore(d,{contextId:s,parentId:e})?.libStoreId:this.getStoreId(d,{key:a,contextId:s}));if(!S){const i=`Cannot find or create store '${a}': '${this.getStoreId(d)}'`;if(this.logger.warn(i),this.logger.debug(i,{contextId:s,parentId:e,suspenseId:o,componentName:r,isParent:p},!0),"dummy"!==n)return"empty"===n&&(t.hasCreationFailure=!0),t;S=this.getStoreId(d,{key:a,contextId:s})}const c=this.createStore(d,{id:S,contextId:s,parentId:e,suspenseId:o,componentName:r,componentProps:i});return p?t.parentStores[a]=c:c.isGlobal?t.globalStores[a]=c:t.relativeStores[a]=c,t}),{relativeStores:{},parentStores:{},globalStores:{},hasCreationFailure:!1});return this.createRelationContext(s,e,r),a}createRelationContext(t,e,s){this.storesRelations.has(t)||this.storesRelations.set(t,{ids:new Set,parentId:e&&e!==t?e:o,componentName:s})}removeRelationContext(t){const e=this.storesRelations.get(t);!e||t===o||e.ids.size>0||this.storesRelations.delete(t)}prepareStore(t){const e=t.libStoreId,s=t.libStoreContextId,o=t.libStoreSuspenseId;if(this.stores.has(e))return;const i=this.initState[e];if(i&&r(t,i),"wakeup"in t&&u.persistedStores.has(e)&&t.wakeup?.({initState:i,persistedState:this.storage?.getStoreData(t),manager:this}),u.persistedStores.has(e)&&"addOnChangeListener"in t){const e=t.onDestroy?.bind(t),s=t.addOnChangeListener(t,this);t.onDestroy=()=>{s?.(),e?.()}}t.init?.(),this.createRelationContext(s,t.libStoreParentId,t.libStoreComponentName),this.suspenseRelations.has(o)||this.suspenseRelations.set(o,new Set);const{ids:n}=this.storesRelations.get(s);this.stores.set(e,t),n.add(e),this.suspenseRelations.get(o).add(e)}removeStore(e){const s=e.libStoreId,o=e.libStoreSuspenseId,{ids:r}=this.storesRelations.get(e.libStoreContextId)??{ids:new Set};this.stores.has(s)&&(this.stores.delete(s),r.delete(s),o&&this.suspenseRelations.get(o)?.has(s)&&this.suspenseRelations.get(o).delete(s),this.removeRelationContext(e.libStoreContextId),"onDestroy"in e&&e.onDestroy?.(),t.publish(i.DELETE_STORE,{store:e}))}mountStores(e,{globalStores:s={},relativeStores:o={}}){const{shouldRemoveInitState:r}=this.options,n={...s,...o};return Object.values(n).forEach((e=>{const s=e.libStoreId;r&&this.initState[s]&&delete this.initState[s],this.setStoreStatus(e,S.inUse),t.publish(i.MOUNT_STORE,{store:e})})),()=>{Object.values(n).forEach((e=>{e.isGlobal||(this.setStoreStatus(e,S.unused),t.publish(i.UNMOUNT_STORE,{store:e}))})),this.removeRelationContext(e)}}touchedStores(t){Object.values(t).forEach((t=>{t.libStoreStatus!==S.init||t.isGlobal||this.setStoreStatus(t,S.touched)}))}setStoreStatus(t,e){const{destroyTimers:{init:s=500,touched:o=1e4,unused:r=1e3}={}}=this.options;t.libStoreStatus=e,clearTimeout(t.libDestroyTimer);let i=0;switch(e){case S.init:i=s;break;case S.touched:i=o;break;case S.unused:i=r}i&&(t.libDestroyTimer=setTimeout((()=>this.removeStore(t)),i))}getStoreState(t,e=!1){return t.toJSON?.()??u.getObservableProps(t,e)}toJSON(t,e=!1){const s={},o=Array.isArray(t)?t.reduce(((t,e)=>(this.stores.has(e)&&t.set(e,this.stores.get(e)),t)),new Map):this.stores;for(const[t,r]of o.entries())s[t]=this.getStoreState(r,e);return s}async savePersistedStore(t){if(this.options.shouldDisablePersist||!this.storage)return!1;try{return await this.storage.saveStoreData(t,this.getStoreState(t,!0)),!0}catch(t){this.logger.err("Failed to persist stores: ",t)}return!1}static getObservableProps(t,o=!1){const r=e(t);return Object.entries(r).reduce(((e,[r,i])=>({...e,...s(t,r)&&!a(t,r,o)||l(t,r)?{[r]:i}:{},...h(t,r)?{[r]:u.getObservableProps(t[r])}:{}})),{})}static persistStore(t,e,s={}){return u.persistedStores.add(e),t.libStoreId=e,"libStorageOptions"in t.prototype||(t.prototype.libStorageOptions=s),"wakeup"in t.prototype||(t.prototype.wakeup=c),"addOnChangeListener"in t.prototype||(t.prototype.addOnChangeListener=d),t}}export{u as default};
|
|
2
2
|
//# sourceMappingURL=manager.js.map
|
package/manager.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","sources":["../src/manager.ts"],"sourcesContent":["import EventManager from '@lomray/event-manager';\nimport { isObservableProp, toJS } from 'mobx';\nimport { ROOT_CONTEXT_ID } from './constants';\nimport deepMerge from './deep-merge';\nimport Events from './events';\nimport Logger from './logger';\nimport {\n isPropExcludedFromExport,\n isPropObservableExported,\n isPropSimpleExported,\n} from './make-exported';\nimport onChangeListener from './on-change-listener';\nimport CombinedStorage from './storages/combined-storage';\nimport StoreStatus from './store-status';\nimport type {\n IConstructableStore,\n IGroupedStores,\n IManagerOptions,\n IManagerParams,\n IPersistOptions,\n IStoreParams,\n IStorePersisted,\n TAnyStore,\n TInitStore,\n TStoreDefinition,\n TStores,\n} from './types';\nimport wakeup from './wakeup';\n\n/**\n * Mobx stores manager\n */\nclass Manager {\n /**\n * Manger instance\n */\n protected static instance: Manager;\n\n /**\n * Created stores\n */\n protected readonly stores = new Map<string, TInitStore>();\n\n /**\n * Relations between stores\n */\n protected readonly storesRelations = new Map<\n string, // contextId\n { ids: Set<string>; parentId: string | null; componentName?: string }\n >();\n\n /**\n * Save persisted stores identities\n */\n protected static readonly persistedStores = new Set<string>();\n\n /**\n * Initial stores state (local storage, custom etc.)\n */\n protected readonly initState: Record<string, any>;\n\n /**\n * Storage for persisted stores\n */\n public readonly storage?: CombinedStorage;\n\n /**\n * Additional store's constructor params\n */\n protected readonly storesParams: IManagerParams['storesParams'];\n\n /**\n * Manager options\n */\n public readonly options: IManagerOptions = {\n shouldDisablePersist: false,\n shouldRemoveInitState: true,\n };\n\n /**\n * Suspense stores relations\n * @see withStores\n */\n protected suspenseRelations: Map<string, Set<string>> = new Map();\n\n /**\n * Mobx manager logger\n */\n protected readonly logger: Logger;\n\n /**\n * @constructor\n */\n public constructor({ initState, storesParams, storage, options, logger }: IManagerParams = {}) {\n this.initState = initState || {};\n this.storesParams = storesParams || {};\n this.logger =\n logger && 'log' in logger\n ? logger\n : new Logger({ level: 3, ...(logger ?? {}), manager: this });\n this.storage =\n storage instanceof CombinedStorage\n ? storage\n : storage\n ? new CombinedStorage({ default: storage })\n : undefined;\n\n Object.assign(this.options, options || {});\n\n Manager.instance = this;\n\n // only client side\n if (typeof window !== 'undefined') {\n const state = window.mbxM;\n\n window.mbxM = { push: this.pushInitState };\n\n (Array.isArray(state) ? state : []).forEach(this.pushInitState);\n }\n }\n\n /**\n * Init store manager\n */\n public async init(): Promise<Manager> {\n try {\n if (this.storage) {\n await this.storage.get();\n }\n } catch (e) {\n this.logger.err('Failed initialized store manager: ', e);\n }\n\n return this;\n }\n\n /**\n * Get manager instance\n */\n public static get(): Manager {\n if (!Manager.instance) {\n throw new Error('Store manager is not initialized.');\n }\n\n return Manager.instance;\n }\n\n /**\n * Get all stores\n */\n public getStores(): Manager['stores'] {\n return this.stores;\n }\n\n /**\n * Get stores relations\n */\n public getStoresRelations(): Manager['storesRelations'] {\n return this.storesRelations;\n }\n\n /**\n * Get suspense relations with stores\n */\n public getSuspenseRelations(): Manager['suspenseRelations'] {\n return this.suspenseRelations;\n }\n\n /**\n * Get persisted stores ids\n */\n public static getPersistedStoresIds(): Set<string> {\n return Manager.persistedStores;\n }\n\n /**\n * Push initial state dynamically\n * E.g. when stream html\n */\n public pushInitState = (storesState: Record<string, any> = {}): void => {\n for (const [storeId, state] of Object.entries(storesState)) {\n this.initState[storeId] = state;\n }\n };\n\n /**\n * Get store identity\n */\n protected getStoreId<T extends TAnyStore>(\n store: IConstructableStore<T> | TInitStore,\n params: IStoreParams = {},\n ): string {\n const { id, contextId, key } = params;\n\n if (id) {\n return id;\n }\n\n if (store.libStoreId) {\n return store.libStoreId;\n }\n\n let storeId = (store['id'] as string) || (store['name'] as string) || store.constructor.name;\n\n if (store.isGlobal) {\n return storeId;\n }\n\n storeId = `${storeId}--${contextId!}`;\n\n return key ? `${storeId}--${key}` : storeId;\n }\n\n /**\n * Get exist store\n */\n public getStore<T>(store: IConstructableStore<T>, params: IStoreParams = {}): T | undefined {\n const storeId = this.getStoreId(store, params);\n\n // full match\n if (this.stores.has(storeId)) {\n return this.stores.get(storeId) as T;\n }\n\n // in case with global store (create if not exist)\n if (store.isGlobal) {\n return this.createStore(store, {\n id: storeId,\n contextId: 'global',\n parentId: ROOT_CONTEXT_ID,\n suspenseId: '',\n componentName: 'root-app',\n componentProps: {},\n });\n }\n\n // try to look up store in current or parent context\n return this.lookupStore(storeId, params) as T;\n }\n\n /**\n * Lookup store\n */\n protected lookupStore(id: string, params: IStoreParams): TInitStore<TAnyStore> | undefined {\n const { contextId, parentId: defaultParentId } = params;\n const clearId = id.split('--')?.[0];\n const { ids, parentId } = this.storesRelations.get(contextId!) ?? {\n ids: new Set(),\n parentId: defaultParentId,\n };\n\n const matchedIds = [...ids].filter((storeId) => storeId.startsWith(`${clearId}--`));\n\n if (matchedIds.length === 1) {\n return this.stores.get(matchedIds[0]);\n } else if (matchedIds.length > 1) {\n this.logger.err(\n 'Parent context has multiple stores with the same id, please pass key to getStore function.',\n );\n\n return undefined;\n }\n\n if (!parentId || parentId === ROOT_CONTEXT_ID) {\n return undefined;\n }\n\n return this.lookupStore(id, { contextId: this.getBiggerContext(parentId, defaultParentId) });\n }\n\n /**\n * Get bigger context from two\n */\n protected getBiggerContext(ctx1?: string, ctx2?: string): string | undefined {\n if (!ctx1) {\n return ctx2;\n } else if (!ctx2) {\n return ctx1;\n }\n\n const regexp = /[^a-zA-Z]/g;\n\n return ctx1.replace(regexp, '') > ctx2.replace(regexp, '') ? ctx1 : ctx2;\n }\n\n /**\n * Create new store instance\n */\n protected createStore<T>(\n store: IConstructableStore<T>,\n params: Omit<Required<IStoreParams>, 'key'>,\n ): T {\n const { id, contextId, parentId, suspenseId, componentName, componentProps } = params;\n\n // only for global store\n if (this.stores.has(id)) {\n return this.stores.get(id) as T;\n }\n\n const newStore = new store({\n ...this.storesParams,\n storeManager: this,\n getStore: <TS>(\n targetStore: IConstructableStore<TS>,\n targetParams = { contextId, parentId },\n ) => this.getStore(targetStore, targetParams),\n componentProps,\n initState: this.initState[id],\n });\n\n // assign params to new store\n newStore.libStoreId = id;\n newStore.isGlobal = store.isGlobal;\n newStore.libStoreContextId = store.isGlobal ? 'global' : contextId;\n newStore.libStoreParentId =\n store.isGlobal || !parentId || parentId === contextId ? ROOT_CONTEXT_ID : parentId;\n newStore.libStoreSuspenseId = suspenseId;\n newStore.libStoreComponentName = componentName;\n\n this.setStoreStatus(newStore, store.isGlobal ? StoreStatus.inUse : StoreStatus.init);\n this.prepareStore(newStore);\n EventManager.publish(Events.CREATE_STORE, { store });\n\n return newStore as T;\n }\n\n /**\n * Create stores for component\n *\n * NOTE: use only inside withStores wrapper\n */\n public createStores(\n map: [string, TStoreDefinition][],\n parentId: string,\n contextId: string,\n suspenseId: string,\n componentName: string,\n componentProps: Record<string, any> = {},\n ): IGroupedStores {\n const result = map.reduce(\n (res, [key, store]) => {\n const {\n id,\n store: s,\n isParent = false,\n } = 'store' in store ? store : { store, id: undefined, isParent: false };\n const storeId =\n id ||\n (isParent\n ? (this.getStore(s, { contextId, parentId })?.libStoreId as string)\n : this.getStoreId(s, { key, contextId }));\n\n if (!storeId) {\n const msg = `Cannot find or create store '${key}': '${this.getStoreId(s)}'`;\n\n this.logger.warn(msg);\n this.logger.debug(\n msg,\n { contextId, parentId, suspenseId, componentName, isParent },\n true,\n );\n\n return res;\n }\n\n const storeInstance = this.createStore(s, {\n id: storeId,\n contextId,\n parentId,\n suspenseId,\n componentName,\n componentProps,\n });\n\n if (isParent) {\n res.parentStores[key] = storeInstance;\n } else if (storeInstance.isGlobal) {\n res.globalStores[key] = storeInstance;\n } else {\n res.relativeStores[key] = storeInstance;\n }\n\n return res;\n },\n { relativeStores: {}, parentStores: {}, globalStores: {} },\n );\n\n // need create context relation in case when component doesn't include relative stores\n this.createRelationContext(contextId, parentId, componentName);\n\n return result;\n }\n\n /**\n * Create empty relation context\n */\n protected createRelationContext(\n contextId: string,\n parentId?: string,\n componentName?: string,\n ): void {\n if (this.storesRelations.has(contextId)) {\n return;\n }\n\n this.storesRelations.set(contextId, {\n ids: new Set(),\n parentId: !parentId || parentId === contextId ? ROOT_CONTEXT_ID : parentId,\n componentName,\n });\n }\n\n /**\n * Delete relation context id\n */\n protected removeRelationContext(contextId: string): void {\n const storesRelations = this.storesRelations.get(contextId);\n\n if (!storesRelations || contextId === ROOT_CONTEXT_ID || storesRelations.ids.size > 0) {\n return;\n }\n\n this.storesRelations.delete(contextId);\n }\n\n /**\n * Prepare store before usage\n */\n protected prepareStore(store: TStores[string]): void {\n const storeId = store.libStoreId!;\n const contextId = store.libStoreContextId!;\n const suspenseId = store.libStoreSuspenseId!;\n\n if (this.stores.has(storeId)) {\n return;\n }\n\n // restore initial state from server\n const initState = this.initState[storeId];\n\n if (initState) {\n deepMerge(store, initState);\n }\n\n // restore persisted state\n if ('wakeup' in store && Manager.persistedStores.has(storeId)) {\n store.wakeup?.({\n initState,\n persistedState: this.storage?.getStoreData(store),\n manager: this,\n });\n }\n\n // track changes in persisted store\n if (Manager.persistedStores.has(storeId) && 'addOnChangeListener' in store) {\n const onDestroyDefault = store.onDestroy?.bind(store);\n const removeListener = store.addOnChangeListener!(store, this);\n\n store.onDestroy = () => {\n removeListener?.();\n onDestroyDefault?.();\n };\n }\n\n store.init?.();\n this.createRelationContext(contextId, store.libStoreParentId, store.libStoreComponentName);\n\n if (!this.suspenseRelations.has(suspenseId)) {\n this.suspenseRelations.set(suspenseId, new Set());\n }\n\n const { ids } = this.storesRelations.get(contextId)!;\n\n // add store to manager\n this.stores.set(storeId, store);\n ids.add(storeId);\n // add store relation with suspense\n this.suspenseRelations.get(suspenseId)!.add(storeId);\n }\n\n /**\n * Remove store\n */\n protected removeStore(store: TStores[string]): void {\n const storeId = store.libStoreId!;\n const suspenseId = store.libStoreSuspenseId!;\n const { ids } = this.storesRelations.get(store.libStoreContextId!) ?? { ids: new Set() };\n\n if (!this.stores.has(storeId)) {\n return;\n }\n\n this.stores.delete(storeId);\n ids.delete(storeId);\n\n if (suspenseId && this.suspenseRelations.get(suspenseId)?.has(storeId)) {\n this.suspenseRelations.get(suspenseId)!.delete(storeId);\n }\n\n this.removeRelationContext(store.libStoreContextId!);\n\n if ('onDestroy' in store) {\n store.onDestroy?.();\n }\n\n EventManager.publish(Events.DELETE_STORE, { store });\n }\n\n /**\n * Mount stores to component\n *\n * NOTE: use only inside withStores wrapper\n */\n public mountStores(\n contextId: string,\n { globalStores = {}, relativeStores = {} }: Partial<IGroupedStores>,\n ): () => void {\n const { shouldRemoveInitState } = this.options;\n const touchableStores = { ...globalStores, ...relativeStores };\n\n Object.values(touchableStores).forEach((store) => {\n const storeId = store.libStoreId!;\n\n // cleanup init state\n if (shouldRemoveInitState && this.initState[storeId]) {\n delete this.initState[storeId];\n }\n\n this.setStoreStatus(store, StoreStatus.inUse);\n EventManager.publish(Events.MOUNT_STORE, { store });\n });\n\n return () => {\n Object.values(touchableStores).forEach((store) => {\n if (store.isGlobal) {\n return;\n }\n\n this.setStoreStatus(store, StoreStatus.unused);\n EventManager.publish(Events.UNMOUNT_STORE, { store });\n });\n\n this.removeRelationContext(contextId);\n };\n }\n\n /**\n * Change the stores status to touched\n */\n public touchedStores(stores: TStores): void {\n Object.values(stores).forEach((store) => {\n if (store.libStoreStatus !== StoreStatus.init || store.isGlobal) {\n return;\n }\n\n this.setStoreStatus(store, StoreStatus.touched);\n });\n }\n\n /**\n * Change store status\n */\n protected setStoreStatus(store: TStores[string], status: StoreStatus): void {\n const { destroyTimers: { init = 500, touched = 10000, unused = 1000 } = {} } = this.options;\n\n store.libStoreStatus = status;\n\n clearTimeout(store.libDestroyTimer);\n\n let destroyTime = 0;\n\n switch (status) {\n case StoreStatus.init:\n destroyTime = init;\n break;\n\n case StoreStatus.touched:\n destroyTime = touched;\n break;\n\n case StoreStatus.unused:\n destroyTime = unused;\n break;\n }\n\n if (!destroyTime) {\n return;\n }\n\n store.libDestroyTimer = setTimeout(() => this.removeStore(store), destroyTime);\n }\n\n /**\n * Get store state\n */\n public getStoreState(store: TAnyStore, withNotExported = false): Record<string, any> {\n return store.toJSON?.() ?? Manager.getObservableProps(store, withNotExported);\n }\n\n /**\n * Get store's state\n */\n public toJSON(ids?: string[], isIncludeExported = false): Record<string, any> {\n const result = {};\n const stores = Array.isArray(ids)\n ? ids.reduce((res, id) => {\n if (this.stores.has(id)) {\n res.set(id, this.stores.get(id)!);\n }\n\n return res;\n }, new Map<string, TInitStore>())\n : this.stores;\n\n for (const [storeId, store] of stores.entries()) {\n result[storeId] = this.getStoreState(store, isIncludeExported);\n }\n\n return result;\n }\n\n /**\n * Save persisted store state to provided storage\n */\n public async savePersistedStore(store: IStorePersisted): Promise<boolean> {\n if (this.options.shouldDisablePersist || !this.storage) {\n return false;\n }\n\n try {\n await this.storage.saveStoreData(store, this.getStoreState(store, true));\n\n return true;\n } catch (e) {\n this.logger.err('Failed to persist stores: ', e);\n }\n\n return false;\n }\n\n /**\n * Get observable store props (fields)\n */\n public static getObservableProps(store: TAnyStore, withNotExported = false): Record<string, any> {\n const props = toJS(store);\n\n return Object.entries(props).reduce(\n (res, [prop, value]) => ({\n ...res,\n ...((isObservableProp(store, prop) &&\n !isPropExcludedFromExport(store, prop, withNotExported)) ||\n isPropSimpleExported(store, prop)\n ? { [prop]: value }\n : {}),\n ...(isPropObservableExported(store, prop)\n ? { [prop]: Manager.getObservableProps(store[prop] as TAnyStore) }\n : {}),\n }),\n {},\n );\n }\n\n /**\n * Persist store\n */\n public static persistStore<TSt>(\n store: IConstructableStore<TSt>,\n id: string,\n options: IPersistOptions = {},\n ): IConstructableStore<TSt> {\n Manager.persistedStores.add(id);\n\n store.libStoreId = id;\n\n // add storage options\n if (!('libStorageOptions' in store.prototype)) {\n store.prototype.libStorageOptions = options;\n }\n\n // add default wakeup handler\n if (!('wakeup' in store.prototype)) {\n store.prototype.wakeup = wakeup;\n }\n\n // add default changes listener\n if (!('addOnChangeListener' in store.prototype)) {\n store.prototype.addOnChangeListener = onChangeListener;\n }\n\n return store;\n }\n}\n\nexport default Manager;\n"],"names":["Manager","static","stores","Map","storesRelations","Set","initState","storage","storesParams","options","shouldDisablePersist","shouldRemoveInitState","suspenseRelations","logger","constructor","this","Logger","level","manager","CombinedStorage","default","undefined","Object","assign","instance","window","state","mbxM","push","pushInitState","Array","isArray","forEach","async","get","e","err","Error","getStores","getStoresRelations","getSuspenseRelations","persistedStores","storesState","storeId","entries","getStoreId","store","params","id","contextId","key","libStoreId","name","isGlobal","getStore","has","createStore","parentId","ROOT_CONTEXT_ID","suspenseId","componentName","componentProps","lookupStore","defaultParentId","clearId","split","ids","matchedIds","filter","startsWith","length","getBiggerContext","ctx1","ctx2","regexp","replace","newStore","storeManager","targetStore","targetParams","libStoreContextId","libStoreParentId","libStoreSuspenseId","libStoreComponentName","setStoreStatus","StoreStatus","inUse","init","prepareStore","EventManager","publish","Events","CREATE_STORE","createStores","map","result","reduce","res","s","isParent","msg","warn","debug","storeInstance","parentStores","globalStores","relativeStores","createRelationContext","set","removeRelationContext","size","delete","deepMerge","wakeup","persistedState","getStoreData","onDestroyDefault","onDestroy","bind","removeListener","addOnChangeListener","add","removeStore","DELETE_STORE","mountStores","touchableStores","values","MOUNT_STORE","unused","UNMOUNT_STORE","touchedStores","libStoreStatus","touched","status","destroyTimers","clearTimeout","libDestroyTimer","destroyTime","setTimeout","getStoreState","withNotExported","toJSON","getObservableProps","isIncludeExported","saveStoreData","props","toJS","prop","value","isObservableProp","isPropExcludedFromExport","isPropSimpleExported","isPropObservableExported","prototype","libStorageOptions","onChangeListener"],"mappings":"oeAgCA,MAAMA,EAIMC,gBAKSC,OAAS,IAAIC,IAKbC,gBAAkB,IAAID,IAQ/BF,uBAAkC,IAAII,IAK7BC,UAKHC,QAKGC,aAKHC,QAA2B,CACzCC,sBAAsB,EACtBC,uBAAuB,GAOfC,kBAA8C,IAAIT,IAKzCU,OAKnBC,aAAmBR,UAAEA,EAASE,aAAEA,EAAYD,QAAEA,EAAOE,QAAEA,EAAOI,OAAEA,GAA2B,IAmBzF,GAlBAE,KAAKT,UAAYA,GAAa,GAC9BS,KAAKP,aAAeA,GAAgB,GACpCO,KAAKF,OACHA,GAAU,QAASA,EACfA,EACA,IAAIG,EAAO,CAAEC,MAAO,KAAOJ,GAAU,GAAKK,QAASH,OACzDA,KAAKR,QACHA,aAAmBY,EACfZ,EACAA,EACE,IAAIY,EAAgB,CAAEC,QAASb,SAC/Bc,EAERC,OAAOC,OAAOR,KAAKN,QAASA,GAAW,CAAE,GAEzCT,EAAQwB,SAAWT,KAGG,oBAAXU,OAAwB,CACjC,MAAMC,EAAQD,OAAOE,KAErBF,OAAOE,KAAO,CAAEC,KAAMb,KAAKc,gBAE1BC,MAAMC,QAAQL,GAASA,EAAQ,IAAIM,QAAQjB,KAAKc,cAClD,CACF,CAKMI,aACL,IACMlB,KAAKR,eACDQ,KAAKR,QAAQ2B,KAEtB,CAAC,MAAOC,GACPpB,KAAKF,OAAOuB,IAAI,qCAAsCD,EACvD,CAED,OAAOpB,IACR,CAKMd,aACL,IAAKD,EAAQwB,SACX,MAAM,IAAIa,MAAM,qCAGlB,OAAOrC,EAAQwB,QAChB,CAKMc,YACL,OAAOvB,KAAKb,MACb,CAKMqC,qBACL,OAAOxB,KAAKX,eACb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G,YACnC3G,EAAM2G,UAAUjC,oBAAsBmC,GAGjC7G,CACR"}
|
|
1
|
+
{"version":3,"file":"manager.js","sources":["../src/manager.ts"],"sourcesContent":["import EventManager from '@lomray/event-manager';\nimport { isObservableProp, toJS } from 'mobx';\nimport { ROOT_CONTEXT_ID } from './constants';\nimport deepMerge from './deep-merge';\nimport Events from './events';\nimport Logger from './logger';\nimport {\n isPropExcludedFromExport,\n isPropObservableExported,\n isPropSimpleExported,\n} from './make-exported';\nimport onChangeListener from './on-change-listener';\nimport CombinedStorage from './storages/combined-storage';\nimport StoreStatus from './store-status';\nimport type {\n IConstructableStore,\n IGroupedStores,\n IManagerOptions,\n IManagerParams,\n IPersistOptions,\n IStoreParams,\n IStorePersisted,\n TAnyStore,\n TInitStore,\n TStoreDefinition,\n TStores,\n} from './types';\nimport wakeup from './wakeup';\n\n/**\n * Mobx stores manager\n */\nclass Manager {\n /**\n * Manger instance\n */\n protected static instance: Manager;\n\n /**\n * Created stores\n */\n protected readonly stores = new Map<string, TInitStore>();\n\n /**\n * Relations between stores\n */\n protected readonly storesRelations = new Map<\n string, // contextId\n { ids: Set<string>; parentId: string | null; componentName?: string }\n >();\n\n /**\n * Save persisted stores identities\n */\n protected static readonly persistedStores = new Set<string>();\n\n /**\n * Initial stores state (local storage, custom etc.)\n */\n protected readonly initState: Record<string, any>;\n\n /**\n * Storage for persisted stores\n */\n public readonly storage?: CombinedStorage;\n\n /**\n * Additional store's constructor params\n */\n protected readonly storesParams: IManagerParams['storesParams'];\n\n /**\n * Manager options\n */\n public readonly options: IManagerOptions = {\n shouldDisablePersist: false,\n shouldRemoveInitState: true,\n failedCreationStrategy: 'empty',\n };\n\n /**\n * Suspense stores relations\n * @see withStores\n */\n protected suspenseRelations: Map<string, Set<string>> = new Map();\n\n /**\n * Mobx manager logger\n */\n protected readonly logger: Logger;\n\n /**\n * @constructor\n */\n public constructor({ initState, storesParams, storage, options, logger }: IManagerParams = {}) {\n this.initState = initState || {};\n this.storesParams = storesParams || {};\n this.logger =\n logger && 'log' in logger\n ? logger\n : new Logger({ level: 3, ...(logger ?? {}), manager: this });\n this.storage =\n storage instanceof CombinedStorage\n ? storage\n : storage\n ? new CombinedStorage({ default: storage })\n : undefined;\n\n Object.assign(this.options, options || {});\n\n Manager.instance = this;\n\n // only client side\n if (typeof window !== 'undefined') {\n const state = window.mbxM;\n\n window.mbxM = { push: this.pushInitState };\n\n (Array.isArray(state) ? state : []).forEach(this.pushInitState);\n }\n }\n\n /**\n * Init store manager\n */\n public async init(): Promise<Manager> {\n try {\n if (this.storage) {\n await this.storage.get();\n }\n } catch (e) {\n this.logger.err('Failed initialized store manager: ', e);\n }\n\n return this;\n }\n\n /**\n * Get manager instance\n */\n public static get(): Manager {\n if (!Manager.instance) {\n throw new Error('Store manager is not initialized.');\n }\n\n return Manager.instance;\n }\n\n /**\n * Get all stores\n */\n public getStores(): Manager['stores'] {\n return this.stores;\n }\n\n /**\n * Get stores relations\n */\n public getStoresRelations(): Manager['storesRelations'] {\n return this.storesRelations;\n }\n\n /**\n * Get suspense relations with stores\n */\n public getSuspenseRelations(): Manager['suspenseRelations'] {\n return this.suspenseRelations;\n }\n\n /**\n * Get persisted stores ids\n */\n public static getPersistedStoresIds(): Set<string> {\n return Manager.persistedStores;\n }\n\n /**\n * Push initial state dynamically\n * E.g. when stream html\n */\n public pushInitState = (storesState: Record<string, any> = {}): void => {\n for (const [storeId, state] of Object.entries(storesState)) {\n this.initState[storeId] = state;\n }\n };\n\n /**\n * Get store identity\n */\n protected getStoreId<T extends TAnyStore>(\n store: IConstructableStore<T> | TInitStore,\n params: IStoreParams = {},\n ): string {\n const { id, contextId, key } = params;\n\n if (id) {\n return id;\n }\n\n if (store.libStoreId) {\n return store.libStoreId;\n }\n\n let storeId = (store['id'] as string) || (store['name'] as string) || store.constructor.name;\n\n if (store.isGlobal) {\n return storeId;\n }\n\n storeId = `${storeId}--${contextId!}`;\n\n return key ? `${storeId}--${key}` : storeId;\n }\n\n /**\n * Get exist store\n */\n public getStore<T>(store: IConstructableStore<T>, params: IStoreParams = {}): T | undefined {\n const storeId = this.getStoreId(store, params);\n\n // full match\n if (this.stores.has(storeId)) {\n return this.stores.get(storeId) as T;\n }\n\n // in case with global store (create if not exist)\n if (store.isGlobal) {\n return this.createStore(store, {\n id: storeId,\n contextId: 'global',\n parentId: ROOT_CONTEXT_ID,\n suspenseId: '',\n componentName: 'root-app',\n componentProps: {},\n });\n }\n\n // try to look up store in current or parent context\n return this.lookupStore(storeId, params) as T;\n }\n\n /**\n * Lookup store\n */\n protected lookupStore(id: string, params: IStoreParams): TInitStore<TAnyStore> | undefined {\n const { contextId, parentId: defaultParentId } = params;\n const clearId = id.split('--')?.[0];\n const { ids, parentId } = this.storesRelations.get(contextId!) ?? {\n ids: new Set(),\n parentId: defaultParentId,\n };\n\n const matchedIds = [...ids].filter((storeId) => storeId.startsWith(`${clearId}--`));\n\n if (matchedIds.length === 1) {\n return this.stores.get(matchedIds[0]);\n } else if (matchedIds.length > 1) {\n this.logger.err(\n 'Parent context has multiple stores with the same id, please pass key to getStore function.',\n );\n\n return undefined;\n }\n\n if (!parentId || parentId === ROOT_CONTEXT_ID) {\n return undefined;\n }\n\n return this.lookupStore(id, { contextId: this.getBiggerContext(parentId, defaultParentId) });\n }\n\n /**\n * Get bigger context from two\n */\n protected getBiggerContext(ctx1?: string, ctx2?: string): string | undefined {\n if (!ctx1) {\n return ctx2;\n } else if (!ctx2) {\n return ctx1;\n }\n\n const regexp = /[^a-zA-Z]/g;\n\n return ctx1.replace(regexp, '') > ctx2.replace(regexp, '') ? ctx1 : ctx2;\n }\n\n /**\n * Create new store instance\n */\n protected createStore<T>(\n store: IConstructableStore<T>,\n params: Omit<Required<IStoreParams>, 'key'>,\n ): T {\n const { id, contextId, parentId, suspenseId, componentName, componentProps } = params;\n\n // only for global store\n if (this.stores.has(id)) {\n return this.stores.get(id) as T;\n }\n\n const newStore = new store({\n ...this.storesParams,\n storeManager: this,\n getStore: <TS>(\n targetStore: IConstructableStore<TS>,\n targetParams = { contextId, parentId },\n ) => this.getStore(targetStore, targetParams),\n componentProps,\n initState: this.initState[id],\n });\n\n // assign params to new store\n newStore.libStoreId = id;\n newStore.isGlobal = store.isGlobal;\n newStore.libStoreContextId = store.isGlobal ? 'global' : contextId;\n newStore.libStoreParentId =\n store.isGlobal || !parentId || parentId === contextId ? ROOT_CONTEXT_ID : parentId;\n newStore.libStoreSuspenseId = suspenseId;\n newStore.libStoreComponentName = componentName;\n\n this.setStoreStatus(newStore, store.isGlobal ? StoreStatus.inUse : StoreStatus.init);\n this.prepareStore(newStore);\n EventManager.publish(Events.CREATE_STORE, { store });\n\n return newStore as T;\n }\n\n /**\n * Create stores for component\n *\n * NOTE: use only inside withStores wrapper\n */\n public createStores(\n map: [string, TStoreDefinition][],\n parentId: string,\n contextId: string,\n suspenseId: string,\n componentName: string,\n componentProps: Record<string, any> = {},\n ): IGroupedStores {\n const { failedCreationStrategy } = this.options;\n\n const result = map.reduce(\n (res, [key, store]) => {\n const {\n id,\n store: s,\n isParent = false,\n } = 'store' in store ? store : { store, id: undefined, isParent: false };\n let storeId =\n id ||\n (isParent\n ? (this.getStore(s, { contextId, parentId })?.libStoreId as string)\n : this.getStoreId(s, { key, contextId }));\n\n if (!storeId) {\n const msg = `Cannot find or create store '${key}': '${this.getStoreId(s)}'`;\n\n this.logger.warn(msg);\n this.logger.debug(\n msg,\n { contextId, parentId, suspenseId, componentName, isParent },\n true,\n );\n\n if (failedCreationStrategy === 'dummy') {\n // try to force create store\n storeId = this.getStoreId(s, { key, contextId });\n } else {\n if (failedCreationStrategy === 'empty') {\n res.hasCreationFailure = true;\n }\n\n return res;\n }\n }\n\n const storeInstance = this.createStore(s, {\n id: storeId,\n contextId,\n parentId,\n suspenseId,\n componentName,\n componentProps,\n });\n\n if (isParent) {\n res.parentStores[key] = storeInstance;\n } else if (storeInstance.isGlobal) {\n res.globalStores[key] = storeInstance;\n } else {\n res.relativeStores[key] = storeInstance;\n }\n\n return res;\n },\n { relativeStores: {}, parentStores: {}, globalStores: {}, hasCreationFailure: false },\n );\n\n // need create context relation in case when component doesn't include relative stores\n this.createRelationContext(contextId, parentId, componentName);\n\n return result;\n }\n\n /**\n * Create empty relation context\n */\n protected createRelationContext(\n contextId: string,\n parentId?: string,\n componentName?: string,\n ): void {\n if (this.storesRelations.has(contextId)) {\n return;\n }\n\n this.storesRelations.set(contextId, {\n ids: new Set(),\n parentId: !parentId || parentId === contextId ? ROOT_CONTEXT_ID : parentId,\n componentName,\n });\n }\n\n /**\n * Delete relation context id\n */\n protected removeRelationContext(contextId: string): void {\n const storesRelations = this.storesRelations.get(contextId);\n\n if (!storesRelations || contextId === ROOT_CONTEXT_ID || storesRelations.ids.size > 0) {\n return;\n }\n\n this.storesRelations.delete(contextId);\n }\n\n /**\n * Prepare store before usage\n */\n protected prepareStore(store: TStores[string]): void {\n const storeId = store.libStoreId!;\n const contextId = store.libStoreContextId!;\n const suspenseId = store.libStoreSuspenseId!;\n\n if (this.stores.has(storeId)) {\n return;\n }\n\n // restore initial state from server\n const initState = this.initState[storeId];\n\n if (initState) {\n deepMerge(store, initState);\n }\n\n // restore persisted state\n if ('wakeup' in store && Manager.persistedStores.has(storeId)) {\n store.wakeup?.({\n initState,\n persistedState: this.storage?.getStoreData(store),\n manager: this,\n });\n }\n\n // track changes in persisted store\n if (Manager.persistedStores.has(storeId) && 'addOnChangeListener' in store) {\n const onDestroyDefault = store.onDestroy?.bind(store);\n const removeListener = store.addOnChangeListener!(store, this);\n\n store.onDestroy = () => {\n removeListener?.();\n onDestroyDefault?.();\n };\n }\n\n store.init?.();\n this.createRelationContext(contextId, store.libStoreParentId, store.libStoreComponentName);\n\n if (!this.suspenseRelations.has(suspenseId)) {\n this.suspenseRelations.set(suspenseId, new Set());\n }\n\n const { ids } = this.storesRelations.get(contextId)!;\n\n // add store to manager\n this.stores.set(storeId, store);\n ids.add(storeId);\n // add store relation with suspense\n this.suspenseRelations.get(suspenseId)!.add(storeId);\n }\n\n /**\n * Remove store\n */\n protected removeStore(store: TStores[string]): void {\n const storeId = store.libStoreId!;\n const suspenseId = store.libStoreSuspenseId!;\n const { ids } = this.storesRelations.get(store.libStoreContextId!) ?? { ids: new Set() };\n\n if (!this.stores.has(storeId)) {\n return;\n }\n\n this.stores.delete(storeId);\n ids.delete(storeId);\n\n if (suspenseId && this.suspenseRelations.get(suspenseId)?.has(storeId)) {\n this.suspenseRelations.get(suspenseId)!.delete(storeId);\n }\n\n this.removeRelationContext(store.libStoreContextId!);\n\n if ('onDestroy' in store) {\n store.onDestroy?.();\n }\n\n EventManager.publish(Events.DELETE_STORE, { store });\n }\n\n /**\n * Mount stores to component\n *\n * NOTE: use only inside withStores wrapper\n */\n public mountStores(\n contextId: string,\n { globalStores = {}, relativeStores = {} }: Partial<IGroupedStores>,\n ): () => void {\n const { shouldRemoveInitState } = this.options;\n const touchableStores = { ...globalStores, ...relativeStores };\n\n Object.values(touchableStores).forEach((store) => {\n const storeId = store.libStoreId!;\n\n // cleanup init state\n if (shouldRemoveInitState && this.initState[storeId]) {\n delete this.initState[storeId];\n }\n\n this.setStoreStatus(store, StoreStatus.inUse);\n EventManager.publish(Events.MOUNT_STORE, { store });\n });\n\n return () => {\n Object.values(touchableStores).forEach((store) => {\n if (store.isGlobal) {\n return;\n }\n\n this.setStoreStatus(store, StoreStatus.unused);\n EventManager.publish(Events.UNMOUNT_STORE, { store });\n });\n\n this.removeRelationContext(contextId);\n };\n }\n\n /**\n * Change the stores status to touched\n */\n public touchedStores(stores: TStores): void {\n Object.values(stores).forEach((store) => {\n if (store.libStoreStatus !== StoreStatus.init || store.isGlobal) {\n return;\n }\n\n this.setStoreStatus(store, StoreStatus.touched);\n });\n }\n\n /**\n * Change store status\n */\n protected setStoreStatus(store: TStores[string], status: StoreStatus): void {\n const { destroyTimers: { init = 500, touched = 10000, unused = 1000 } = {} } = this.options;\n\n store.libStoreStatus = status;\n\n clearTimeout(store.libDestroyTimer);\n\n let destroyTime = 0;\n\n switch (status) {\n case StoreStatus.init:\n destroyTime = init;\n break;\n\n case StoreStatus.touched:\n destroyTime = touched;\n break;\n\n case StoreStatus.unused:\n destroyTime = unused;\n break;\n }\n\n if (!destroyTime) {\n return;\n }\n\n store.libDestroyTimer = setTimeout(() => this.removeStore(store), destroyTime);\n }\n\n /**\n * Get store state\n */\n public getStoreState(store: TAnyStore, withNotExported = false): Record<string, any> {\n return store.toJSON?.() ?? Manager.getObservableProps(store, withNotExported);\n }\n\n /**\n * Get store's state\n */\n public toJSON(ids?: string[], isIncludeExported = false): Record<string, any> {\n const result = {};\n const stores = Array.isArray(ids)\n ? ids.reduce((res, id) => {\n if (this.stores.has(id)) {\n res.set(id, this.stores.get(id)!);\n }\n\n return res;\n }, new Map<string, TInitStore>())\n : this.stores;\n\n for (const [storeId, store] of stores.entries()) {\n result[storeId] = this.getStoreState(store, isIncludeExported);\n }\n\n return result;\n }\n\n /**\n * Save persisted store state to provided storage\n */\n public async savePersistedStore(store: IStorePersisted): Promise<boolean> {\n if (this.options.shouldDisablePersist || !this.storage) {\n return false;\n }\n\n try {\n await this.storage.saveStoreData(store, this.getStoreState(store, true));\n\n return true;\n } catch (e) {\n this.logger.err('Failed to persist stores: ', e);\n }\n\n return false;\n }\n\n /**\n * Get observable store props (fields)\n */\n public static getObservableProps(store: TAnyStore, withNotExported = false): Record<string, any> {\n const props = toJS(store);\n\n return Object.entries(props).reduce(\n (res, [prop, value]) => ({\n ...res,\n ...((isObservableProp(store, prop) &&\n !isPropExcludedFromExport(store, prop, withNotExported)) ||\n isPropSimpleExported(store, prop)\n ? { [prop]: value }\n : {}),\n ...(isPropObservableExported(store, prop)\n ? { [prop]: Manager.getObservableProps(store[prop] as TAnyStore) }\n : {}),\n }),\n {},\n );\n }\n\n /**\n * Persist store\n */\n public static persistStore<TSt>(\n store: IConstructableStore<TSt>,\n id: string,\n options: IPersistOptions = {},\n ): IConstructableStore<TSt> {\n Manager.persistedStores.add(id);\n\n store.libStoreId = id;\n\n // add storage options\n if (!('libStorageOptions' in store.prototype)) {\n store.prototype.libStorageOptions = options;\n }\n\n // add default wakeup handler\n if (!('wakeup' in store.prototype)) {\n store.prototype.wakeup = wakeup;\n }\n\n // add default changes listener\n if (!('addOnChangeListener' in store.prototype)) {\n store.prototype.addOnChangeListener = onChangeListener;\n }\n\n return store;\n }\n}\n\nexport default Manager;\n"],"names":["Manager","static","stores","Map","storesRelations","Set","initState","storage","storesParams","options","shouldDisablePersist","shouldRemoveInitState","failedCreationStrategy","suspenseRelations","logger","constructor","this","Logger","level","manager","CombinedStorage","default","undefined","Object","assign","instance","window","state","mbxM","push","pushInitState","Array","isArray","forEach","async","get","e","err","Error","getStores","getStoresRelations","getSuspenseRelations","persistedStores","storesState","storeId","entries","getStoreId","store","params","id","contextId","key","libStoreId","name","isGlobal","getStore","has","createStore","parentId","ROOT_CONTEXT_ID","suspenseId","componentName","componentProps","lookupStore","defaultParentId","clearId","split","ids","matchedIds","filter","startsWith","length","getBiggerContext","ctx1","ctx2","regexp","replace","newStore","storeManager","targetStore","targetParams","libStoreContextId","libStoreParentId","libStoreSuspenseId","libStoreComponentName","setStoreStatus","StoreStatus","inUse","init","prepareStore","EventManager","publish","Events","CREATE_STORE","createStores","map","result","reduce","res","s","isParent","msg","warn","debug","hasCreationFailure","storeInstance","parentStores","globalStores","relativeStores","createRelationContext","set","removeRelationContext","size","delete","deepMerge","wakeup","persistedState","getStoreData","onDestroyDefault","onDestroy","bind","removeListener","addOnChangeListener","add","removeStore","DELETE_STORE","mountStores","touchableStores","values","MOUNT_STORE","unused","UNMOUNT_STORE","touchedStores","libStoreStatus","touched","status","destroyTimers","clearTimeout","libDestroyTimer","destroyTime","setTimeout","getStoreState","withNotExported","toJSON","getObservableProps","isIncludeExported","saveStoreData","props","toJS","prop","value","isObservableProp","isPropExcludedFromExport","isPropSimpleExported","isPropObservableExported","prototype","libStorageOptions","onChangeListener"],"mappings":"oeAgCA,MAAMA,EAIMC,gBAKSC,OAAS,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M4G,UAAUjC,oBAAsBmC,GAGjC9G,CACR"}
|
package/package.json
CHANGED
package/types.d.ts
CHANGED
|
@@ -77,6 +77,13 @@ interface IManagerOptions {
|
|
|
77
77
|
touched?: number;
|
|
78
78
|
unused?: number;
|
|
79
79
|
};
|
|
80
|
+
/**
|
|
81
|
+
* When for some strange reason stores cannot be created or found in the parent context:
|
|
82
|
+
* none: don't do anything
|
|
83
|
+
* dummy: force create empty store
|
|
84
|
+
* empty (default): don't render component if any of the stores not created
|
|
85
|
+
*/
|
|
86
|
+
failedCreationStrategy: 'none' | 'dummy' | 'empty';
|
|
80
87
|
}
|
|
81
88
|
type TAnyStore = IStore | IStorePersisted;
|
|
82
89
|
type TStores = {
|
|
@@ -124,6 +131,7 @@ interface IGroupedStores {
|
|
|
124
131
|
relativeStores: TStores;
|
|
125
132
|
parentStores: TStores;
|
|
126
133
|
globalStores: TStores;
|
|
134
|
+
hasCreationFailure: boolean;
|
|
127
135
|
}
|
|
128
136
|
interface IPersistOptions {
|
|
129
137
|
behaviour?: 'exclude' | 'include';
|
package/with-stores.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useConsistentSuspense as e,useId as t}from"@lomray/consistent-suspense";import o from"hoist-non-react-statics";import{observer as r}from"mobx-react-lite";import
|
|
1
|
+
import{useConsistentSuspense as e,useId as t}from"@lomray/consistent-suspense";import o from"hoist-non-react-statics";import{observer as r}from"mobx-react-lite";import s,{useState as a,useEffect as n}from"react";import{useStoreManager as m,useStoreManagerParent as c,StoreManagerParentProvider as i}from"./context.js";const l=(l,u,{customContextId:p}={})=>{const S=r(l),b=p||l.libStoreContextId,d=l.displayName||l.name,x=o=>{const r=m(),l=c(),{suspenseId:p}=e(),x=t(),[{contextId:f,hasFailure:h,touchableStores:I,componentStores:y,mountStores:j}]=a((()=>{const e=b||x,t=r.createStores(Object.entries(u),l,e,p,d,o),{globalStores:s,relativeStores:a,parentStores:n,hasCreationFailure:m}=t,c={...a,...s};return{contextId:e,hasFailure:m,touchableStores:c,componentStores:{...c,...n},mountStores:()=>r.mountStores(e,t)}}));return n(j,[j]),s.createElement(i,{parentId:f,touchableStores:I},!h&&s.createElement(S,{...o,...y}))};return o(x,l),x.displayName=`Mobx(${d})`,Object.defineProperty(x,"name",{value:x.displayName,writable:!1,enumerable:!1})};export{l as default};
|
|
2
2
|
//# sourceMappingURL=with-stores.js.map
|
package/with-stores.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"with-stores.js","sources":["../src/with-stores.tsx"],"sourcesContent":["import { useConsistentSuspense, useId } from '@lomray/consistent-suspense';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport { observer } from 'mobx-react-lite';\nimport type { FC } from 'react';\nimport React, { useEffect, useState } from 'react';\nimport { useStoreManager, useStoreManagerParent, StoreManagerParentProvider } from './context';\nimport type { TMapStores, IWithStoreOptions } from './types';\n\n/**\n * Make component observable and pass stores as props\n */\nconst withStores = <T extends Record<string, any>, TS extends TMapStores>(\n Component: FC<T>,\n stores: TS,\n { customContextId }: IWithStoreOptions = {},\n): FC<Omit<T, keyof TS>> => {\n const ObservableComponent = observer(Component) as FC;\n const manualContextId = customContextId || (Component['libStoreContextId'] as string);\n const componentName = Component.displayName || Component.name;\n\n const Element: FC<Omit<T, keyof TS>> = (props) => {\n const storeManager = useStoreManager();\n const parentId = useStoreManagerParent();\n const { suspenseId } = useConsistentSuspense();\n const id = useId();\n const [{ contextId,
|
|
1
|
+
{"version":3,"file":"with-stores.js","sources":["../src/with-stores.tsx"],"sourcesContent":["import { useConsistentSuspense, useId } from '@lomray/consistent-suspense';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport { observer } from 'mobx-react-lite';\nimport type { FC } from 'react';\nimport React, { useEffect, useState } from 'react';\nimport { useStoreManager, useStoreManagerParent, StoreManagerParentProvider } from './context';\nimport type { TMapStores, IWithStoreOptions } from './types';\n\n/**\n * Make component observable and pass stores as props\n */\nconst withStores = <T extends Record<string, any>, TS extends TMapStores>(\n Component: FC<T>,\n stores: TS,\n { customContextId }: IWithStoreOptions = {},\n): FC<Omit<T, keyof TS>> => {\n const ObservableComponent = observer(Component) as FC;\n const manualContextId = customContextId || (Component['libStoreContextId'] as string);\n const componentName = Component.displayName || Component.name;\n\n const Element: FC<Omit<T, keyof TS>> = (props) => {\n const storeManager = useStoreManager();\n const parentId = useStoreManagerParent();\n const { suspenseId } = useConsistentSuspense();\n const id = useId();\n const [{ contextId, hasFailure, touchableStores, componentStores, mountStores }] = useState(\n () => {\n const ctxId = manualContextId || id;\n const groupedStores = storeManager.createStores(\n Object.entries(stores),\n parentId,\n ctxId,\n suspenseId,\n componentName,\n props,\n );\n const { globalStores, relativeStores, parentStores, hasCreationFailure } = groupedStores;\n const tStores = { ...relativeStores, ...globalStores };\n\n return {\n contextId: ctxId,\n hasFailure: hasCreationFailure,\n touchableStores: tStores,\n componentStores: { ...tStores, ...parentStores },\n mountStores: () => storeManager.mountStores(ctxId, groupedStores),\n };\n },\n );\n\n useEffect(mountStores, [mountStores]);\n\n return (\n <StoreManagerParentProvider parentId={contextId} touchableStores={touchableStores}>\n {!hasFailure && <ObservableComponent {...props} {...componentStores} />}\n </StoreManagerParentProvider>\n );\n };\n\n hoistNonReactStatics(Element, Component);\n Element.displayName = `Mobx(${componentName})`;\n\n return Object.defineProperty(Element, 'name', {\n value: Element.displayName,\n writable: false,\n enumerable: false,\n });\n};\n\nexport default withStores;\n"],"names":["withStores","Component","stores","customContextId","ObservableComponent","observer","manualContextId","componentName","displayName","name","Element","props","storeManager","useStoreManager","parentId","useStoreManagerParent","suspenseId","useConsistentSuspense","id","useId","contextId","hasFailure","touchableStores","componentStores","mountStores","useState","ctxId","groupedStores","createStores","Object","entries","globalStores","relativeStores","parentStores","hasCreationFailure","tStores","useEffect","React","createElement","StoreManagerParentProvider","hoistNonReactStatics","defineProperty","value","writable","enumerable"],"mappings":"8TAWA,MAAMA,EAAa,CACjBC,EACAC,GACEC,mBAAuC,CAAA,KAEzC,MAAMC,EAAsBC,EAASJ,GAC/BK,EAAkBH,GAAoBF,EAA6B,kBACnEM,EAAgBN,EAAUO,aAAeP,EAAUQ,KAEnDC,EAAkCC,IACtC,MAAMC,EAAeC,IACfC,EAAWC,KACXC,WAAEA,GAAeC,IACjBC,EAAKC,MACJC,UAAEA,EAASC,WAAEA,EAAUC,gBAAEA,EAAeC,gBAAEA,EAAeC,YAAEA,IAAiBC,GACjF,KACE,MAAMC,EAAQpB,GAAmBY,EAC3BS,EAAgBf,EAAagB,aACjCC,OAAOC,QAAQ5B,GACfY,EACAY,EACAV,EACAT,EACAI,IAEIoB,aAAEA,EAAYC,eAAEA,EAAcC,aAAEA,EAAYC,mBAAEA,GAAuBP,EACrEQ,EAAU,IAAKH,KAAmBD,GAExC,MAAO,CACLX,UAAWM,EACXL,WAAYa,EACZZ,gBAAiBa,EACjBZ,gBAAiB,IAAKY,KAAYF,GAClCT,YAAa,IAAMZ,EAAaY,YAAYE,EAAOC,GACpD,IAML,OAFAS,EAAUZ,EAAa,CAACA,IAGtBa,EAACC,cAAAC,EAA2B,CAAAzB,SAAUM,EAAWE,gBAAiBA,IAC9DD,GAAcgB,EAACC,cAAAlC,EAAwB,IAAAO,KAAWY,IAEtD,EAMJ,OAHAiB,EAAqB9B,EAAST,GAC9BS,EAAQF,YAAc,QAAQD,KAEvBsB,OAAOY,eAAe/B,EAAS,OAAQ,CAC5CgC,MAAOhC,EAAQF,YACfmC,UAAU,EACVC,YAAY,GACZ"}
|