@adimm/x-injection-reactjs 0.1.1 → 0.2.0

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/README.md CHANGED
@@ -18,11 +18,13 @@ xInjection ReactJS&nbsp;<a href="https://www.npmjs.com/package/@adimm/x-injectio
18
18
  - [Installation](#installation)
19
19
  - [TypeScript Configuration](#typescript-configuration)
20
20
  - [Getting Started](#getting-started)
21
+ - [Component ProviderModules](#component-providermodules)
22
+ - [Component Injection](#component-injection)
23
+ - [Via anonymous function](#via-anonymous-function)
24
+ - [Via named function](#via-named-function)
25
+ - [Hook Injection](#hook-injection)
21
26
  - [Examples](#examples)
22
- - [Component with private context](#component-with-private-context)
23
- - [Component with public context](#component-with-public-context)
24
- - [Safe method](#safe-method)
25
- - [Experimental method](#experimental-method)
27
+ - [Composable components](#composable-components)
26
28
  - [Documentation](#documentation)
27
29
  - [Contributing](#contributing)
28
30
 
@@ -65,186 +67,403 @@ Add the following options to your `tsconfig.json` to enable decorator metadata:
65
67
 
66
68
  ## Getting Started
67
69
 
68
- If you never used the parent library (`xInjection`), then please access the official [xInjection Repository](https://github.com/AdiMarianMutu/x-injection?tab=readme-ov-file#registering-global-providers) to better understand how to use its `ReactJS` implementation.
70
+ If you never used the parent library (`xInjection`), then please access the official [xInjection Repository](https://github.com/AdiMarianMutu/x-injection?tab=readme-ov-file#getting-started) to better understand how to use its `ReactJS` implementation.
69
71
 
70
- ## Examples
72
+ ### Component ProviderModules
71
73
 
72
- ### Component with private context
74
+ A [ComponentProviderModule](https://adimarianmutu.github.io/x-injection-reactjs/interfaces/IComponentProviderModule.html) isn't so different than the original [ProviderModule](https://adimarianmutu.github.io/x-injection/interfaces/IProviderModule.html) from the base `xInjection` library, the main difference being that it'll automatically create a [clone](https://adimarianmutu.github.io/x-injection-reactjs/interfaces/IComponentProviderModule.html#clone) of itself whenever a component is `mounted` and during the `unmount` process it'll [dispose](https://adimarianmutu.github.io/x-injection-reactjs/interfaces/IComponentProviderModule.html#dispose) itself.
73
75
 
74
- A component with a private context it means that when it'll inject dependencies from a module within its instance,
75
- a parent component will not be able to access those dependencies instances.
76
+ This is needed so:
76
77
 
77
- ```tsx
78
- export class RandomNumberService {
79
- generate(): number {
80
- /* ... */
78
+ - Each instance of a component has its own instance of the `ProviderModule` _(also known as `ContextualizedModule`)_
79
+ - Whenever a component is unmounted, the container of that `ContextualizedModule` is destroyed, making sure that the resources can be garbage-collected by the JS garbage collector.
80
+
81
+ > **Note:** By default each `ContextualizedModule` has its `InjectionScope` set to `Singleton`, you can of course change it by providing the [defaultScope](https://adimarianmutu.github.io/x-injection/interfaces/ProviderModuleOptions.html#defaultscope) property.
82
+
83
+ ### Component Injection
84
+
85
+ In order to be able to inject dependencies into your components, you must first supply them with a `ComponentProviderModule`.
86
+
87
+ This is how you can create one:
88
+
89
+ ```ts
90
+ @Injectable()
91
+ export class UserService {
92
+ firstName: string;
93
+ lastName: string;
94
+
95
+ generateFullName(): string {
96
+ return `${firstName} ${lastName}`;
81
97
  }
82
98
  }
83
99
 
84
- // Make sure to use the `ComponentProviderModule` from `@adimm/x-injection-reactjs` not the `ProviderModule` from `@adimm/x-injection`!
85
- export const RandomNumberComponentModule = new ComponentProviderModule({
86
- identifier: Symbol('RandomNumberComponentModule'),
87
- providers: [RandomNumberService],
100
+ export const UserComponentModule = new ComponentProviderModule({
101
+ identifier: Symbol('UserComponentModule'),
102
+ providers: [UserService],
88
103
  });
89
104
 
90
- export function RandomNumberComponent(props: RandomNumberComponentProps) {
91
- const service = useInject(RandomNumberService);
105
+ interface UserInfoProps {
106
+ firstName: string;
107
+ lastName: string;
108
+ }
109
+ ```
110
+
111
+ Now you have to actually provide the `UserComponentModule` to your component(s). You can do so with 2 different methods:
112
+
113
+ #### Via anonymous function
92
114
 
93
- return <h1>A random number: {service.generate()}</h1>;
115
+ If you prefer to use the `const Component = () => {}` syntax, then you must use the [provideModuleToComponent](https://adimarianmutu.github.io/x-injection-reactjs/functions/provideModuleToComponent.html) method as shown below:
116
+
117
+ > **Note:** _This is the preferred method as it allows you to avoid wrapping your component within another provider once created._
118
+
119
+ ```tsx
120
+ // The UserInfo component will correctly infer the interface of `UserInfoProps` automatically!
121
+ export const UserInfo = provideModuleToComponent(UserComponentModule, ({ firstName, lastName }: UserInfoProps) => {
122
+ const userService = useInject(UserService);
123
+
124
+ userService.firstName = firstName;
125
+ userService.lastName = lastName;
126
+
127
+ return <p>Hello {userService.generateFullName()}!</p>;
128
+ });
129
+
130
+ function MyApp() {
131
+ return <UserInfo firstName="John" lastName="Doe" />;
132
+ // Result
133
+ //
134
+ // <p>Hello John Doe!</p>
94
135
  }
95
136
  ```
96
137
 
97
- ### Component with public context
138
+ #### Via named function
139
+
140
+ Or if you prefer to use the `function Component() {}` syntax, then you must use the [ProvideModule](https://adimarianmutu.github.io/x-injection-reactjs/functions/ProvideModule.html) `HoC` as shown below:
98
141
 
99
- #### Safe method
142
+ > **Note:** _If you need to access the contextualized `module` forwarded to your component, you can wrap the component props with the [PropsWithModule](https://adimarianmutu.github.io/x-injection-reactjs/types/PropsWithModule.html) generic type._
100
143
 
101
144
  ```tsx
102
- export class RandomNumberService {
103
- generate(): number {
104
- /* ... */
105
- }
145
+ export function UserInfo({ firstName, lastName }: UserInfoProps) {
146
+ const userService = useInject(UserService);
147
+
148
+ userService.firstName = firstName;
149
+ userService.lastName = lastName;
150
+
151
+ return <p>Hello {userService.generateFullName()}!</p>;
106
152
  }
107
153
 
108
- // Make sure to use the `ComponentProviderModule` from `@adimm/x-injection-reactjs` not the `ProviderModule` from `@adimm/x-injection`!
109
- export const RandomNumberComponentModule = new ComponentProviderModule({
110
- identifier: Symbol('RandomNumberComponentModule'),
111
- providers: [RandomNumberService],
112
- exports: [RandomNumberService],
154
+ function MyApp() {
155
+ return (
156
+ <ProvideModule module={UserComponentModule}>
157
+ <UserInfo firstName="John" lastName="Doe" />
158
+ </ProvideModule>
159
+ );
160
+ // Result
161
+ //
162
+ // <p>Hello John Doe!</p>
163
+ }
164
+ ```
165
+
166
+ That's all you need to do, at least for simple components 😃.
167
+
168
+ > You can find more complex examples at the [Examples](#examples) section.
169
+
170
+ ### Hook Injection
171
+
172
+ You already have seen in action the low-level [useInject](https://adimarianmutu.github.io/x-injection-reactjs/functions/useInject.html) hook _(take a look also at the [useInjectMany](https://adimarianmutu.github.io/x-injection-reactjs/functions/useInjectMany.html) hook)_. It is quite useful when you just have to inject quickly some dependencies into a component quite simple.
173
+
174
+ What it does under the hood? Finds the nearest contextualized module and resolves from it the required dependencies into your component, that's all.
175
+
176
+ But, as your UI will grow, you'll soon discover that you may inject more dependencies into a component, or even in multiple components, therefore you'll end up writing a lot of duplicated code, well, as per the [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself#:~:text=%22Don't%20repeat%20yourself%22,redundancy%20in%20the%20first%20place.) principle, that's not good! 🥲
177
+
178
+ This means that we can actually use the [hookFactory](https://adimarianmutu.github.io/x-injection-reactjs/functions/hookFactory.html) method to compose a _custom_ hook with access to any dependency available in the component contextualized module.
179
+
180
+ Having the above examples with the `UserService`, we'll create a custom `generateFullName` hook.
181
+
182
+ ```ts
183
+ // The `HookWithDeps` generic type will help
184
+ // in making sure that the `useGenerateUserFullName` hooks params are correctly visible.
185
+ // The 1st generic param must be the hook params (Like `UserInfoProps`)
186
+ // and starting from the 2nd generic param you must provide the type of your dependencies.
187
+ const useGenerateUserFullName = hookFactory({
188
+ // The `use` property is where you write your hook implementation.
189
+ use: ({ firstName, lastName, deps: [userService] }: HookWithDeps<UserInfoProps, UserService>) => {
190
+ userService.firstName = firstName;
191
+ userService.lastName = lastName;
192
+
193
+ return userService.generateFullName();
194
+ },
195
+ // The `inject` array is very important,
196
+ // here we basically specify which dependencies should be injected into the custom hook.
197
+ // Also, keep in mind that the order of the `inject` array matters, the order of the `deps` prop
198
+ // is determined by the order of the `inject` array!
199
+ inject: [UserService],
113
200
  });
201
+ ```
114
202
 
115
- export function RandomNumberComponent(props: RandomNumberComponentProps) {
116
- <ModuleProvider
117
- module={RandomNumberComponentModule}
118
- render={() => {
119
- // This hook is necessary in order to expose the component instance
120
- // context up to the parent component
121
- useExposeComponentModuleContext();
203
+ Now you can use it in inside any component which has access to a contextualized module which can provide the `UserService`.
122
204
 
123
- const service = useInject(RandomNumberService);
205
+ ```tsx
206
+ export function UserInfo({ firstName, lastName }: UserInfoProps) {
207
+ const userFullName = useGenerateFullName({ firstName, lastName });
124
208
 
125
- return <h1>A random number: {service.generate()}</h1>;
126
- }}
127
- />;
209
+ return <p>Hello {userFullName}!</p>;
128
210
  }
211
+ ```
212
+
213
+ ## Examples
214
+
215
+ ### Composable components
216
+
217
+ In a real world scenario, you'll definitely have custom components which render other custom components and so on... _(like a [Matryoshka doll](https://en.wikipedia.org/wiki/Matryoshka_doll))_
218
+
219
+ So you may find yourself wanting to be able to control a dependency/service of a child component from a parent component, with `xInject` this is very easy to achieve thanks to the `ProviderModule` architecture, because each `module` can `import` and `export` other dependencies _(or modules)_ it fits in perfectly within the [declarative programming](https://en.wikipedia.org/wiki/Declarative_programming) world!
220
+
221
+ In this example, we'll build 4 components, each with its own purpose. However, the `autocomplete` component will be the one capable of accessing the services of all of them.
222
+
223
+ - An `inputbox`
224
+ - A `list viewer`
225
+ - A `dropdown`
226
+ - An `autocomplete`
227
+
228
+ <hr>
129
229
 
130
- ////////////////////////////////////////
230
+ > Inputbox
131
231
 
132
- export class ParentService {
133
- constructor(public readonly randomNumberService: RandomNumberService) {}
232
+ `inputbox.service.ts`
134
233
 
135
- injectRandomNumberService(service: RandomNumberService): void {
136
- this.randomNumberService = service;
234
+ ```ts
235
+ @Injectable()
236
+ export class InputboxService {
237
+ currentValue = '';
238
+
239
+ // We'll initialize this soon enough.
240
+ setStateValue!: (newValue: string) => void;
241
+
242
+ /** Can be used to update the {@link currentValue} of the `inputbox`. */
243
+ setValue(newValue: string): void {
244
+ this.currentValue = newValue;
245
+
246
+ this.setStateValue(this.currentValue);
137
247
  }
138
248
  }
139
249
 
140
- export const ParentServiceComponentModule = new ComponentProviderModule({
141
- identifier: Symbol('ParentServiceComponentModule'),
142
- imports: [RandomNumberComponentModule],
143
- providers: [ParentService],
250
+ export const InputboxModule = new ComponentProviderModule({
251
+ identifier: Symbol('InputboxModule'),
252
+ provides: [InputboxService],
253
+ exports: [InputboxService],
144
254
  });
255
+ ```
145
256
 
146
- export function ParentComponent(props: ParentComponentProps) {
147
- return (
148
- <ModuleProvider
149
- module={ParentServiceComponentModule}
150
- render={() => {
151
- const service = useInject(ParentService);
152
-
153
- return (
154
- <>
155
- <TapIntoComponent
156
- // By using the fluid syntax
157
- contextInstance={() => ({
158
- // If one of the children did expose the `RandomNumberComponentModule`
159
- // module, we'll be able to access its instance.
160
- tryGet: RandomNumberComponentModule,
161
- thenDo: (ctx) => {
162
- const randomNumberService_FromComponentInstance = ctx.get(RandomNumberComponentModule);
163
-
164
- service.injectRandomNumberService(randomNumberService_FromComponentInstance);
165
- },
166
- })}>
167
- <RandomNumberComponent />
168
- </TapIntoComponent>
169
-
170
- <TapIntoComponent
171
- // By accessing the entire underlying context map which may contain even more
172
- // modules exposed by more children down the tree.
173
- contextInstance={(ctxMap) => {
174
- const ctx = ctxMap.get(RandomNumberComponentModule.toString());
175
- if (!ctx) return;
176
-
177
- const randomNumberService_FromComponentInstance = ctx.get(RandomNumberComponentModule);
178
-
179
- service.injectRandomNumberService(randomNumberService_FromComponentInstance);
180
- }}>
181
- <RandomNumberComponent />
182
- </TapIntoComponent>
183
- </>
184
- );
185
- }}
186
- />
187
- );
257
+ `inputbox.tsx`
258
+
259
+ ```tsx
260
+ export interface InputboxProps {
261
+ initialValue: string;
188
262
  }
263
+
264
+ export const Inputbox = provideModuleToComponent(InputboxModule, ({ initialValue }: InputboxProps) => {
265
+ const service = useInject(InputboxService);
266
+ const [, setCurrentValue] = useState(initialValue);
267
+ service.setStateValue = setCurrentValue;
268
+
269
+ useEffect(() => {
270
+ service.currentValue = initialValue;
271
+ }, [initialValue]);
272
+
273
+ return <input value={service.currentValue} onChange={(e) => service.setValue(e.currentTarget.value)} />;
274
+ });
189
275
  ```
190
276
 
191
- #### Experimental method
277
+ <hr>
278
+
279
+ > Listview
192
280
 
193
- There is another method which is currently in _experimental_ mode and it may not always work as expected, it may even produce unnecessary re-render cycles
194
- or introduce unknown bugs, please use it carefully and with diligence!
281
+ `listview.service.ts`
282
+
283
+ ```ts
284
+ @Injectable()
285
+ export class ListviewService {
286
+ items = [];
287
+
288
+ /* Remaining fancy implementation */
289
+ }
290
+
291
+ export const ListviewModule = new ComponentProviderModule({
292
+ identifier: Symbol('ListviewModule'),
293
+ provides: [ListviewService],
294
+ exports: [ListviewService],
295
+ });
296
+ ```
297
+
298
+ `listview.tsx`
195
299
 
196
300
  ```tsx
197
- export function ParentComponent(props: ParentComponentProps) {
301
+ export interface ListviewProps {
302
+ items: any[];
303
+ }
304
+
305
+ export const Listview = provideModuleToComponent(ListviewModule, ({ items }: ListviewProps) => {
306
+ const service = useInject(ListviewService);
307
+
308
+ /* Remaining fancy implementation */
309
+
198
310
  return (
199
- <ModuleProvder
200
- module={ParentServiceComponentModule}
201
- render={() => {
202
- // By using this hook, the component will always re-render whenever
203
- // a child using a ProviderModule which is also imported into the parent ProviderModule,
204
- // has mounted and rendered!
205
- useRerenderOnChildrenModuleContextLoaded();
206
-
207
- // We should use the `useInjectOnRender` instead of the default `useInject`
208
- // hook which re-uses the same instance of the injected dependency
209
- // between re-renders.
210
- //
211
- // Note: It may still work with the `useInject` hook too, but it may not be predictable.
212
- const service = useInjectOnRender(ParentService);
213
-
214
- // At this point the `service.randomNumberService` instance should be the one
215
- // from the `RandomNumberComponent` below.
216
- //
217
- // Note: Expect during the 1st render cycle to not be the same instance as the one used by the child component!
218
- // The `xInjection` container will still supply the correct provider to the
219
- // constructor parameter, but it'll be a new transient instance.
220
- console.log(service.randomNumberService.generate());
221
-
222
- // As we are now using the `useRerenderOnChildrenModuleContextLoaded` hook
223
- // there's no need anymore for the `TapIntoComponent` wrapper.
224
- return <RandomNumberComponent />;
225
- }}
226
- />
311
+ <div>
312
+ {service.items.map((item) => (
313
+ <span key={item}>{item}</span>
314
+ ))}
315
+ </div>
227
316
  );
317
+ });
318
+ ```
319
+
320
+ <hr>
321
+
322
+ > Dropdown
323
+
324
+ Now keep close attention to how we implement the `Dropdown` component, as it'll actually be the _parent_ controlling the `Listview` component own service.
325
+
326
+ `dropdown.service.ts`
327
+
328
+ ```ts
329
+ @Injectable()
330
+ export class DropdownService {
331
+ constructor(readonly listviewService: ListviewService) {
332
+ // We can already take control of the children `ListviewService`!
333
+ this.listviewService.items = [1, 2, 3, 4, 5];
334
+ }
335
+
336
+ /* Remaining fancy implementation */
228
337
  }
338
+
339
+ export const DropdownModule = new ComponentProviderModule({
340
+ identifier: Symbol('DropdownModule'),
341
+ // It is very important that we import all the exportable dependencies from the `ListviewModule`!
342
+ imports: [ListviewModule],
343
+ provides: [DropdownService],
344
+ exports: [
345
+ // Let's also re-export the dependencies of the `ListviewModule` so once we import the `DropdownModule`
346
+ // somewhere elese, we get access to the `ListviewModule` exported dependencies as well!
347
+ ListviewModule,
348
+ // Let's not forget to also export our `DropdownService` :)
349
+ DropdownService,
350
+ ],
351
+ });
229
352
  ```
230
353
 
231
- The `ModuleProvider` component also accepts the `children` prop, this means you can also use it like this:
354
+ `dropdown.tsx`
232
355
 
233
356
  ```tsx
234
- export function Component() {
235
- return <h1>Hello World!</h1>;
357
+ export interface DropdownProps {
358
+ listviewProps: ListviewProps;
359
+
360
+ initialSelectedValue: number;
236
361
  }
237
362
 
238
- function MyApp() {
239
- return (
240
- <ModuleProvider module={ComponentModule}>
241
- <Component />
242
- </ModuleProvider>
243
- );
363
+ export const Dropdown = provideModuleToComponent(
364
+ ListviewModule,
365
+ ({
366
+ listviewProps,
367
+ initialSelectedValue,
368
+ // Here it is important that we get access to the contextualized module
369
+ // so we can forward it to the `Listview` component!
370
+ module,
371
+ }: DropdownProps) => {
372
+ const service = useInject(DropdownService);
373
+
374
+ /* Remaining fancy implementation */
375
+
376
+ return (
377
+ <div className="fancy-dropdown">
378
+ <span>{initialSelectedValue}</span>
379
+
380
+ {/* Here we forward the contextualized module which will be sent from the parent component consuming this component,
381
+ in our case, the `Autocomplete` component. */}
382
+ <Listview module={module} />
383
+ </div>
384
+ );
385
+ }
386
+ );
387
+ ```
388
+
389
+ <hr>
390
+
391
+ > Autocomplete
392
+
393
+ And finally the grand finale!
394
+
395
+ `autocomplete.service.ts`
396
+
397
+ ```ts
398
+ @Injectable()
399
+ export class AutocompleteService {
400
+ constructor(
401
+ readonly inputboxService: InputboxService,
402
+ readonly dropdownService: DropdownService
403
+ ) {
404
+ // Here we can override even what the `Dropdown` has already overriden!
405
+ this.dropdownService.listviewService.items = [29, 9, 1969];
406
+
407
+ // However doing the following, will throw an error because the `Inputbox` component
408
+ // at this time is not yet mounted, therefore the `setStateValue` state setter
409
+ // method doesn't exist yet.
410
+ //
411
+ // A better way would be to use a store manager so you can generate your application state through
412
+ // the services, rather than inside the UI (components should be used only to render the data, not to manipulate/manage it).
413
+ this.inputboxService.setValue('xInjection');
414
+ }
415
+
416
+ /* Remaining fancy implementation */
417
+ }
418
+
419
+ export const AutocompleteModule = new ComponentProviderModule({
420
+ identifier: Symbol('AutocompleteModule'),
421
+ imports: [InputboxModule, DropdownModule],
422
+ provides: [AutocompleteService],
423
+ // If we don't plan to share the internal dependencies of the
424
+ // Autocomplete component, then we can omit the `exports` array declaration.
425
+ });
426
+ ```
427
+
428
+ `autocomplete.tsx`
429
+
430
+ ```tsx
431
+ export interface AutocompleteProps {
432
+ inputboxProps: InputboxProps;
433
+ dropdownProps: DropdownProps;
434
+
435
+ currentText: string;
244
436
  }
437
+
438
+ export const Autocomplete = provideModuleToComponent(
439
+ AutocompleteModule,
440
+ ({
441
+ dropdownProps,
442
+ currentText,
443
+
444
+ module,
445
+ }: AutocompleteProps) => {
446
+ const service = useInject(AutocompleteService);
447
+
448
+ console.log(service.dropdownService.listviewService.items);
449
+ // Produces: [29, 9, 1969]
450
+
451
+ /* Remaining fancy implementation */
452
+
453
+ return (
454
+ <div className="fancy-autocomplete">
455
+ {/* Let's not forget to forward the module to both components we want to control */}
456
+ <Inputbox {...inputboxProps} module={module} >
457
+ <Dropdown {...dropdownProps} module={module} />
458
+ </div>
459
+ );
460
+ }
461
+ );
245
462
  ```
246
463
 
247
- > **Note:** You don't have to wrap your entire application with a `ModuleProvider` which provides the `AppModule`, the global container is already available to use and all your `ComponentProviderModule` know ouf-of-the-box how to access it when you provide them with providers registered into the `AppModule`.
464
+ This should cover the fundamentals of how you can build a scalable UI by using the `xInjection` Dependency Injection 😊
465
+
466
+ > **Note:** _Keep in mind that both library ([xInjection](https://www.npmjs.com/package/@adimm/x-injection) & [xInjection ReactJS](https://www.npmjs.com/package/@adimm/x-injection-reactjs)) are still young and being developed, therefore the internals and public API may change in the near future._
248
467
 
249
468
  ## Documentation
250
469