@lomray/react-mobx-manager 1.3.0 → 1.3.1-beta.2

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.
@@ -0,0 +1,128 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ Github issues.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.0, available at
119
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
+
121
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
+ enforcement ladder](https://github.com/mozilla/diversity).
123
+
124
+ [homepage]: https://www.contributor-covenant.org
125
+
126
+ For answers to common questions about this code of conduct, see the FAQ at
127
+ https://www.contributor-covenant.org/faq. Translations are available at
128
+ https://www.contributor-covenant.org/translations.
@@ -0,0 +1,88 @@
1
+ # Contributing
2
+
3
+ When contributing to this repository, please first discuss the change you wish to make via issue,
4
+ email, or any other method with the owners of this repository before making a change.
5
+
6
+ Please note we have a code of conduct, please follow it in all your interactions with the project.
7
+
8
+ ## Pull Request Process
9
+
10
+ 1. Ensure any unused install dependencies are removed before create PR.
11
+ 2. Update the README.md with details of changes to the interface.
12
+ 3. You may merge the Pull Request in once you have the sign-off of two other developers, or if you
13
+ do not have permission to do that, you may request the second reviewer to merge it for you.
14
+
15
+ ## Code of Conduct
16
+
17
+ ### Our Pledge
18
+
19
+ In the interest of fostering an open and welcoming environment, we as
20
+ contributors and maintainers pledge to making participation in our project and
21
+ our community a harassment-free experience for everyone, regardless of age, body
22
+ size, disability, ethnicity, gender identity and expression, level of experience,
23
+ nationality, personal appearance, race, religion, or sexual identity and
24
+ orientation.
25
+
26
+ ### Our Standards
27
+
28
+ Examples of behavior that contributes to creating a positive environment
29
+ include:
30
+
31
+ * Using welcoming and inclusive language
32
+ * Being respectful of differing viewpoints and experiences
33
+ * Gracefully accepting constructive criticism
34
+ * Focusing on what is best for the community
35
+ * Showing empathy towards other community members
36
+
37
+ Examples of unacceptable behavior by participants include:
38
+
39
+ * The use of sexualized language or imagery and unwelcome sexual attention or
40
+ advances
41
+ * Trolling, insulting/derogatory comments, and personal or political attacks
42
+ * Public or private harassment
43
+ * Publishing others' private information, such as a physical or electronic
44
+ address, without explicit permission
45
+ * Other conduct which could reasonably be considered inappropriate in a
46
+ professional setting
47
+
48
+ ### Our Responsibilities
49
+
50
+ Project maintainers are responsible for clarifying the standards of acceptable
51
+ behavior and are expected to take appropriate and fair corrective action in
52
+ response to any instances of unacceptable behavior.
53
+
54
+ Project maintainers have the right and responsibility to remove, edit, or
55
+ reject comments, commits, code, wiki edits, issues, and other contributions
56
+ that are not aligned to this Code of Conduct, or to ban temporarily or
57
+ permanently any contributor for other behaviors that they deem inappropriate,
58
+ threatening, offensive, or harmful.
59
+
60
+ ### Scope
61
+
62
+ This Code of Conduct applies both within project spaces and in public spaces
63
+ when an individual is representing the project or its community. Examples of
64
+ representing a project or community include using an official project e-mail
65
+ address, posting via an official social media account, or acting as an appointed
66
+ representative at an online or offline event. Representation of a project may be
67
+ further defined and clarified by project maintainers.
68
+
69
+ ### Enforcement
70
+
71
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
72
+ reported by contacting the project team at [INSERT EMAIL ADDRESS]. All
73
+ complaints will be reviewed and investigated and will result in a response that
74
+ is deemed necessary and appropriate to the circumstances. The project team is
75
+ obligated to maintain confidentiality with regard to the reporter of an incident.
76
+ Further details of specific enforcement policies may be posted separately.
77
+
78
+ Project maintainers who do not follow or enforce the Code of Conduct in good
79
+ faith may face temporary or permanent repercussions as determined by other
80
+ members of the project's leadership.
81
+
82
+ ### Attribution
83
+
84
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
85
+ available at [http://contributor-covenant.org/version/1/4][version]
86
+
87
+ [homepage]: http://contributor-covenant.org
88
+ [version]: http://contributor-covenant.org/version/1/4/
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Lomray Software
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -2,21 +2,46 @@
2
2
  <img src="https://user-images.githubusercontent.com/95251720/180519123-eb8a36e7-e7af-41f2-9a01-ae6d6b6a94f3.svg" alt="Bootstrap logo" width="200" height="165">
3
3
  </p>
4
4
 
5
- <h3 align='center'>Mobx stores manager for React</h3>
5
+ <h1 align='center'>Mobx stores manager for React</h1>
6
6
 
7
- [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=Lomray-Software_react-mobx-manager)
8
- [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=Lomray-Software_react-mobx-manager)
9
- [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=Lomray-Software_react-mobx-manager)
10
- [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=vulnerabilities)](https://sonarcloud.io/summary/new_code?id=Lomray-Software_react-mobx-manager)
11
- [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=bugs)](https://sonarcloud.io/summary/new_code?id=Lomray-Software_react-mobx-manager)
12
- [![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=ncloc)](https://sonarcloud.io/summary/new_code?id=Lomray-Software_react-mobx-manager)
7
+ - One way to escape state tree 🌲🌳🌴.
8
+ - Manage your Mobx stores like a boss - debug like a hacker.
9
+ - Simple idea - simple implementation.
10
+ - Small package size.
11
+ - Support code splitting out of the box.
12
+ - Access stores from other stores.
13
+ - Can be a replacement for react context.
14
+ - And many other nice things 😎
15
+
16
+ <p align="center">
17
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=reliability_rating" alt="reliability">
18
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=security_rating" alt="Security Rating">
19
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=sqale_rating" alt="Maintainability Rating">
20
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=vulnerabilities" alt="Vulnerabilities">
21
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=bugs" alt="Bugs">
22
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=Lomray-Software_react-mobx-manager&metric=ncloc" alt="Lines of Code">
23
+ <img src="https://img.shields.io/bundlephobia/minzip/@lomray/react-mobx-manager" alt="size">
24
+ <img src="https://img.shields.io/npm/l/@lomray/react-mobx-manager" alt="size">
25
+ <img src="https://img.shields.io/npm/v/@lomray/react-mobx-manager?label=semantic%20release&logo=semantic-release" alt="semantic version">
26
+ <img src="https://app.fossa.com/api/projects/git%2Bgithub.com%2FLomray-Software%2Freact-mobx-manager.svg?type=small" alt="FOSSA Status">
27
+ </p>
13
28
 
14
29
  ## Table of contents
15
30
 
16
31
  - [Getting started](#getting-started)
32
+ - [Usage](#usage)
33
+ - [Support SSR](#support-ssr)
34
+ - [Important Tips](#important-tips)
35
+ - [Documentation](#documentation)
36
+ - [Manager](#manager)
37
+ - [withStores](#withstores)
38
+ - [StoreManagerProvider](#storemanagerprovider)
39
+ - [useStoreManagerContext](#usestoremanagercontext)
40
+ - [useStoreManagerParentContext](#usestoremanagerparentcontext)
41
+ - [Store](#store)
42
+ - [React Native Debug Plugin](#react-native-debug-plugin)
17
43
  - [Bugs and feature requests](#bugs-and-feature-requests)
18
- - [Copyright](#copyright)
19
-
44
+ - [License](#license)
20
45
 
21
46
  ## Getting started
22
47
 
@@ -26,15 +51,15 @@ The React-mobx-manager package is distributed using [npm](https://www.npmjs.com/
26
51
  npm i --save @lomray/react-mobx-manager
27
52
  ```
28
53
 
29
- _Optional:_ Configure your bundler for keep classnames and function names in production OR use `id` for each store:
30
-
31
- **React:** (craco or webpack config, terser options)
54
+ **Optional:** Configure your bundler to keep classnames and function names in production OR use `id` for each store:
55
+
56
+ - **React:** (craco or webpack config, terser options)
32
57
  ```bash
33
58
  terserOptions.keep_classnames = true;
34
59
  terserOptions.keep_fnames = true;
35
60
  ```
36
61
 
37
- **React Native:** (metro bundler config)
62
+ - **React Native:** (metro bundler config)
38
63
  ```
39
64
  transformer: {
40
65
  minifierConfig: {
@@ -44,16 +69,23 @@ transformer: {
44
69
  }
45
70
  ```
46
71
 
47
- Import `Manager, StoreManagerProvider` from `@lomray/react-mobx-manager` into your index file after wrap `<App/>` with `<StoreManagerProvider/>`
72
+ ## Usage
48
73
 
49
- ```jsx
74
+ Import `Manager, StoreManagerProvider` from `@lomray/react-mobx-manager` into your index file and wrap `<App/>` with `<StoreManagerProvider/>`
75
+
76
+ ```typescript jsx
50
77
  import React from 'react';
51
78
  import ReactDOM from 'react-dom/client';
52
79
  import './index.css';
53
- import { Manager, StoreManagerProvider } from '@lomray/react-mobx-manager';
80
+ import { Manager, StoreManagerProvider, MobxLocalStorage } from '@lomray/react-mobx-manager';
54
81
  import App from './app';
82
+ import MyApiClient from './services/my-api-client';
55
83
 
56
- const storeManager = new Manager();
84
+ const apiClient = new MyApiClient();
85
+ const storeManager = new Manager({
86
+ storage: new MobxLocalStorage(), // optional: needs for persisting stores
87
+ storesParams: { apiClient }, // optional: we can provide our api client for access from the store
88
+ });
57
89
 
58
90
  const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
59
91
 
@@ -66,25 +98,77 @@ root.render(
66
98
  );
67
99
  ```
68
100
 
69
- Connect mobx store to manager, and you're good to go!
101
+ Connect mobx store to the manager, and you're good to go!
70
102
 
71
103
  ```typescript
72
- import { withStores } from '@lomray/react-mobx-manager';
73
- import { makeAutoObservable } from 'mobx';
104
+ import { withStores, Manager } from '@lomray/react-mobx-manager';
105
+ import { makeObservable, observable, action } from 'mobx';
106
+ import type { IConstructorParams, ClassReturnType } from '@lomray/react-mobx-manager';
74
107
 
75
108
  /**
76
109
  * Mobx user store
110
+ *
111
+ * Usually store like that are related to the global store,
112
+ * because they store information about the current user,
113
+ * which may be needed in different places of the application.
114
+ *
115
+ * You may also want to save the state of the store, for example,
116
+ * to local storage, so that it can be restored after page reload,
117
+ * in this case, just export wrap export with 'persist':
118
+ * export default Manager.persistStore(UserStore, 'user');
77
119
  */
78
120
  class UserStore {
79
121
  /**
80
- * Required only if we don't configure our bundler for keep classnames and function names
122
+ * Required only if we don't configure our bundler to keep classnames and function names
123
+ * Default: current class name
81
124
  */
82
125
  static id = 'user';
83
-
84
- name = 'Matthew'
85
126
 
86
- constructor() {
87
- makeAutoObservable()
127
+ /**
128
+ * You can also enable 'singleton' behavior for global application stores
129
+ * Default: false
130
+ */
131
+ static isSingleton = true;
132
+
133
+ /**
134
+ * Our state
135
+ */
136
+ public name = 'Matthew'
137
+
138
+ /**
139
+ * Our API client
140
+ */
141
+ private apiClient: MyApiClient;
142
+
143
+ /**
144
+ * @constructor
145
+ */
146
+ constructor({ getStore, apiClient }: IConstructorParams) {
147
+ this.apiClient = apiClient;
148
+ // if we need, we can get a global store or store from the parent context
149
+ // this.otherStore = getStore(SomeOtherStore);
150
+
151
+ makeObservable(this, {
152
+ name: observable,
153
+ setName: action.bound,
154
+ });
155
+ }
156
+
157
+ /**
158
+ * Set user name
159
+ */
160
+ public setName(name: string): void {
161
+ this.name = name;
162
+ }
163
+
164
+ /**
165
+ * Example async
166
+ * Call this func from component
167
+ */
168
+ public getNameFromApi = async (userId: number) => {
169
+ const name = await this.apiClient.fetchName(userId);
170
+
171
+ this.setName(name);
88
172
  }
89
173
  }
90
174
 
@@ -113,12 +197,285 @@ const User: FC<TProps> = ({ userStore: { name } }) => {
113
197
  export default withStores(User, stores);
114
198
  ```
115
199
 
116
- [See example app](example) for more understanding.
200
+ [See app example](example) for a better understanding.
201
+
202
+ ## Support SSR
203
+ Does this library support SSR? Short answer - yes, but we need some steps to prepare our framework.
204
+ - Look at [After.js (razzle) based project](https://github.com/Lomray-Software/microservices-dashboard/blob/staging/src/pages/user/index.tsx#L82) for a better understanding.
205
+ - Look at [NextJS example](https://github.com/Lomray-Software/nextjs-mobx-store-manager-example) for a better understanding (needs writing a wrapper).
206
+
207
+ ## Important Tips
208
+ - Create **singleton** store only for global stores e.g, for application settings, logged user, etc.
209
+ - To get started, stick to the concept: Store for Component. Don't connect (through withStores) not singleton store to several components.
210
+
211
+ ## Documentation
212
+
213
+ ### Manager
214
+ ```typescript
215
+ import { Manager, MobxLocalStorage, MobxAsyncStorage } from '@lomray/react-mobx-manager';
216
+ // import AsyncStorage from '@react-native-async-storage/async-storage';
217
+
218
+ // Params
219
+ const storeManager = new Manager({
220
+ /**
221
+ * Optional: needs for persisting stores when you use Manager.persistStore
222
+ * Available: MobxLocalStorage and MobxAsyncStorage
223
+ * Default: none
224
+ */
225
+ storage: new MobxLocalStorage(), // React
226
+ // storage: new MobxAsyncStorage(AsyncStorage), // React Native
227
+ /**
228
+ * Optional: provide some params for access from store constructor
229
+ * E.g. we can provide our api client for access from the store
230
+ * Default: {}
231
+ */
232
+ storesParams: { apiClient },
233
+ /**
234
+ * Initial stores state.
235
+ * E.g. in SSR case, restore client state from a server
236
+ * Default: {}
237
+ */
238
+ initState: { storeId: { param: 'test' } },
239
+ /**
240
+ * Additional manager options
241
+ */
242
+ options: {
243
+ /**
244
+ * Disable persisting stores
245
+ * E.g., it should be 'true' on a server-side (SSR)
246
+ * Default: false
247
+ */
248
+ shouldDisablePersist: false,
249
+ /**
250
+ * Remove the initial store state after initialization
251
+ * Default: true
252
+ */
253
+ shouldRemoveInitState: true,
254
+ /**
255
+ * Enable this option if your application support server-side rendering (on both side, client and server)
256
+ * Default: false
257
+ */
258
+ isSSR: false,
259
+ }
260
+ });
261
+
262
+ // Methods
263
+
264
+ /**
265
+ * Optional: Call this method to load persisting data from persist storage
266
+ * E.g., you may want manually to do this before the app render
267
+ * Default: StoreManagerProvider does this automatically with 'shoudInit' prop
268
+ */
269
+ await storeManager.init();
270
+
271
+ /**
272
+ * Get all-created stores
273
+ */
274
+ const managerStores = storeManager.getStores();
275
+
276
+ /**
277
+ * Get specific store
278
+ */
279
+ const store = storeManager.getStore(SomeSingletonStore);
280
+ const store2 = storeManager.getStore(SomeStore, { contextId: 'necessary-context-id' });
281
+
282
+ /**
283
+ * Get stores context's and relations
284
+ */
285
+ const relations = storeManager.getStoresRelations();
286
+
287
+ /**
288
+ * Generate unique context id
289
+ */
290
+ const contextId = storeManager.createContextId();
291
+
292
+ /**
293
+ * Manually create stores for component
294
+ * NOTE: 'withStores' wrapper use this method, probably you won't need it
295
+ */
296
+ const stores = storeManager.createStores(['someStore', MyStore], 'parent-id', 'context-id', 'HomePage');
297
+
298
+ /**
299
+ * Mount/Unmount simple stores to component
300
+ */
301
+ const unmount = storeManager.mountStores(stores);
302
+
303
+ /**
304
+ * Get all-stores state
305
+ */
306
+ const storesState = storeManager.toJSON();
307
+
308
+ /**
309
+ * Get all persisted store's state
310
+ */
311
+ const persistedStoresState = storeManager.toPersistedJSON();
312
+
313
+ /**
314
+ * Get only persisted stores id's
315
+ */
316
+ const persistedIds = Manager.getPersistedStoresIds();
317
+
318
+ /**
319
+ * Get store observable props
320
+ */
321
+ const observableProps = Manager.getObservableProps(store);
322
+
323
+ /**
324
+ * Static method for access to manager from anywhere
325
+ * NOTE: Be careful with this, especially with SSR on server-side
326
+ */
327
+ const manager = Manager.get();
328
+
329
+ /**
330
+ * Enable persisting state for store
331
+ */
332
+ const storeClass = Manager.persistStore(class MyStore {}, 'my-store');
333
+ ```
334
+
335
+ ### withStores
336
+ ```typescript
337
+ import { withStores } from '@lomray/react-mobx-manager';
338
+
339
+ /**
340
+ * Create and connect 'stores' to component
341
+ * NOTE: In most cases, you don't need to pass a third argument (contextId).
342
+ */
343
+ withStores(Component, stores, 'optional-context-id');
344
+
345
+ const stores = { myStore: MyStore, anotherStore: AnotherStore };
346
+ ```
347
+
348
+ ### StoreManagerProvider
349
+ ```typescript jsx
350
+ import { StoreManagerProvider } from '@lomray/react-mobx-manager';
351
+
352
+ /**
353
+ * Wrap your application for a pass-down store manager, context id, and init persisted state
354
+ *
355
+ * shouldInit - default: false, enable initialize peristed state
356
+ * fallback - show loader while the manager has initialized
357
+ */
358
+ <StoreManagerProvider storeManager={storeManager} shouldInit fallback={<Loader />}>
359
+ {/* your components */}
360
+ </StoreManagerProvider>
361
+ ```
362
+
363
+ ### useStoreManagerContext
364
+ ```typescript jsx
365
+ import { useStoreManagerContext } from '@lomray/react-mobx-manager';
366
+
367
+ const MyComponent: FC = () => {
368
+ /**
369
+ * Get store manager inside your function component
370
+ */
371
+ const storeManager = useStoreManagerContext();
372
+ }
373
+ ```
374
+
375
+ ### useStoreManagerParentContext
376
+ ```typescript jsx
377
+ import { useStoreManagerParentContext } from '@lomray/react-mobx-manager';
378
+
379
+ const MyComponent: FC = () => {
380
+ /**
381
+ * Get parent context id
382
+ */
383
+ const { parentId } = useStoreManagerParentContext();
384
+ }
385
+ ```
386
+
387
+ ### Store
388
+
389
+ ```typescript
390
+ import { makeObservable, observable, action } from 'mobx';
391
+
392
+ class MyStore {
393
+ /**
394
+ * Required only if we don't configure our bundler to keep classnames and function names
395
+ * Default: current class name
396
+ */
397
+ static id = 'user';
398
+
399
+ /**
400
+ * You can also enable 'singleton' behavior for global application stores
401
+ * Default: false
402
+ */
403
+ static isSingleton = true;
404
+
405
+ /**
406
+ * Store observable state
407
+ */
408
+ public state = {
409
+ name: 'Matthew',
410
+ username: 'meow',
411
+ }
412
+
413
+ /**
414
+ * @private
415
+ */
416
+ private someParentStore: ClassReturnType<typeof SomeParentStore>;
417
+
418
+ /**
419
+ * @constructor
420
+ *
421
+ * getStore - get parent store or singleton store
422
+ * storeManager - access to store manager
423
+ * apiClient - your custom param, see 'storesParams' in Manager
424
+ */
425
+ constructor({ getStore, storeManager, apiClient }: IConstructorParams) {
426
+ this.apiClient = apiClient;
427
+ this.someParentStore = getStore(SomeParentStore);
428
+
429
+ makeObservable(this, {
430
+ state: observable,
431
+ });
432
+ }
433
+
434
+ /**
435
+ * Define this method if you want to do something after initialize the store
436
+ * State restored, store ready for usage
437
+ * Optional.
438
+ * @private
439
+ */
440
+ private init(): void {
441
+ // do something
442
+ }
443
+
444
+ /**
445
+ * Define this method if you want to do something when a component with this store is mount
446
+ * @private
447
+ */
448
+ private onMount(): void {
449
+ // do something
450
+ }
451
+
452
+ /**
453
+ * Define this method if you want to do something when a component with this store is unmount
454
+ * @private
455
+ */
456
+ private onDestroy(): void {
457
+ // do something
458
+ }
459
+
460
+ /**
461
+ * Custom method for return store state
462
+ * Optional.
463
+ * Default: @see Manager.toJSON
464
+ */
465
+ public toJSON(): Record<string, any> {
466
+ return { state: { username: this.state.username } };
467
+ }
468
+ }
469
+ ```
470
+
471
+ ## React Native debug plugin
472
+ For debug state, you can use [Reactotron debug plugin](https://github.com/Lomray-Software/reactotron-mobx-store-manager)
117
473
 
118
474
  ## Bugs and feature requests
119
475
 
120
476
  Bug or a feature request, [please open a new issue](https://github.com/Lomray-Software/react-mobx-manager/issues/new).
121
477
 
122
- ## Copyright
478
+ ## License
479
+ Made with 💚
123
480
 
124
- Code and documentation copyright 2022 the [Lomray Software](https://lomray.com/).
481
+ Published under [MIT License](./LICENSE).
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export * from "./types-e1cf38b5";
1
+ export * from "./types-4e5aab57";
2
2
  export * from "./context";
3
3
  export { default as Manager } from "./manager";
4
4
  export { default as onChangeListener } from "./on-change-listener";
package/lib/manager.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { IConstructableStore, IManagerParams, IStorage, IStore, TStoreDefinition, IManagerOptions, TStores, IStoreLifecycle, TInitStore, IStoreParams } from "./types-e1cf38b5";
1
+ import { IConstructableStore, IManagerParams, IStorage, IStore, TStoreDefinition, IManagerOptions, TStores, IStoreLifecycle, TInitStore, IStoreParams } from "./types-4e5aab57";
2
2
  /**
3
3
  * Mobx stores manager
4
4
  */
package/lib/manager.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("mobx"),t=require("./on-change-listener.js"),s=require("./wakeup.js");class r{constructor({initState:e,storesParams:t,storage:s,options:o}={}){Object.defineProperty(this,"stores",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"storesRelations",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"initState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"storage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"persistData",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"storesParams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:{shouldDisablePersist:!1,shouldRemoveInitState:!0,isSSR:!1}}),this.initState=e||{},this.storesParams=t||{},this.storage=s,Object.assign(this.options,o||{}),r.instance=this}async init(){return this.storage&&(this.persistData=await this.storage.get()||{}),this}static get(){if(!r.instance)throw new Error("Store manager is not initialized.");return r.instance}getStores(){return this.stores}getStoresRelations(){return this.storesRelations}static getPersistedStoresIds(){return r.persistedStores}getStoreId(e,t={}){const{id:s,contextId:r,key:o}=t;if(s)return s;if(e.id)return e.id;let i=e.name||e.constructor.name;return e.isSingleton?i:(i=`${i}--${r}`,o?`${i}--${o}`:i)}createContextId(e){return`ctx${e||this.storesRelations.size+1}`}getStore(e,t={}){const s=this.getStoreId(e,t);return this.stores.has(s)?this.stores.get(s):e.isSingleton?this.createStore(e,{id:s,contextId:"singleton",parentId:"root",componentName:""}):this.lookupStore(s,t)}lookupStore(e,t){var s,r;const{contextId:o,parentId:i}=t,n=null===(s=e.split("--"))||void 0===s?void 0:s[0],{ids:a,parentId:l}=null!==(r=this.storesRelations.get(o))&&void 0!==r?r:{ids:new Set,parentId:i},d=[...a].filter((e=>e.startsWith(`${n}--`)));if(1===d.length)return this.stores.get(d[0]);if(d.length>1)console.error("Parent context has multiple stores with the same id, please pass key to getStore function.");else if(l&&"root"!==l)return this.lookupStore(e,{contextId:l})}createStore(e,t){var s,o;const{isSSR:i}=this.options,{id:n,contextId:a,parentId:l,componentName:d}=t;if((e.isSingleton||i)&&this.stores.has(n))return this.stores.get(n);const c=new e({storeManager:this,getStore:(e,t={contextId:a,parentId:l})=>this.getStore(e,t),...this.storesParams});c.id=n,c.isSingleton=e.isSingleton,c.contextId=e.isSingleton?"singleton":a,c.parentId=e.isSingleton||!l||l===a?"root":l,c.componentName=d;const u=this.initState[n],h=this.persistData[n];return u&&Object.assign(c,u),"wakeup"in c&&r.persistedStores.has(n)&&(null===(s=c.wakeup)||void 0===s||s.call(c,c,{initState:u,persistedState:h})),null===(o=c.init)||void 0===o||o.call(c),(c.isSingleton||i)&&this.prepareStore(c),c}createStores(e,t,s,r){return e.reduce(((e,[o,i])=>{const[n,a]="store"in i?[i.store,i.id]:[i,this.getStoreId(i,{key:o,contextId:s})];return{...e,[o]:this.createStore(n,{id:a,contextId:s,parentId:t,componentName:r})}}),{})}prepareStore(e){const{shouldRemoveInitState:t}=this.options,s=e.id,o=e.contextId,i=[];this.storesRelations.has(o)||this.storesRelations.set(o,{ids:new Set,parentId:e.parentId&&e.parentId!==o?e.parentId:"root",componentName:e.componentName});const{ids:n}=this.storesRelations.get(o);return r.persistedStores.has(s)&&"addOnChangeListener"in e&&i.push(e.addOnChangeListener(e,this)),t&&this.initState[s]&&delete this.initState[s],this.stores.has(s)||(this.stores.set(s,e),n.add(s)),i}mountStores(e){const t=[];return Object.values(e).forEach((e=>{var s;if(t.push(...this.prepareStore(e)),"onMount"in e){const r=null===(s=e.onMount)||void 0===s?void 0:s.call(e);"function"==typeof r&&t.push(r)}"onDestroy"in e&&t.push((()=>{var t;return null===(t=e.onDestroy)||void 0===t?void 0:t.call(e)}))})),()=>{t.forEach((e=>e())),Object.values(e).forEach((e=>{var t;const s=e.id;if(!e.isSingleton){const{ids:r}=null!==(t=this.storesRelations.get(e.contextId))&&void 0!==t?t:{ids:new Set};this.stores.delete(s),r.delete(s),r.size||this.storesRelations.delete(e.contextId)}}))}}toJSON(){var e,t;const s={};for(const[o,i]of this.stores.entries())s[o]=null!==(t=null===(e=i.toJSON)||void 0===e?void 0:e.call(i))&&void 0!==t?t:r.getObservableProps(i);return s}toPersistedJSON(){var e,t;const s={};for(const o of r.persistedStores){const i=this.stores.get(o);i&&(s[o]=null!==(t=null===(e=i.toJSON)||void 0===e?void 0:e.call(i))&&void 0!==t?t:r.getObservableProps(i))}return s}static getObservableProps(t){const s=e.toJS(t);return Object.entries(s).reduce(((s,[r,o])=>({...s,...e.isObservableProp(t,r)?{[r]:o}:{}})),{})}static persistStore(e,o){return r.persistedStores.has(o)?(console.error(`Duplicate serializable store key: ${o}`),e):(r.persistedStores.add(o),e.id=o,"wakeup"in e.prototype||(e.prototype.wakeup=s),"addOnChangeListener"in e.prototype||(e.prototype.addOnChangeListener=t),e)}}Object.defineProperty(r,"persistedStores",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),module.exports=r;
1
+ "use strict";var e=require("mobx"),t=require("./on-change-listener.js"),s=require("./wakeup.js");class r{constructor({initState:e,storesParams:t,storage:s,options:o}={}){Object.defineProperty(this,"stores",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"storesRelations",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"initState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"storage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"persistData",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"storesParams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:{shouldDisablePersist:!1,shouldRemoveInitState:!0,isSSR:!1}}),this.initState=e||{},this.storesParams=t||{},this.storage=s,Object.assign(this.options,o||{}),r.instance=this}async init(){return this.storage&&(this.persistData=await this.storage.get()||{}),this}static get(){if(!r.instance)throw new Error("Store manager is not initialized.");return r.instance}getStores(){return this.stores}getStoresRelations(){return this.storesRelations}static getPersistedStoresIds(){return r.persistedStores}getStoreId(e,t={}){const{id:s,contextId:r,key:o}=t;if(s)return s;if(e.libStoreId)return e.libStoreId;let i=e.name||e.constructor.name;return e.isSingleton?i:(i=`${i}--${r}`,o?`${i}--${o}`:i)}createContextId(e){return`ctx${e||this.storesRelations.size+1}`}getStore(e,t={}){const s=this.getStoreId(e,t);return this.stores.has(s)?this.stores.get(s):e.isSingleton?this.createStore(e,{id:s,contextId:"singleton",parentId:"root",componentName:""}):this.lookupStore(s,t)}lookupStore(e,t){var s,r;const{contextId:o,parentId:i}=t,n=null===(s=e.split("--"))||void 0===s?void 0:s[0],{ids:a,parentId:l}=null!==(r=this.storesRelations.get(o))&&void 0!==r?r:{ids:new Set,parentId:i},d=[...a].filter((e=>e.startsWith(`${n}--`)));if(1===d.length)return this.stores.get(d[0]);if(d.length>1)console.error("Parent context has multiple stores with the same id, please pass key to getStore function.");else if(l&&"root"!==l)return this.lookupStore(e,{contextId:l})}createStore(e,t){var s,o;const{isSSR:i}=this.options,{id:n,contextId:a,parentId:l,componentName:d}=t;if((e.isSingleton||i)&&this.stores.has(n))return this.stores.get(n);const u=new e({storeManager:this,getStore:(e,t={contextId:a,parentId:l})=>this.getStore(e,t),...this.storesParams});u.libStoreId=n,u.isSingleton=e.isSingleton,u.libStoreContextId=e.isSingleton?"singleton":a,u.libStoreParentId=e.isSingleton||!l||l===a?"root":l,u.libStoreComponentName=d;const c=this.initState[n],h=this.persistData[n];return c&&Object.assign(u,c),"wakeup"in u&&r.persistedStores.has(n)&&(null===(s=u.wakeup)||void 0===s||s.call(u,u,{initState:c,persistedState:h})),null===(o=u.init)||void 0===o||o.call(u),(u.isSingleton||i)&&this.prepareStore(u),u}createStores(e,t,s,r){return e.reduce(((e,[o,i])=>{const[n,a]="store"in i?[i.store,i.id]:[i,this.getStoreId(i,{key:o,contextId:s})];return{...e,[o]:this.createStore(n,{id:a,contextId:s,parentId:t,componentName:r})}}),{})}prepareStore(e){const{shouldRemoveInitState:t}=this.options,s=e.libStoreId,o=e.libStoreContextId,i=[];this.storesRelations.has(o)||this.storesRelations.set(o,{ids:new Set,parentId:e.libStoreParentId&&e.libStoreParentId!==o?e.libStoreParentId:"root",componentName:e.libStoreComponentName});const{ids:n}=this.storesRelations.get(o);return r.persistedStores.has(s)&&"addOnChangeListener"in e&&i.push(e.addOnChangeListener(e,this)),t&&this.initState[s]&&delete this.initState[s],this.stores.has(s)||(this.stores.set(s,e),n.add(s)),i}mountStores(e){const t=[];return Object.values(e).forEach((e=>{var s;if(t.push(...this.prepareStore(e)),"onMount"in e){const r=null===(s=e.onMount)||void 0===s?void 0:s.call(e);"function"==typeof r&&t.push(r)}"onDestroy"in e&&t.push((()=>{var t;return null===(t=e.onDestroy)||void 0===t?void 0:t.call(e)}))})),()=>{t.forEach((e=>e())),Object.values(e).forEach((e=>{var t;const s=e.libStoreId;if(!e.isSingleton){const{ids:r}=null!==(t=this.storesRelations.get(e.libStoreContextId))&&void 0!==t?t:{ids:new Set};this.stores.delete(s),r.delete(s),r.size||this.storesRelations.delete(e.libStoreContextId)}}))}}toJSON(){var e,t;const s={};for(const[o,i]of this.stores.entries())s[o]=null!==(t=null===(e=i.toJSON)||void 0===e?void 0:e.call(i))&&void 0!==t?t:r.getObservableProps(i);return s}toPersistedJSON(){var e,t;const s={};for(const o of r.persistedStores){const i=this.stores.get(o);i&&(s[o]=null!==(t=null===(e=i.toJSON)||void 0===e?void 0:e.call(i))&&void 0!==t?t:r.getObservableProps(i))}return s}static getObservableProps(t){const s=e.toJS(t);return Object.entries(s).reduce(((s,[r,o])=>({...s,...e.isObservableProp(t,r)?{[r]:o}:{}})),{})}static persistStore(e,o){return r.persistedStores.has(o)?(console.error(`Duplicate serializable store key: ${o}`),e):(r.persistedStores.add(o),e.libStoreId=o,"wakeup"in e.prototype||(e.prototype.wakeup=s),"addOnChangeListener"in e.prototype||(e.prototype.addOnChangeListener=t),e)}}Object.defineProperty(r,"persistedStores",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),module.exports=r;
@@ -1,4 +1,4 @@
1
- import { IStorePersisted } from "./types-e1cf38b5";
1
+ import { IStorePersisted } from "./types-4e5aab57";
2
2
  /**
3
3
  * Listen persist store changes
4
4
  */
@@ -1,9 +1,12 @@
1
- import { IStorage } from "../types-e1cf38b5";
1
+ import { IStorage } from "../types-4e5aab57";
2
2
  interface IAsyncStorage {
3
3
  getItem: (key: string) => Promise<string | null>;
4
4
  setItem: (key: string, value: string) => Promise<void>;
5
5
  removeItem: (key: string) => Promise<void>;
6
6
  }
7
+ /**
8
+ * Async storage for mobx store manager
9
+ */
7
10
  declare class AsyncStorage implements IStorage {
8
11
  globalKey: string;
9
12
  /**
@@ -1,4 +1,7 @@
1
- import { IStorage } from "../types-e1cf38b5";
1
+ import { IStorage } from "../types-4e5aab57";
2
+ /**
3
+ * Local storage for mobx store manager
4
+ */
2
5
  declare class LocalStorage implements IStorage {
3
6
  globalKey: string;
4
7
  /**
@@ -8,10 +8,10 @@ interface IStoreLifecycle {
8
8
  onMount?: () => void | (() => void);
9
9
  }
10
10
  interface IStore extends IStoreLifecycle {
11
- id?: string;
12
- contextId?: string;
13
- parentId?: string;
14
- componentName?: string;
11
+ libStoreId?: string;
12
+ libStoreContextId?: string;
13
+ libStoreParentId?: string;
14
+ libStoreComponentName?: string;
15
15
  isSingleton?: boolean;
16
16
  init?: () => void;
17
17
  toJSON?: () => Record<string, any>;
package/lib/wakeup.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { IStorePersisted } from "./types-e1cf38b5";
1
+ import { IStorePersisted } from "./types-4e5aab57";
2
2
  /**
3
3
  * Restore store state from initial state
4
4
  */
@@ -1,5 +1,5 @@
1
1
  import { FC } from 'react';
2
- import { TMapStores } from "./types-e1cf38b5";
2
+ import { TMapStores } from "./types-4e5aab57";
3
3
  /**
4
4
  * Make component observable and pass stores as props
5
5
  */
@@ -1 +1 @@
1
- "use strict";var e=require("hoist-non-react-statics"),t=require("mobx-react-lite"),r=require("react"),a=require("./context.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(e),u=n(r);module.exports=(e,n,s)=>{const c=t.observer(e),d=s||e.contextId,i=e.displayName||e.name,l=({...e})=>{var t;const o=a.useStoreManagerContext(),{parentId:s}=a.useStoreManagerParentContext(),l=null===(t=u.default.useId)||void 0===t?void 0:t.call(u.default),[{contextId:f,initStores:x}]=r.useState((()=>{const e=o.createContextId(d||l);return{contextId:e,initStores:o.createStores(Object.entries(n),s,e,i)}}));return r.useEffect((()=>o.mountStores(x)),[x,o]),u.default.createElement(a.StoreManagerParentProvider,{parentId:f},u.default.createElement(c,{...x,...e}))};return o.default(l,e),l.displayName=`Mobx(${i})`,l};
1
+ "use strict";var e=require("hoist-non-react-statics"),t=require("mobx-react-lite"),r=require("react"),a=require("./context.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(e),u=n(r);module.exports=(e,n,s)=>{const i=t.observer(e),c=s||e.libStoreContextId,d=e.displayName||e.name,l=({...e})=>{var t;const o=a.useStoreManagerContext(),{parentId:s}=a.useStoreManagerParentContext(),l=null===(t=u.default.useId)||void 0===t?void 0:t.call(u.default),[{contextId:f,initStores:x}]=r.useState((()=>{const e=o.createContextId(c||l);return{contextId:e,initStores:o.createStores(Object.entries(n),s,e,d)}}));return r.useEffect((()=>o.mountStores(x)),[x,o]),u.default.createElement(a.StoreManagerParentProvider,{parentId:f},u.default.createElement(i,{...x,...e}))};return o.default(l,e),l.displayName=`Mobx(${d})`,l};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lomray/react-mobx-manager",
3
- "version": "1.3.0",
3
+ "version": "1.3.1-beta.2",
4
4
  "description": "This package provides Mobx stores manager for react.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",