@servicetitan/docs-uikit 36.2.0 → 36.3.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/docs/install.mdx +1 -1
- package/docs/react-ioc.mdx +441 -82
- package/docs/startup/test/test.mdx +50 -0
- package/package.json +2 -2
package/docs/install.mdx
CHANGED
|
@@ -40,7 +40,7 @@ The `npx --yes @servicetitan/install` command works regardless of which package
|
|
|
40
40
|
|
|
41
41
|
### pnpm support
|
|
42
42
|
|
|
43
|
-
✨ New in **
|
|
43
|
+
✨ New in **36.2.0** ✨
|
|
44
44
|
|
|
45
45
|
`@servicetitan/startup` includes experimental pnpm support. See the [Switching to pnpm](/docs/frontend/switching-to-pnpm) migration guide to get started.
|
|
46
46
|
|
package/docs/react-ioc.mdx
CHANGED
|
@@ -4,55 +4,121 @@ title: React IoC
|
|
|
4
4
|
|
|
5
5
|
#### [CHANGELOG (@servicetitan/react-ioc)](https://github.com/servicetitan/uikit/blob/master/packages/react-ioc/CHANGELOG.md)
|
|
6
6
|
|
|
7
|
-
`@servicetitan/react-ioc` is an implementation of [InversifyJS](https://
|
|
7
|
+
`@servicetitan/react-ioc` is an implementation of [InversifyJS](https://inversify.io/) for React applications. It uses the React Context API to manage hierarchical dependency injection containers, so services declared higher in the component tree are visible to descendants and can be overridden in sub-trees.
|
|
8
8
|
|
|
9
9
|
## Features
|
|
10
10
|
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
11
|
+
- Hierarchical dependency injection mirroring the React tree
|
|
12
|
+
- Singleton and transient (per-resolve) bindings
|
|
13
|
+
- Decorator-based and JSX-based providers and injections
|
|
14
|
+
- Hook and decorator consumers for function and class components
|
|
15
|
+
- Automatic disposal of provided services on unmount
|
|
16
|
+
- Async store initialization with loading and error fallbacks
|
|
15
17
|
|
|
16
|
-
##
|
|
18
|
+
## Setup
|
|
17
19
|
|
|
18
|
-
###
|
|
20
|
+
### Install
|
|
19
21
|
|
|
20
|
-
|
|
22
|
+
```bash
|
|
23
|
+
npm install @servicetitan/react-ioc
|
|
24
|
+
```
|
|
21
25
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
+
The package imports `reflect-metadata` for you. Do not import it again in your application.
|
|
27
|
+
|
|
28
|
+
### TypeScript configuration
|
|
29
|
+
|
|
30
|
+
Decorator-based APIs (`@injectable`, `@inject`, `@injectDependency`, `@provide`) require these compiler options:
|
|
31
|
+
|
|
32
|
+
```json title="tsconfig.json"
|
|
33
|
+
{
|
|
34
|
+
"compilerOptions": {
|
|
35
|
+
"experimentalDecorators": true,
|
|
36
|
+
"emitDecoratorMetadata": true
|
|
37
|
+
}
|
|
26
38
|
}
|
|
27
39
|
```
|
|
28
40
|
|
|
29
|
-
|
|
41
|
+
:::note
|
|
42
|
+
Projects extending `@servicetitan/startup/tsconfig/base` already have both flags enabled and need no further configuration.
|
|
43
|
+
:::
|
|
30
44
|
|
|
31
|
-
|
|
45
|
+
The hook-based APIs (`useDependencies`, `useOptionalDependencies`) and the JSX `<Provider>` work without decorators.
|
|
32
46
|
|
|
33
|
-
|
|
34
|
-
|
|
47
|
+
## Concepts
|
|
48
|
+
|
|
49
|
+
### Container hierarchy
|
|
50
|
+
|
|
51
|
+
Every `<Provider>` (or `@provide`-decorated component) creates a new InversifyJS [Container](https://inversify.io/docs/6.x/api/container/) whose parent is the container from the nearest ancestor Provider. When a consumer asks for a token, the container walks up the chain until a match is found, exactly like React Context lookup.
|
|
52
|
+
|
|
53
|
+
This means you can re-provide a service for a sub-tree without disturbing the rest of the app. See [Reusing a parent binding](#inherit) for the `inherit` flag that opts back in to the parent's instance.
|
|
54
|
+
|
|
55
|
+
#### `rootContainer`
|
|
56
|
+
|
|
57
|
+
The chain terminates at `rootContainer`, an InversifyJS `Container` created at module load. It is also the default value of the underlying `ContainerContext`, so a consumer rendered without any `<Provider>` above it resolves against `rootContainer`. Two cases where you might bind directly into it:
|
|
58
|
+
|
|
59
|
+
- **App-wide globals without wrapping the whole tree.** Calling `rootContainer.bind(Logger).toConstantValue(...)` once at startup makes the binding visible to every consumer in the app, even ones rendered outside a `<Provider>`.
|
|
60
|
+
- **Resolving from non-React code** that runs before the React tree mounts.
|
|
61
|
+
|
|
62
|
+
Prefer `<Provider>` in normal application code. Bindings on `rootContainer` are global, persist for the lifetime of the process, and cannot be overridden by descendants the way Provider bindings can.
|
|
63
|
+
|
|
64
|
+
### Singletons vs instances
|
|
65
|
+
|
|
66
|
+
`<Provider>` accepts two lists, with different scopes.
|
|
67
|
+
|
|
68
|
+
| List | Scope | When to use |
|
|
69
|
+
| :----------- | :------------------------------------------------------------------------------- | :----------------------------------------------------------------------- |
|
|
70
|
+
| `singletons` | One instance per container. Every consumer in the sub-tree gets the same object. | Stores, services, anything that holds state shared across the sub-tree. |
|
|
71
|
+
| `instances` | A new instance per resolution (transient). | Stateless helpers, per-call value objects. Rare for typical store usage. |
|
|
72
|
+
|
|
73
|
+
### Tokens
|
|
74
|
+
|
|
75
|
+
A token identifies a binding. Three shapes are supported:
|
|
76
|
+
|
|
77
|
+
| Token form | Example | Notes |
|
|
78
|
+
| :------------------ | :------------------------------- | :----------------------------------------------------------------------------------------- |
|
|
79
|
+
| Class (constructor) | `Store` | Most common. The class itself is the token and the implementation. |
|
|
80
|
+
| Symbol token | `symbolToken<ILogger>('LOGGER')` | Use when there is no concrete class (interface only) or you need multiple implementations. |
|
|
81
|
+
| Function | A function reference | Allowed by the type, mainly for interop. Prefer classes or symbol tokens. |
|
|
82
|
+
|
|
83
|
+
## Providing services
|
|
84
|
+
|
|
85
|
+
### `Provider` {#provider}
|
|
86
|
+
|
|
87
|
+
JSX provider. Use anywhere in your tree.
|
|
35
88
|
|
|
36
|
-
|
|
89
|
+
```tsx
|
|
90
|
+
import { Provider } from '@servicetitan/react-ioc';
|
|
37
91
|
|
|
38
|
-
|
|
92
|
+
<Provider singletons={[Store]}>
|
|
93
|
+
<Component />
|
|
94
|
+
</Provider>;
|
|
39
95
|
```
|
|
40
96
|
|
|
41
|
-
|
|
97
|
+
#### Props
|
|
98
|
+
|
|
99
|
+
| Name | Type | Description |
|
|
100
|
+
| :---------------- | :--------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |
|
|
101
|
+
| `singletons` | [`ProviderConfigEntry[]`](#entry-shapes) | (optional) Singleton-scoped bindings. |
|
|
102
|
+
| `instances` | [`ProviderConfigEntry[]`](#entry-shapes) | (optional) Transient-scoped bindings. |
|
|
103
|
+
| `loadingFallback` | `ReactNode` | (optional) Rendered while [`Store.initialize`](#store-lifecycle) promises are pending. Defaults to `<h2>Loading...</h2>`. |
|
|
104
|
+
| `errorFallback` | `ReactNode` | (optional) Rendered when initialization throws or [duplicate tokens](#runtime-checks) are found. Defaults to `<h2>Error</h2>`. |
|
|
105
|
+
| `children` | `ReactNode` | The sub-tree that can consume the bindings. |
|
|
42
106
|
|
|
43
|
-
|
|
107
|
+
### `@provide` {#provide}
|
|
44
108
|
|
|
45
|
-
|
|
109
|
+
Decorator equivalent of `<Provider>`. Wraps a function or class component.
|
|
46
110
|
|
|
47
111
|
```tsx
|
|
48
|
-
|
|
112
|
+
import { provide } from '@servicetitan/react-ioc';
|
|
113
|
+
|
|
114
|
+
const Component = provide({
|
|
49
115
|
singletons: [Store],
|
|
50
|
-
})(() =>
|
|
51
|
-
return <SubComponent />;
|
|
52
|
-
});
|
|
116
|
+
})(() => <SubComponent />);
|
|
53
117
|
```
|
|
54
118
|
|
|
55
119
|
```tsx
|
|
120
|
+
import { provide } from '@servicetitan/react-ioc';
|
|
121
|
+
|
|
56
122
|
@provide({
|
|
57
123
|
singletons: [Store],
|
|
58
124
|
})
|
|
@@ -63,43 +129,150 @@ class Component extends React.Component {
|
|
|
63
129
|
}
|
|
64
130
|
```
|
|
65
131
|
|
|
66
|
-
|
|
132
|
+
#### Parameters
|
|
133
|
+
|
|
134
|
+
| Name | Type | Description |
|
|
135
|
+
| :-------- | :---------------------------------------------------- | :----------------------------------------------------------------------------------------------------- |
|
|
136
|
+
| `entries` | `{ singletons?, instances? }` | Same shape as the [`Provider`](#provider) `singletons` / `instances` props. |
|
|
137
|
+
| `options` | [`FallbackOptions`](#fallback-options) \| `ReactNode` | (optional) Fallback configuration. Passing a `ReactNode` is shorthand for `{ loadingFallback: node }`. |
|
|
138
|
+
|
|
139
|
+
#### `FallbackOptions` {#fallback-options}
|
|
140
|
+
|
|
141
|
+
| Name | Type | Description |
|
|
142
|
+
| :---------------- | :---------- | :----------------------------------------------------------------------------- |
|
|
143
|
+
| `loadingFallback` | `ReactNode` | (optional) Forwarded to [`Provider`](#provider) as the `loadingFallback` prop. |
|
|
144
|
+
| `errorFallback` | `ReactNode` | (optional) Forwarded to [`Provider`](#provider) as the `errorFallback` prop. |
|
|
145
|
+
|
|
146
|
+
```tsx
|
|
147
|
+
import { Spinner } from '@servicetitan/anvil2';
|
|
148
|
+
import { provide } from '@servicetitan/react-ioc';
|
|
149
|
+
|
|
150
|
+
// shorthand: ReactNode is treated as loadingFallback
|
|
151
|
+
const A = provide({ singletons: [Store] }, <Spinner />)(App);
|
|
152
|
+
|
|
153
|
+
// full options
|
|
154
|
+
const B = provide(
|
|
155
|
+
{ singletons: [Store] },
|
|
156
|
+
{ loadingFallback: <Spinner />, errorFallback: <ErrorScreen /> }
|
|
157
|
+
)(App);
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Provider entry shapes {#entry-shapes}
|
|
161
|
+
|
|
162
|
+
The four ways to write a binding in `singletons` or `instances`.
|
|
163
|
+
|
|
164
|
+
```tsx
|
|
165
|
+
import { Provider, symbolToken } from '@servicetitan/react-ioc';
|
|
166
|
+
|
|
167
|
+
// 1. Bare class. Token and implementation are the same.
|
|
168
|
+
<Provider singletons={[Store]} />;
|
|
169
|
+
|
|
170
|
+
// 2. Different implementation for a class token.
|
|
171
|
+
<Provider singletons={[{ provide: Store, useClass: StoreV2 }]} />;
|
|
172
|
+
|
|
173
|
+
// 3. Constant value for a symbol or function token.
|
|
174
|
+
const CONFIG_TOKEN = symbolToken<AppConfig>('APP_CONFIG');
|
|
175
|
+
<Provider singletons={[{ provide: CONFIG_TOKEN, useValue: { apiUrl: '/api' } }]} />;
|
|
176
|
+
|
|
177
|
+
// 4. Object form with only `provide`. Same as a bare class.
|
|
178
|
+
<Provider singletons={[{ provide: Store }]} />;
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
| Field | Type | Description |
|
|
182
|
+
| :--------- | :-------------------- | :---------------------------------------------------------------------------------------------------------------- |
|
|
183
|
+
| `provide` | [`Token<T>`](#tokens) | The identifier consumers ask for. |
|
|
184
|
+
| `useClass` | `Newable<T>` | (optional) Class to instantiate. If omitted on a class token, `provide` is used as both token and implementation. |
|
|
185
|
+
| `useValue` | `T` | (optional) Pre-built value. Cannot be combined with `useClass`. Only valid in `singletons`. |
|
|
186
|
+
| `inherit` | `true` | (optional) See [Reusing a parent binding](#inherit). Only valid in `singletons`. |
|
|
187
|
+
|
|
188
|
+
### Reusing a parent binding {#inherit}
|
|
67
189
|
|
|
68
|
-
|
|
190
|
+
`inherit: true` makes a binding skip itself if the token is already bound in an ancestor container. The descendant consumer ends up with the parent's instance.
|
|
69
191
|
|
|
70
192
|
```tsx
|
|
193
|
+
import { Provider } from '@servicetitan/react-ioc';
|
|
194
|
+
|
|
71
195
|
<Provider singletons={[Store]}>
|
|
72
|
-
<
|
|
73
|
-
</Provider
|
|
196
|
+
<Inner />
|
|
197
|
+
</Provider>;
|
|
198
|
+
|
|
199
|
+
// inside Inner:
|
|
200
|
+
<Provider singletons={[{ provide: Store, inherit: true }]}>
|
|
201
|
+
<Leaf /> {/* receives the outer Store instance */}
|
|
202
|
+
</Provider>;
|
|
74
203
|
```
|
|
75
204
|
|
|
76
|
-
|
|
205
|
+
Use this as a defensive measure when a component must declare its own dependency list to work standalone, but should reuse an ancestor's instance whenever one is present. Without `inherit`, the child would always create a fresh container-local instance and silently fork state from the enclosing scope.
|
|
206
|
+
|
|
207
|
+
### Runtime checks {#runtime-checks}
|
|
208
|
+
|
|
209
|
+
`Provider` validates `singletons` and `instances` at mount.
|
|
210
|
+
|
|
211
|
+
#### Duplicate entries
|
|
212
|
+
|
|
213
|
+
When a token is listed more than once, InversifyJS reports an "Ambiguous match" error at injection time, far from the offending list. `Provider` catches the duplicate at mount instead.
|
|
77
214
|
|
|
78
|
-
|
|
215
|
+
- In development, the provider renders `errorFallback` and throws an error that names every duplicated token.
|
|
216
|
+
- In production, it emits `console.warn` and binds only the first occurrence (singletons before instances).
|
|
79
217
|
|
|
80
218
|
```tsx
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
219
|
+
import { Provider } from '@servicetitan/react-ioc';
|
|
220
|
+
|
|
221
|
+
// SomeStore listed twice: throws in development, warns in production.
|
|
222
|
+
<Provider singletons={[SomeStore, SomeStore]}>
|
|
223
|
+
<Children />
|
|
224
|
+
</Provider>;
|
|
84
225
|
```
|
|
85
226
|
|
|
86
|
-
|
|
227
|
+
:::note
|
|
228
|
+
The same token appearing in both `singletons` and `instances` is also flagged.
|
|
229
|
+
:::
|
|
87
230
|
|
|
88
|
-
|
|
231
|
+
## Consuming services
|
|
232
|
+
|
|
233
|
+
### `useDependencies` {#use-dependencies}
|
|
234
|
+
|
|
235
|
+
Hook for function components. Returns a tuple in the order of the tokens passed.
|
|
89
236
|
|
|
90
237
|
```tsx
|
|
91
|
-
|
|
92
|
-
const [store] = useDependencies(Store);
|
|
238
|
+
import { useDependencies } from '@servicetitan/react-ioc';
|
|
93
239
|
|
|
240
|
+
const SubComponent: React.FC = () => {
|
|
241
|
+
const [store, logger] = useDependencies(Store, LOGGER_TOKEN);
|
|
94
242
|
return <div>{store.value}</div>;
|
|
95
243
|
};
|
|
96
244
|
```
|
|
97
245
|
|
|
98
|
-
|
|
246
|
+
Throws if any token is not bound in the container hierarchy.
|
|
247
|
+
|
|
248
|
+
### `useOptionalDependencies` {#use-optional-dependencies}
|
|
99
249
|
|
|
100
|
-
|
|
250
|
+
Same shape as `useDependencies`, but returns `undefined` for tokens that are not bound instead of throwing.
|
|
101
251
|
|
|
102
252
|
```tsx
|
|
253
|
+
import { useOptionalDependencies } from '@servicetitan/react-ioc';
|
|
254
|
+
|
|
255
|
+
const SaveButton: React.FC = () => {
|
|
256
|
+
const [log] = useOptionalDependencies(Log);
|
|
257
|
+
|
|
258
|
+
const onClick = () => {
|
|
259
|
+
log?.info('save clicked');
|
|
260
|
+
save();
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
return <button onClick={onClick}>Save</button>;
|
|
264
|
+
};
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Use this when a service is genuinely optional, for example a logger that is only bound in production builds. The component works either way and skips the call when `Log` is not provided.
|
|
268
|
+
|
|
269
|
+
### `@injectDependency` {#inject-dependency}
|
|
270
|
+
|
|
271
|
+
Property decorator for class components.
|
|
272
|
+
|
|
273
|
+
```tsx
|
|
274
|
+
import { injectDependency } from '@servicetitan/react-ioc';
|
|
275
|
+
|
|
103
276
|
class SubComponent extends React.Component {
|
|
104
277
|
@injectDependency(Store)
|
|
105
278
|
store!: Store;
|
|
@@ -110,11 +283,148 @@ class SubComponent extends React.Component {
|
|
|
110
283
|
}
|
|
111
284
|
```
|
|
112
285
|
|
|
113
|
-
|
|
286
|
+
Combine with InversifyJS `@optional()` for optional bindings:
|
|
287
|
+
|
|
288
|
+
```tsx
|
|
289
|
+
import { injectDependency, optional } from '@servicetitan/react-ioc';
|
|
290
|
+
|
|
291
|
+
class SubComponent extends React.Component {
|
|
292
|
+
@injectDependency(LOGGER_TOKEN)
|
|
293
|
+
@optional()
|
|
294
|
+
logger?: ILogger;
|
|
295
|
+
}
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
:::caution
|
|
299
|
+
`@injectDependency` reads the component's `context`. If you override the constructor and access an injected property in it, you must forward `context` to `super`:
|
|
300
|
+
|
|
301
|
+
```tsx
|
|
302
|
+
constructor(props: Props, context: any) {
|
|
303
|
+
super(props, context);
|
|
304
|
+
this.store.doSomething(); // safe
|
|
305
|
+
}
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
Without this, you will see `"Context doesn't exist on a target class."` at runtime.
|
|
309
|
+
:::
|
|
310
|
+
|
|
311
|
+
### `@inject`
|
|
312
|
+
|
|
313
|
+
Re-exported [from InversifyJS](https://inversify.io/docs/6.x/introduction/getting-started/). Attaches an explicit token to a constructor parameter or property so the container knows which binding to resolve.
|
|
314
|
+
|
|
315
|
+
:::tip
|
|
316
|
+
Only needed when the identifier isn't a class reference, for example a [`Symbol` token](#tokens) representing an interface. For class parameters, InversifyJS infers the token from the parameter type, so prefer omitting `@inject`.
|
|
317
|
+
:::
|
|
318
|
+
|
|
319
|
+
For a non-class token, the container needs the explicit identifier:
|
|
320
|
+
|
|
321
|
+
```tsx
|
|
322
|
+
import { inject, injectable } from '@servicetitan/react-ioc';
|
|
323
|
+
|
|
324
|
+
@injectable()
|
|
325
|
+
class Analytics {
|
|
326
|
+
constructor(@inject(LOGGER_TOKEN) private readonly logger: ILogger) {}
|
|
327
|
+
}
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
For a class token, the decorator is redundant:
|
|
331
|
+
|
|
332
|
+
```tsx
|
|
333
|
+
import { injectable } from '@servicetitan/react-ioc';
|
|
334
|
+
|
|
335
|
+
@injectable()
|
|
336
|
+
class ConsumerStore {
|
|
337
|
+
// No `@inject` needed: the parameter type `Store` is the token.
|
|
338
|
+
constructor(private readonly store: Store) {}
|
|
339
|
+
}
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
### `@optional`
|
|
343
|
+
|
|
344
|
+
Re-exported [from InversifyJS](https://inversify.io/docs/6.x/api/decorator/#optional). Marks a constructor parameter or property injection as optional, so the container will not throw when the token is unbound.
|
|
345
|
+
|
|
346
|
+
```tsx
|
|
347
|
+
import { inject, injectable, optional } from '@servicetitan/react-ioc';
|
|
348
|
+
|
|
349
|
+
@injectable()
|
|
350
|
+
class Analytics {
|
|
351
|
+
constructor(@inject(LOGGER_TOKEN) @optional() private readonly logger?: ILogger) {}
|
|
352
|
+
}
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
### `@unmanaged`
|
|
356
|
+
|
|
357
|
+
Re-exported [from InversifyJS](https://inversify.io/docs/6.x/api/decorator/#unmanaged). Marks a constructor parameter as not managed by the container. Useful when extending a base class whose constructor takes arguments the DI container should ignore.
|
|
358
|
+
|
|
359
|
+
```tsx
|
|
360
|
+
import { injectable, unmanaged } from '@servicetitan/react-ioc';
|
|
361
|
+
|
|
362
|
+
@injectable()
|
|
363
|
+
abstract class Base {
|
|
364
|
+
constructor(@unmanaged() protected readonly tag: string) {}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
@injectable()
|
|
368
|
+
class Concrete extends Base {
|
|
369
|
+
constructor(store: Store) {
|
|
370
|
+
super('concrete');
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
## Defining services
|
|
376
|
+
|
|
377
|
+
### `@injectable`
|
|
378
|
+
|
|
379
|
+
Re-exported [from InversifyJS](https://inversify.io/docs/6.x/api/decorator/#injectable). Marks a class as something the container is allowed to construct.
|
|
380
|
+
|
|
381
|
+
```tsx
|
|
382
|
+
import { injectable } from '@servicetitan/react-ioc';
|
|
383
|
+
|
|
384
|
+
@injectable()
|
|
385
|
+
class Store {
|
|
386
|
+
value = 123;
|
|
387
|
+
}
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
Required on every class you want to bind, including those that only use `@injectDependency` for property injection.
|
|
391
|
+
|
|
392
|
+
### `Store` {#store-lifecycle}
|
|
114
393
|
|
|
115
|
-
|
|
394
|
+
Abstract base class for stores that need async setup or cleanup. Already `@injectable`.
|
|
116
395
|
|
|
117
396
|
```tsx
|
|
397
|
+
import { Store } from '@servicetitan/react-ioc';
|
|
398
|
+
|
|
399
|
+
class UserStore extends Store {
|
|
400
|
+
user?: User;
|
|
401
|
+
|
|
402
|
+
async initialize() {
|
|
403
|
+
this.user = await fetchUser();
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
dispose() {
|
|
407
|
+
this.user = undefined;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
When a `Store` subclass is bound on a `<Provider>`:
|
|
413
|
+
|
|
414
|
+
1. The provider calls `initialize()` after binding.
|
|
415
|
+
2. If it returns a promise, the provider renders `loadingFallback` until the promise settles.
|
|
416
|
+
3. If the promise rejects (or `initialize()` throws), the provider renders `errorFallback` and rethrows asynchronously so global error handlers fire.
|
|
417
|
+
4. On unmount, `dispose()` runs after the container is unbound.
|
|
418
|
+
|
|
419
|
+
`initialize` and `dispose` are both optional.
|
|
420
|
+
|
|
421
|
+
### Tokens for interfaces
|
|
422
|
+
|
|
423
|
+
When you need to bind an interface rather than a concrete class, create a symbol token.
|
|
424
|
+
|
|
425
|
+
```tsx
|
|
426
|
+
import { symbolToken } from '@servicetitan/react-ioc';
|
|
427
|
+
|
|
118
428
|
interface ILogger {
|
|
119
429
|
error(e: Error): void;
|
|
120
430
|
}
|
|
@@ -122,9 +432,26 @@ interface ILogger {
|
|
|
122
432
|
const LOGGER_TOKEN = symbolToken<ILogger>('LOGGER_TOKEN');
|
|
123
433
|
```
|
|
124
434
|
|
|
125
|
-
####
|
|
435
|
+
#### `symbolToken<T>(key, global?)`
|
|
436
|
+
|
|
437
|
+
| Name | Type | Description |
|
|
438
|
+
| :------- | :-------- | :------------------------------------------------------------------------------------------------------ |
|
|
439
|
+
| `key` | `string` | Human-readable identifier. Appears in error messages. |
|
|
440
|
+
| `global` | `boolean` | (optional, default `true`) When `true`, uses `Symbol.for(key)` so two modules can share the same token. |
|
|
441
|
+
|
|
442
|
+
Use a token to provide and inject the interface:
|
|
126
443
|
|
|
127
444
|
```tsx
|
|
445
|
+
import { injectDependency, provide, symbolToken } from '@servicetitan/react-ioc';
|
|
446
|
+
|
|
447
|
+
// Implementation of the interface.
|
|
448
|
+
class Logger implements ILogger {
|
|
449
|
+
error(e: Error) {
|
|
450
|
+
console.log(e);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Consumer: asks for the token, gets whatever implementation is bound.
|
|
128
455
|
class ErrorBoundary extends React.Component {
|
|
129
456
|
state = { hasError: false };
|
|
130
457
|
|
|
@@ -137,24 +464,11 @@ class ErrorBoundary extends React.Component {
|
|
|
137
464
|
}
|
|
138
465
|
|
|
139
466
|
render() {
|
|
140
|
-
|
|
141
|
-
return <div>Something went wrong...</div>;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
return this.props.children;
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
#### Providing a service
|
|
150
|
-
|
|
151
|
-
```tsx
|
|
152
|
-
class Logger implements ILogger {
|
|
153
|
-
error(e: Error) {
|
|
154
|
-
console.log(e);
|
|
467
|
+
return this.state.hasError ? <div>Something went wrong...</div> : this.props.children;
|
|
155
468
|
}
|
|
156
469
|
}
|
|
157
470
|
|
|
471
|
+
// Provider: binds the token to a concrete implementation for the sub-tree.
|
|
158
472
|
const App = provide({ singletons: [{ provide: LOGGER_TOKEN, useClass: Logger }] })(() => (
|
|
159
473
|
<ErrorBoundary>
|
|
160
474
|
<Router />
|
|
@@ -162,44 +476,89 @@ const App = provide({ singletons: [{ provide: LOGGER_TOKEN, useClass: Logger }]
|
|
|
162
476
|
));
|
|
163
477
|
```
|
|
164
478
|
|
|
165
|
-
|
|
479
|
+
## Testing
|
|
480
|
+
|
|
481
|
+
For component tests, render under a `<Provider>` with mocks in place of the real bindings. For service-only tests with no React in the picture, build an InversifyJS `Container` directly.
|
|
482
|
+
|
|
483
|
+
### Overriding a binding for a test
|
|
166
484
|
|
|
167
|
-
|
|
485
|
+
Render the component under test inside a `<Provider>` that binds mocks.
|
|
168
486
|
|
|
169
487
|
```tsx
|
|
170
|
-
|
|
488
|
+
import { render, screen } from '@testing-library/react';
|
|
489
|
+
import { Provider } from '@servicetitan/react-ioc';
|
|
171
490
|
|
|
172
|
-
class
|
|
491
|
+
class UserStoreMock {
|
|
492
|
+
user = { id: 1, name: 'Test' };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
test('renders the user name', () => {
|
|
496
|
+
render(
|
|
497
|
+
<Provider singletons={[{ provide: UserStore, useClass: UserStoreMock }]}>
|
|
498
|
+
<UserBadge />
|
|
499
|
+
</Provider>
|
|
500
|
+
);
|
|
173
501
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
{ provide: SomeStore, useClass: SomeOtherStore, inherit: true },
|
|
177
|
-
{ provide: SomeOtherStore, inherit: true },
|
|
178
|
-
],
|
|
179
|
-
})(() => <div />);
|
|
502
|
+
expect(screen.getByText('Test')).toBeInTheDocument();
|
|
503
|
+
});
|
|
180
504
|
```
|
|
181
505
|
|
|
182
|
-
|
|
506
|
+
### Providing a constant value
|
|
183
507
|
|
|
184
|
-
|
|
508
|
+
`useValue` is the right tool for fixtures and config objects.
|
|
185
509
|
|
|
186
510
|
```tsx
|
|
187
|
-
import {
|
|
188
|
-
import { Store } from '@servicetitan/react-ioc';
|
|
511
|
+
import { Provider, symbolToken } from '@servicetitan/react-ioc';
|
|
189
512
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
513
|
+
render(
|
|
514
|
+
<Provider singletons={[{ provide: CONFIG_TOKEN, useValue: { apiUrl: '/test' } }]}>
|
|
515
|
+
<SettingsPanel />
|
|
516
|
+
</Provider>
|
|
517
|
+
);
|
|
518
|
+
```
|
|
194
519
|
|
|
195
|
-
|
|
196
|
-
// do some initialization
|
|
197
|
-
}
|
|
520
|
+
### Using `Container` directly
|
|
198
521
|
|
|
199
|
-
|
|
200
|
-
|
|
522
|
+
For unit tests of services that resolve other services, you can skip React entirely. Build a fresh `Container`, bind real and fake collaborators, resolve the subject, then exercise it.
|
|
523
|
+
|
|
524
|
+
Given an `Analytics` service that depends on `Logger`:
|
|
525
|
+
|
|
526
|
+
```tsx
|
|
527
|
+
import { injectable } from '@servicetitan/react-ioc';
|
|
528
|
+
|
|
529
|
+
@injectable()
|
|
530
|
+
class Analytics {
|
|
531
|
+
constructor(private readonly logger: Logger) {}
|
|
532
|
+
|
|
533
|
+
track(event: string) {
|
|
534
|
+
this.logger.info(event);
|
|
201
535
|
}
|
|
202
536
|
}
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
```tsx
|
|
540
|
+
import { Container } from '@servicetitan/react-ioc';
|
|
541
|
+
|
|
542
|
+
describe('Analytics', () => {
|
|
543
|
+
let container: Container;
|
|
544
|
+
let logger: Logger;
|
|
203
545
|
|
|
204
|
-
const
|
|
546
|
+
const subject = () => container.get(Analytics);
|
|
547
|
+
|
|
548
|
+
beforeEach(() => {
|
|
549
|
+
jest.clearAllMocks();
|
|
550
|
+
|
|
551
|
+
logger = { info: jest.fn() } as Logger;
|
|
552
|
+
|
|
553
|
+
container = new Container();
|
|
554
|
+
container.bind(Logger).toConstantValue(logger);
|
|
555
|
+
container.bind(Analytics).toSelf();
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
test('forwards tracked events to the logger', () => {
|
|
559
|
+
subject().track('signup');
|
|
560
|
+
|
|
561
|
+
expect(logger.info).toHaveBeenCalledWith('signup');
|
|
562
|
+
});
|
|
563
|
+
});
|
|
205
564
|
```
|
|
@@ -112,6 +112,56 @@ Renders,
|
|
|
112
112
|
<img src="@servicetitan/anvil2/assets/icons/material/round/expand_more.svg" />
|
|
113
113
|
```
|
|
114
114
|
|
|
115
|
+
## Debugging tests
|
|
116
|
+
|
|
117
|
+
You can debug tests in your IDE while still running them through `startup test`.
|
|
118
|
+
|
|
119
|
+
### VS Code
|
|
120
|
+
|
|
121
|
+
Add a Node launch configuration that runs the `startup` binary with the `test` command. The same configuration works for both Jest and Vitest.
|
|
122
|
+
|
|
123
|
+
```json title=".vscode/launch.json"
|
|
124
|
+
{
|
|
125
|
+
"version": "0.2.0",
|
|
126
|
+
"configurations": [
|
|
127
|
+
{
|
|
128
|
+
"type": "node",
|
|
129
|
+
"request": "launch",
|
|
130
|
+
"name": "Test All",
|
|
131
|
+
"program": "${workspaceFolder}/node_modules/.bin/startup",
|
|
132
|
+
"args": ["test", "--runInBand"],
|
|
133
|
+
"console": "integratedTerminal",
|
|
134
|
+
"internalConsoleOptions": "neverOpen",
|
|
135
|
+
"windows": {
|
|
136
|
+
"program": "${workspaceFolder}/node_modules/@servicetitan/startup/dist/cli"
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
"type": "node",
|
|
141
|
+
"request": "launch",
|
|
142
|
+
"name": "Test Current File",
|
|
143
|
+
"program": "${workspaceFolder}/node_modules/.bin/startup",
|
|
144
|
+
"args": ["test", "${file}", "--runInBand"],
|
|
145
|
+
"console": "integratedTerminal",
|
|
146
|
+
"internalConsoleOptions": "neverOpen",
|
|
147
|
+
"windows": {
|
|
148
|
+
"program": "${workspaceFolder}/node_modules/@servicetitan/startup/dist/cli"
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
]
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
:::note
|
|
156
|
+
On Windows, `node_modules/.bin/startup` is a wrapper script generated by npm, not a JavaScript file. Node's launch configuration cannot execute it directly, so the `windows` override points at the underlying JavaScript entry instead.
|
|
157
|
+
:::
|
|
158
|
+
|
|
159
|
+
To debug Vitest tests, add `--runner vitest` to `args` and replace `--runInBand` with `--no-file-parallelism`. See [Vitest's debugging guide](https://vitest.dev/guide/debugging.html) for more options.
|
|
160
|
+
|
|
161
|
+
### WebStorm / Rider
|
|
162
|
+
|
|
163
|
+
For Jest, install [`@servicetitan/startup-jest`](/docs/frontend/anvil-uikit-contrib/startup-jest) and set it as the Jest package in your Run/Debug Configuration. There is no equivalent wrapper for Vitest.
|
|
164
|
+
|
|
115
165
|
## Configuration
|
|
116
166
|
|
|
117
167
|
- [Jest](./jest)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@servicetitan/docs-uikit",
|
|
3
|
-
"version": "36.
|
|
3
|
+
"version": "36.3.1",
|
|
4
4
|
"description": "Documentation content for Uikit packages published at docs.st.dev",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -16,5 +16,5 @@
|
|
|
16
16
|
"cli": {
|
|
17
17
|
"webpack": false
|
|
18
18
|
},
|
|
19
|
-
"gitHead": "
|
|
19
|
+
"gitHead": "93a049ba1e5cb737afb7bc95c06020736bc61a38"
|
|
20
20
|
}
|