@adimm/x-injection-reactjs 0.1.2 → 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,193 +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
- return (
92
- <ModuleProvider
93
- module={RandomNumberComponentModule}
94
- render={() => {
95
- const service = useInject(RandomNumberService);
96
-
97
- return <h1>A random number: {service.generate()}</h1>;
98
- }}
99
- />
100
- );
105
+ interface UserInfoProps {
106
+ firstName: string;
107
+ lastName: string;
101
108
  }
102
109
  ```
103
110
 
104
- ### Component with public context
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
114
+
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:
105
116
 
106
- #### Safe method
117
+ > **Note:** _This is the preferred method as it allows you to avoid wrapping your component within another provider once created._
107
118
 
108
119
  ```tsx
109
- export class RandomNumberService {
110
- generate(): number {
111
- /* ... */
112
- }
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>
113
135
  }
136
+ ```
114
137
 
115
- // Make sure to use the `ComponentProviderModule` from `@adimm/x-injection-reactjs` not the `ProviderModule` from `@adimm/x-injection`!
116
- export const RandomNumberComponentModule = new ComponentProviderModule({
117
- identifier: Symbol('RandomNumberComponentModule'),
118
- providers: [RandomNumberService],
119
- exports: [RandomNumberService],
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:
141
+
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._
143
+
144
+ ```tsx
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>;
152
+ }
153
+
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],
120
200
  });
201
+ ```
121
202
 
122
- export function RandomNumberComponent(props: RandomNumberComponentProps) {
123
- <ModuleProvider
124
- module={RandomNumberComponentModule}
125
- render={() => {
126
- // This hook is necessary in order to expose the component instance
127
- // context up to the parent component
128
- useExposeComponentModuleContext();
203
+ Now you can use it in inside any component which has access to a contextualized module which can provide the `UserService`.
129
204
 
130
- const service = useInject(RandomNumberService);
205
+ ```tsx
206
+ export function UserInfo({ firstName, lastName }: UserInfoProps) {
207
+ const userFullName = useGenerateFullName({ firstName, lastName });
131
208
 
132
- return <h1>A random number: {service.generate()}</h1>;
133
- }}
134
- />;
209
+ return <p>Hello {userFullName}!</p>;
135
210
  }
211
+ ```
136
212
 
137
- ////////////////////////////////////////
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>
138
229
 
139
- export class ParentService {
140
- constructor(public readonly randomNumberService: RandomNumberService) {}
230
+ > Inputbox
141
231
 
142
- injectRandomNumberService(service: RandomNumberService): void {
143
- this.randomNumberService = service;
232
+ `inputbox.service.ts`
233
+
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);
144
247
  }
145
248
  }
146
249
 
147
- export const ParentServiceComponentModule = new ComponentProviderModule({
148
- identifier: Symbol('ParentServiceComponentModule'),
149
- imports: [RandomNumberComponentModule],
150
- providers: [ParentService],
250
+ export const InputboxModule = new ComponentProviderModule({
251
+ identifier: Symbol('InputboxModule'),
252
+ provides: [InputboxService],
253
+ exports: [InputboxService],
151
254
  });
255
+ ```
152
256
 
153
- export function ParentComponent(props: ParentComponentProps) {
154
- return (
155
- <ModuleProvider
156
- module={ParentServiceComponentModule}
157
- render={() => {
158
- const service = useInject(ParentService);
159
-
160
- return (
161
- <>
162
- <TapIntoComponent
163
- // By using the fluid syntax
164
- contextInstance={() => ({
165
- // If one of the children did expose the `RandomNumberComponentModule`
166
- // module, we'll be able to access its instance.
167
- tryGet: RandomNumberComponentModule,
168
- thenDo: (ctx) => {
169
- const randomNumberService_FromComponentInstance = ctx.get(RandomNumberComponentModule);
170
-
171
- service.injectRandomNumberService(randomNumberService_FromComponentInstance);
172
- },
173
- })}>
174
- <RandomNumberComponent />
175
- </TapIntoComponent>
176
-
177
- <TapIntoComponent
178
- // By accessing the entire underlying context map which may contain even more
179
- // modules exposed by more children down the tree.
180
- contextInstance={(ctxMap) => {
181
- const ctx = ctxMap.get(RandomNumberComponentModule.toString());
182
- if (!ctx) return;
183
-
184
- const randomNumberService_FromComponentInstance = ctx.get(RandomNumberComponentModule);
185
-
186
- service.injectRandomNumberService(randomNumberService_FromComponentInstance);
187
- }}>
188
- <RandomNumberComponent />
189
- </TapIntoComponent>
190
- </>
191
- );
192
- }}
193
- />
194
- );
257
+ `inputbox.tsx`
258
+
259
+ ```tsx
260
+ export interface InputboxProps {
261
+ initialValue: string;
195
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
+ });
196
275
  ```
197
276
 
198
- #### Experimental method
277
+ <hr>
278
+
279
+ > Listview
280
+
281
+ `listview.service.ts`
199
282
 
200
- 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
201
- or introduce unknown bugs, please use it carefully and with diligence!
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`
202
299
 
203
300
  ```tsx
204
- 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
+
205
310
  return (
206
- <ModuleProvder
207
- module={ParentServiceComponentModule}
208
- render={() => {
209
- // By using this hook, the component will always re-render whenever
210
- // a child using a ProviderModule which is also imported into the parent ProviderModule,
211
- // has mounted and rendered!
212
- useRerenderOnChildrenModuleContextLoaded();
213
-
214
- // We should use the `useInjectOnRender` instead of the default `useInject`
215
- // hook which re-uses the same instance of the injected dependency
216
- // between re-renders.
217
- //
218
- // Note: It may still work with the `useInject` hook too, but it may not be predictable.
219
- const service = useInjectOnRender(ParentService);
220
-
221
- // At this point the `service.randomNumberService` instance should be the one
222
- // from the `RandomNumberComponent` below.
223
- //
224
- // Note: Expect during the 1st render cycle to not be the same instance as the one used by the child component!
225
- // The `xInjection` container will still supply the correct provider to the
226
- // constructor parameter, but it'll be a new transient instance.
227
- console.log(service.randomNumberService.generate());
228
-
229
- // As we are now using the `useRerenderOnChildrenModuleContextLoaded` hook
230
- // there's no need anymore for the `TapIntoComponent` wrapper.
231
- return <RandomNumberComponent />;
232
- }}
233
- />
311
+ <div>
312
+ {service.items.map((item) => (
313
+ <span key={item}>{item}</span>
314
+ ))}
315
+ </div>
234
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 */
235
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
+ });
236
352
  ```
237
353
 
238
- The `ModuleProvider` component also accepts the `children` prop, this means you can also use it like this:
354
+ `dropdown.tsx`
239
355
 
240
356
  ```tsx
241
- export function Component() {
242
- return <h1>Hello World!</h1>;
357
+ export interface DropdownProps {
358
+ listviewProps: ListviewProps;
359
+
360
+ initialSelectedValue: number;
243
361
  }
244
362
 
245
- function MyApp() {
246
- return (
247
- <ModuleProvider module={ComponentModule}>
248
- <Component />
249
- </ModuleProvider>
250
- );
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 */
251
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;
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
+ );
252
462
  ```
253
463
 
254
- > **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._
255
467
 
256
468
  ## Documentation
257
469