@adimm/x-injection-reactjs 0.2.2 → 0.2.4
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 +527 -567
- package/dist/index.cjs +30 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +29 -25
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.cjs
CHANGED
|
@@ -9,26 +9,26 @@ var e, t = Object.create, o = Object.defineProperty, r = Object.getOwnPropertyDe
|
|
|
9
9
|
enumerable: !(s = r(t, a)) || s.enumerable
|
|
10
10
|
});
|
|
11
11
|
return e;
|
|
12
|
-
},
|
|
12
|
+
}, d = (e, r, n) => (n = null != e ? t(i(e)) : {}, a(!r && e && e.__esModule ? n : o(n, "default", {
|
|
13
13
|
value: e,
|
|
14
14
|
enumerable: !0
|
|
15
|
-
}), e)),
|
|
15
|
+
}), e)), c = {};
|
|
16
16
|
|
|
17
17
|
((e, t) => {
|
|
18
18
|
for (var r in t) o(e, r, {
|
|
19
19
|
get: t[r],
|
|
20
20
|
enumerable: !0
|
|
21
21
|
});
|
|
22
|
-
})(
|
|
23
|
-
ComponentProviderModule: () =>
|
|
22
|
+
})(c, {
|
|
23
|
+
ComponentProviderModule: () => C,
|
|
24
24
|
ProvideModule: () => q,
|
|
25
25
|
REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT: () => p,
|
|
26
|
-
hookFactory: () =>
|
|
26
|
+
hookFactory: () => R,
|
|
27
27
|
provideModuleToComponent: () => I,
|
|
28
28
|
useComponentModule: () => f,
|
|
29
29
|
useInject: () => v,
|
|
30
30
|
useInjectMany: () => M
|
|
31
|
-
}), module.exports = (e =
|
|
31
|
+
}), module.exports = (e = c, a(o({}, "__esModule", {
|
|
32
32
|
value: !0
|
|
33
33
|
}), e));
|
|
34
34
|
|
|
@@ -48,15 +48,15 @@ function M(...e) {
|
|
|
48
48
|
|
|
49
49
|
s(f, "useComponentModule"), s(v, "useInject"), s(M, "useInjectMany");
|
|
50
50
|
|
|
51
|
-
var
|
|
51
|
+
var h = require("@adimm/x-injection"), C = class e extends h.ProviderModule {
|
|
52
52
|
static {
|
|
53
53
|
s(this, "ComponentProviderModule");
|
|
54
54
|
}
|
|
55
55
|
_initializedFromComponent;
|
|
56
56
|
constructor(e) {
|
|
57
|
-
super(
|
|
57
|
+
super(h.ProviderModuleHelpers.buildInternalConstructorParams({
|
|
58
58
|
...e,
|
|
59
|
-
defaultScope: e.defaultScope ??
|
|
59
|
+
defaultScope: e.defaultScope ?? h.InjectionScope.Singleton,
|
|
60
60
|
identifier: Symbol(`Component${e.identifier.description}`)
|
|
61
61
|
})), this._initializedFromComponent = !1;
|
|
62
62
|
}
|
|
@@ -66,8 +66,9 @@ var C = require("@adimm/x-injection"), h = class e extends C.ProviderModule {
|
|
|
66
66
|
clone(t) {
|
|
67
67
|
let o = [ ...this.providers ];
|
|
68
68
|
t?.providersMap && (o = o.map((e => t.providersMap(e, this))));
|
|
69
|
-
const r = new e(
|
|
69
|
+
const r = new e(h.ProviderModuleHelpers.buildInternalConstructorParams({
|
|
70
70
|
isAppModule: this.isAppModule,
|
|
71
|
+
markAsGlobal: this.isMarkedAsGlobal,
|
|
71
72
|
identifier: Symbol(this.identifier.description.replace("Component", "")),
|
|
72
73
|
defaultScope: this.defaultScope.native,
|
|
73
74
|
dynamicExports: this.dynamicExports,
|
|
@@ -89,25 +90,28 @@ var C = require("@adimm/x-injection"), h = class e extends C.ProviderModule {
|
|
|
89
90
|
return e.identifier = Symbol(`Contextualized${e.identifier.description}`), e._initializedFromComponent = !0,
|
|
90
91
|
e;
|
|
91
92
|
}
|
|
92
|
-
}, y =
|
|
93
|
+
}, y = d(require("react"), 1), P = require("react"), b = require("react");
|
|
93
94
|
|
|
94
|
-
function
|
|
95
|
-
const t = (0,
|
|
96
|
-
|
|
97
|
-
o.current && (r.current = !0), (0,
|
|
95
|
+
function j(e) {
|
|
96
|
+
const t = (0, b.useRef)(void 0), o = (0, b.useRef)(!1), r = (0, b.useRef)(!1), [, n] = (0,
|
|
97
|
+
b.useState)(0);
|
|
98
|
+
o.current && (r.current = !0), (0, b.useEffect)((() => (o.current || (t.current = e(),
|
|
98
99
|
o.current = !0), n((e => e + 1)), () => {
|
|
99
100
|
r.current && t.current?.();
|
|
100
101
|
})), []);
|
|
101
102
|
}
|
|
102
103
|
|
|
103
|
-
function
|
|
104
|
-
const o = (0, P.useMemo)((() =>
|
|
105
|
-
|
|
104
|
+
function _(e, t) {
|
|
105
|
+
const o = (0, P.useMemo)((() => {
|
|
106
|
+
const o = (t ?? e).toNaked();
|
|
107
|
+
return o.isMarkedAsGlobal ? o : o._createContextualizedComponentInstance();
|
|
108
|
+
}), [ e, t ]);
|
|
109
|
+
return j((() => () => {
|
|
106
110
|
o.dispose();
|
|
107
111
|
})), o;
|
|
108
112
|
}
|
|
109
113
|
|
|
110
|
-
s(
|
|
114
|
+
s(j, "useEffectOnce"), s(_, "useContextualizedModule");
|
|
111
115
|
|
|
112
116
|
var x = require("@adimm/x-injection");
|
|
113
117
|
|
|
@@ -125,7 +129,7 @@ var O = y.default.memo(g);
|
|
|
125
129
|
|
|
126
130
|
function I(e, t) {
|
|
127
131
|
return o => {
|
|
128
|
-
const r =
|
|
132
|
+
const r = _(e, o.module);
|
|
129
133
|
return y.default.createElement(p.Provider, {
|
|
130
134
|
value: r
|
|
131
135
|
}, y.default.createElement(O, {
|
|
@@ -142,10 +146,10 @@ function g({module: e, component: t, componentProps: o}) {
|
|
|
142
146
|
|
|
143
147
|
s(I, "provideModuleToComponent"), s(g, "_ComponentRenderer");
|
|
144
148
|
|
|
145
|
-
var F =
|
|
149
|
+
var F = d(require("react"), 1);
|
|
146
150
|
|
|
147
151
|
function q({module: e, children: t}) {
|
|
148
|
-
const o = t.props ?? {}, r =
|
|
152
|
+
const o = t.props ?? {}, r = _(e, o.module), n = (0, F.useMemo)((() => F.default.cloneElement(t, E(t, o, r))), [ o, r ]);
|
|
149
153
|
return F.default.createElement(p.Provider, {
|
|
150
154
|
value: r
|
|
151
155
|
}, n);
|
|
@@ -153,17 +157,17 @@ function q({module: e, children: t}) {
|
|
|
153
157
|
|
|
154
158
|
s(q, "ProvideModule");
|
|
155
159
|
|
|
156
|
-
var z = require("react"), S = require("@adimm/x-injection"),
|
|
160
|
+
var z = require("react"), S = require("@adimm/x-injection"), k = class e extends S.InjectionProviderModuleError {
|
|
157
161
|
static {
|
|
158
162
|
s(this, "InjectionHookFactoryError");
|
|
159
163
|
}
|
|
160
164
|
name=e.name;
|
|
161
165
|
};
|
|
162
166
|
|
|
163
|
-
function
|
|
167
|
+
function R({use: e, inject: t}) {
|
|
164
168
|
return o => {
|
|
165
169
|
const r = f(), n = (0, z.useMemo)((() => {
|
|
166
|
-
if (0 === t.length) throw new
|
|
170
|
+
if (0 === t.length) throw new k(r, "The 'deps' property array is missing!");
|
|
167
171
|
return r.getMany(...t);
|
|
168
172
|
}), [ t ]);
|
|
169
173
|
return e({
|
|
@@ -173,4 +177,4 @@ function w({use: e, inject: t}) {
|
|
|
173
177
|
};
|
|
174
178
|
}
|
|
175
179
|
|
|
176
|
-
s(
|
|
180
|
+
s(R, "hookFactory");//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/core/react-context.ts","../src/core/hooks/use-component-module.ts","../src/core/hooks/use-inject.ts","../src/core/hooks/use-inject-many.ts","../src/core/component-provider-module.ts","../src/core/provide-module/provide-module.arrow-function.tsx","../src/helpers/hooks/use-contextualized-module.ts","../src/helpers/hooks/use-effect-once.ts","../src/helpers/forward-props-with-module.ts","../src/core/provide-module/provide-module.provider.tsx","../src/core/hook-factory.ts","../src/errors/hook-factory.ts"],"sourcesContent":["export * from './core';\nexport type * from './types';\n","import { AppModule } from '@adimm/x-injection';\nimport { createContext } from 'react';\n\nimport type { IComponentProviderModule } from '../types';\n\nexport const REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT = createContext<IComponentProviderModule>(AppModule as any);\n","import { useContext } from 'react';\n\nimport type { IComponentProviderModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\n/** Can be used to retrieve the {@link IComponentProviderModule} from the current context. */\nexport function useComponentModule(): IComponentProviderModule {\n return useContext(REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT);\n}\n","import type { ProviderToken } from '@adimm/x-injection';\n\nimport { useComponentModule } from './use-component-module';\n\n/**\n * Low-level hook which can be used to resolve a single dependency from the current\n * context module.\n *\n * **Note:** _In order to better modularize your code-base, you should strive to create custom hooks by using the_\n * _`hookFactory` method to compose a custom hook._\n *\n * @param provider The {@link ProviderToken}.\n * @param options See {@link UseInjectOptions}.\n * @returns The resolved {@link T | dependency}.\n */\nexport function useInject<T>(provider: ProviderToken<T>, options?: UseInjectOptions): T {\n const componentModule = useComponentModule();\n\n return componentModule.get(provider, options?.isOptional);\n}\n\nexport type UseInjectOptions = {\n /** When set to `false` _(default)_ an exception will be thrown when the `providerOrIdentifier` isn't bound. */\n isOptional?: boolean;\n};\n","import type { ProviderModuleGetManyParam, ProviderModuleGetManySignature, ProviderToken } from '@adimm/x-injection';\n\nimport { useComponentModule } from './use-component-module';\n\n/**\n * Low-level hook which can be used to resolve multiple dependencies at once from the current\n * context module.\n *\n * **Note:** _In order to better modularize your code-base, you should strive to create custom hooks by using the_\n * _`hookFactory` method to compose a custom hook._\n *\n * @param deps Either one or more {@link ProviderToken}.\n * @returns Tuple containing the {@link D | dependencies}.\n */\nexport function useInjectMany<D extends (ProviderModuleGetManyParam<any> | ProviderToken)[]>(\n ...deps: D | unknown[]\n): ProviderModuleGetManySignature<D> {\n const componentModule = useComponentModule();\n\n return componentModule.getMany(...deps);\n}\n","import {\n InjectionScope,\n ProviderModule,\n ProviderModuleHelpers,\n type CloneParams,\n type IProviderModuleNaked,\n type ProviderModuleOptions,\n} from '@adimm/x-injection';\n\nimport type { IComponentProviderModule, IComponentProviderModuleNaked } from '../types';\n\n/** A superset of the {@link ProviderModule} used to integrate within a `React` component. */\nexport class ComponentProviderModule extends ProviderModule implements IComponentProviderModule {\n protected readonly _initializedFromComponent: IComponentProviderModuleNaked['_initializedFromComponent'];\n\n constructor(options: ProviderModuleOptions) {\n super(\n ProviderModuleHelpers.buildInternalConstructorParams({\n ...options,\n defaultScope: options.defaultScope ?? InjectionScope.Singleton,\n identifier: Symbol(`Component${options.identifier.description}`),\n })\n );\n\n this._initializedFromComponent = false;\n }\n\n override toNaked(): IComponentProviderModuleNaked & IProviderModuleNaked {\n return this as any;\n }\n\n /* istanbul ignore next */\n override clone(options?: CloneParams): IComponentProviderModule {\n let providers = [...this.providers];\n\n if (options?.providersMap) {\n providers = providers.map((provider) => options.providersMap!(provider, this));\n }\n\n const clonedModule = new ComponentProviderModule(\n ProviderModuleHelpers.buildInternalConstructorParams({\n isAppModule: this.isAppModule,\n identifier: Symbol(this.identifier.description!.replace('Component', '')),\n defaultScope: this.defaultScope.native,\n dynamicExports: this.dynamicExports,\n onReady: this.onReady,\n onDispose: this.onDispose,\n importedProvidersMap: options?.importedProvidersMap,\n imports: [...this.imports],\n providers,\n exports: [...this.exports],\n })\n );\n\n //@ts-expect-error Read-only method.\n clonedModule._initializedFromComponent = this._initializedFromComponent;\n\n return clonedModule;\n }\n\n /* istanbul ignore next */\n dispose(): void {\n this._dispose();\n }\n\n //#region IComponentProviderModuleNaked methods\n\n /**\n * **Publicly visible when the instance is casted to {@link IComponentProviderModuleNaked}.**\n *\n * See {@link IComponentProviderModuleNaked._createContextualizedComponentInstance}.\n */\n protected _createContextualizedComponentInstance(): IComponentProviderModule {\n if (this._initializedFromComponent) return this;\n\n const ctxModule = this.clone().toNaked();\n\n //@ts-expect-error Read-only property\n ctxModule.identifier = Symbol(`Contextualized${ctxModule.identifier.description}`);\n ctxModule._initializedFromComponent = true;\n\n return ctxModule;\n }\n\n //#endregion\n}\n","import React from 'react';\n\nimport { forwardPropsWithModule, useContextualizedModule } from '../../helpers';\nimport type { IComponentProviderModule, PropsWithModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\nconst ComponentRenderer = React.memo(_ComponentRenderer);\n\n/**\n * Can be used to easily provide a {@link module} to any component.\n *\n * @example\n * ```tsx\n * interface MyComponentProps {\n * firstName: string;\n * lastName: string;\n * }\n *\n * export const MyComponent = provideModuleToComponent(\n * MyComponentModule,\n * ({ firstName, lastName }: MyComponentProps) => {\n * const service = useInject(MyComponentService);\n *\n * return <h1>Hello {service.computeUserName(firstName, lastName)}!</h1>\n * }\n * );\n *\n * function App() {\n * return <MyComponent firstName={'John'} lastName={'Doe'} />;\n * }\n * ```\n *\n * @param module The {@link IComponentProviderModule | Module} which should be consumed by the {@link component}.\n * @returns The provided {@link toComponent | Component}.\n */\nexport function provideModuleToComponent<\n P extends Record<string, any>,\n C extends ReactElementWithProviderModule<P> = ReactElementWithProviderModule<P>,\n>(module: IComponentProviderModule, component: ReactElementWithProviderModule<P>): C {\n return ((componentProps: PropsWithModule<P>) => {\n const moduleCtx = useContextualizedModule(module, componentProps.module);\n\n return (\n <REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider value={moduleCtx}>\n <ComponentRenderer module={moduleCtx} componentProps={componentProps} component={component as any} />\n </REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider>\n );\n }) as any;\n}\n\nfunction _ComponentRenderer<P extends Record<string, any>>({\n module,\n component,\n componentProps,\n}: {\n module: IComponentProviderModule;\n component: ReactElementWithProviderModule<P>;\n componentProps: P;\n}) {\n return <>{component(forwardPropsWithModule(component, componentProps, module))}</>;\n}\n\nexport type ReactElementWithProviderModule<P extends Record<string, any>> = (p: PropsWithModule<P>) => React.ReactNode;\n","import { useMemo } from 'react';\n\nimport type { IComponentProviderModule } from '../../types';\nimport { useEffectOnce } from './use-effect-once';\n\nexport function useContextualizedModule(\n originalModule: IComponentProviderModule,\n forwardedModule?: IComponentProviderModule\n): IComponentProviderModule {\n const ctxModule = useMemo(() => {\n return (forwardedModule ?? originalModule).toNaked()._createContextualizedComponentInstance();\n }, [originalModule, forwardedModule]);\n\n useEffectOnce(() => {\n return () => {\n ctxModule.dispose();\n };\n });\n\n return ctxModule;\n}\n","import { useEffect, useRef, useState } from 'react';\n\n// Credits: https://stackoverflow.com/a/74000921\n\n/** Custom {@link useEffect} hook which will be run once. _(In `StrictMode` as well)_ */\nexport function useEffectOnce(effect: () => React.EffectCallback) {\n const destroyFunc = useRef<React.EffectCallback>(undefined);\n const effectCalled = useRef(false);\n const renderAfterCalled = useRef(false);\n const [, forceRerender] = useState(0);\n\n if (effectCalled.current) renderAfterCalled.current = true;\n\n useEffect(() => {\n // only execute the effect first time around\n if (!effectCalled.current) {\n destroyFunc.current = effect();\n effectCalled.current = true;\n }\n\n // this forces one render after the effect is run\n forceRerender((x) => x + 1);\n\n return () => {\n // if the comp didn't render since the useEffect was called,\n // we know it's the dummy React cycle\n if (!renderAfterCalled.current) return;\n\n destroyFunc.current?.();\n };\n }, []);\n}\n","import { isFunction } from '@adimm/x-injection';\n\nimport type { ReactElementWithProviderModule } from '../core';\nimport type { IComponentProviderModule, PropsWithModule } from '../types';\n\nexport function forwardPropsWithModule<P extends Record<string, any>>(\n component: ReactElementWithProviderModule<P> | React.ReactElement,\n props: Record<string, any>,\n module: IComponentProviderModule\n): PropsWithModule<P> {\n const isReactElement = typeof component === 'object' && 'type' in component;\n\n const result = {\n ...props,\n } as any;\n\n if ((isReactElement && isFunction(component.type)) || isFunction(component)) {\n result['module'] = module;\n }\n\n return result;\n}\n","import React, { useMemo } from 'react';\n\nimport { forwardPropsWithModule, useContextualizedModule } from '../../helpers';\nimport type { IComponentProviderModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\n/**\n * Can be used to easily provide a {@link module} to any component.\n *\n * @example\n * ```tsx\n * interface MyComponentProps {\n * firstName: string;\n * lastName: string;\n * }\n *\n * function MyComponent({ firstName, lastName }: MyComponentProps) {\n * const service = useInject(MyComponentService);\n *\n * return <h1>Hello {service.computeUserName(firstName, lastName)}!</h1>\n * }\n *\n * function App() {\n * return (\n * <ProvideModule module={MyComponentModule}>\n * <MyComponent firstName={'John'} lastName={'Doe'} />\n * </ProvideModule>\n * );\n * }\n * ```\n *\n * @param param0 See {@link ProvideModuleFunctionParams}.\n * @returns The provided {@link toComponent | Component}.\n */\nexport function ProvideModule({ module, children }: ProvideModuleFunctionParams) {\n /* istanbul ignore next */\n const componentProps = (children.props ?? {}) as any;\n const moduleCtx = useContextualizedModule(module, componentProps.module);\n const component = useMemo(\n () => React.cloneElement(children, forwardPropsWithModule(children, componentProps, moduleCtx)),\n [componentProps, moduleCtx]\n );\n\n return (\n <REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider value={moduleCtx}>\n {component}\n </REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider>\n );\n}\n\nexport interface ProvideModuleFunctionParams {\n /** The {@link IComponentProviderModule | Module} which should be consumed by the {@link children | component}. */\n module: IComponentProviderModule;\n\n children: React.ReactElement;\n}\n","import type { ProviderToken } from '@adimm/x-injection';\nimport { useMemo } from 'react';\n\nimport { InjectionHookFactoryError } from '../errors';\nimport { useComponentModule } from './hooks';\n\nexport function hookFactory<P extends HookParams, D extends any[], T>({\n use: hook,\n inject,\n}: HookFactoryParams<P, D, T>): (p: P) => T {\n return (p: P) => {\n const componentModule = useComponentModule();\n\n const deps = useMemo(() => {\n if (inject.length === 0) {\n throw new InjectionHookFactoryError(componentModule, `The 'deps' property array is missing!`);\n }\n\n return componentModule.getMany(...inject);\n }, [inject]);\n\n return hook({ ...p, deps: [...deps] } as any);\n };\n}\n\nexport interface HookFactoryParams<P extends HookParams, D extends any[], T> {\n use: HookWithProviderModuleDependencies<P, D, T>;\n inject: ProviderToken[];\n}\n\nexport type HookWithProviderModuleDependencies<P extends HookParams, D extends any[], T> = (p: HookWithDeps<P, D>) => T;\n\nexport type HookWithDeps<P extends HookParams, D extends any[]> = P & {\n /** Array containing the resolved dependencies from the component context. */\n deps: D;\n};\n\ntype HookParams = Record<string, any> | void;\n","import { InjectionProviderModuleError } from '@adimm/x-injection';\n\nexport class InjectionHookFactoryError extends InjectionProviderModuleError {\n override name = InjectionHookFactoryError.name;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;ACAA,yBAA0B;AAC1B,mBAA8B;AAIvB,IAAMA,gDAA4CC,4BAAwCC,4BAAAA;;;ACLjG,IAAAC,gBAA2B;AAMpB,SAASC,qBAAAA;AACd,aAAOC,0BAAWC,yCAAAA;AACpB;AAFgBF;;;ACST,SAASG,UAAaC,UAA4BC,SAA0B;AACjF,QAAMC,kBAAkBC,mBAAAA;AAExB,SAAOD,gBAAgBE,IAAIJ,UAAUC,SAASI,UAAAA;AAChD;AAJgBN;;;ACDT,SAASO,iBACXC,MAAmB;AAEtB,QAAMC,kBAAkBC,mBAAAA;AAExB,SAAOD,gBAAgBE,QAAO,GAAIH,IAAAA;AACpC;AANgBD;;;ACdhB,IAAAK,sBAOO;AAKA,IAAMC,0BAAN,MAAMA,iCAAgCC,mCAAAA;EAZ7C,OAY6CA;;;EACxBC;EAEnBC,YAAYC,SAAgC;AAC1C,UACEC,0CAAsBC,+BAA+B;MACnD,GAAGF;MACHG,cAAcH,QAAQG,gBAAgBC,mCAAeC;MACrDC,YAAYC,OAAO,YAAYP,QAAQM,WAAWE,WAAW,EAAE;IACjE,CAAA,CAAA;AAGF,SAAKV,4BAA4B;EACnC;EAESW,UAAgE;AACvE,WAAO;EACT;;EAGSC,MAAMV,SAAiD;AAC9D,QAAIW,YAAY;SAAI,KAAKA;;AAEzB,QAAIX,SAASY,cAAc;AACzBD,kBAAYA,UAAUE,IAAI,CAACC,aAAad,QAAQY,aAAcE,UAAU,IAAI,CAAA;IAC9E;AAEA,UAAMC,eAAe,IAAInB,yBACvBK,0CAAsBC,+B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AMC,8BAAAA,QAAMC,aAAaR,UAAUS,uBAAuBT,UAAUC,gBAAgBE,SAAAA,CAAAA,GACpF;IAACF;IAAgBE;GAAU;AAG7B,SACE,8BAAAI,QAAA,cAACG,0CAA0CC,UAAQ;IAACC,OAAOT;KACxDE,SAAAA;AAGP;AAdgBP;;;ACjChB,IAAAe,gBAAwB;;;ACDxB,IAAAC,sBAA6C;AAEtC,IAAMC,4BAAN,MAAMA,mCAAkCC,iDAAAA;EAF/C,OAE+CA;;;EACpCC,OAAOF,2BAA0BE;AAC5C;;;ADEO,SAASC,YAAsD,EACpEC,KAAKC,MACLC,OAAM,GACqB;AAC3B,SAAO,CAACC,MAAAA;AACN,UAAMC,kBAAkBC,mBAAAA;AAExB,UAAMC,WAAOC,uBAAQ,MAAA;AACnB,UAAIL,OAAOM,WAAW,GAAG;AACvB,cAAM,IAAIC,0BAA0BL,iBAAiB,uCAAuC;MAC9F;AAEA,aAAOA,gBAAgBM,QAAO,GAAIR,MAAAA;IACpC,GAAG;MAACA;KAAO;AAEX,WAAOD,KAAK;MAAE,GAAGE;MAAGG,MAAM;WAAIA;;IAAM,CAAA;EACtC;AACF;AAjBgBP;","names":["REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","createContext","AppModule","import_react","useComponentModule","useContext","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","useInject","provider","options","componentModule","useComponentModule","get","isOptional","useInjectMany","deps","componentModule","useComponentModule","getMany","import_x_injection","ComponentProviderModule","ProviderModule","_initializedFromComponent","constructor","options","ProviderModuleHelpers","buildInternalConstructorParams","defaultScope","InjectionScope","Singleton","identifier","Symbol","description","toNaked","clone","providers","providersMap","map","provider","clonedModule","isAppModule","replace","native","dynamicExports","onReady","onDispose","importedProvidersMap","imports","exports","dispose","_dispose","_createContextualizedComponentInstance","ctxModule","import_react","import_react","import_react","useEffectOnce","effect","destroyFunc","useRef","undefined","effectCalled","renderAfterCalled","forceRerender","useState","current","useEffect","x","useContextualizedModule","originalModule","forwardedModule","ctxModule","useMemo","toNaked","_createContextualizedComponentInstance","useEffectOnce","dispose","import_x_injection","forwardPropsWithModule","component","props","module","isReactElement","result","isFunction","type","ComponentRenderer","React","memo","_ComponentRenderer","provideModuleToComponent","module","component","componentProps","moduleCtx","useContextualizedModule","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","Provider","value","forwardPropsWithModule","import_react","ProvideModule","module","children","componentProps","props","moduleCtx","useContextualizedModule","component","useMemo","React","cloneElement","forwardPropsWithModule","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","Provider","value","import_react","import_x_injection","InjectionHookFactoryError","InjectionProviderModuleError","name","hookFactory","use","hook","inject","p","componentModule","useComponentModule","deps","useMemo","length","InjectionHookFactoryError","getMany"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/core/react-context.ts","../src/core/hooks/use-component-module.ts","../src/core/hooks/use-inject.ts","../src/core/hooks/use-inject-many.ts","../src/core/component-provider-module.ts","../src/core/provide-module/provide-module.arrow-function.tsx","../src/helpers/hooks/use-contextualized-module.ts","../src/helpers/hooks/use-effect-once.ts","../src/helpers/forward-props-with-module.ts","../src/core/provide-module/provide-module.provider.tsx","../src/core/hook-factory.ts","../src/errors/hook-factory.ts"],"sourcesContent":["export * from './core';\nexport type * from './types';\n","import { AppModule } from '@adimm/x-injection';\nimport { createContext } from 'react';\n\nimport type { IComponentProviderModule } from '../types';\n\nexport const REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT = createContext<IComponentProviderModule>(AppModule as any);\n","import { useContext } from 'react';\n\nimport type { IComponentProviderModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\n/** Can be used to retrieve the {@link IComponentProviderModule} from the current context. */\nexport function useComponentModule(): IComponentProviderModule {\n return useContext(REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT);\n}\n","import type { ProviderToken } from '@adimm/x-injection';\n\nimport { useComponentModule } from './use-component-module';\n\n/**\n * Low-level hook which can be used to resolve a single dependency from the current\n * context module.\n *\n * **Note:** _In order to better modularize your code-base, you should strive to create custom hooks by using the_\n * _`hookFactory` method to compose a custom hook._\n *\n * @param provider The {@link ProviderToken}.\n * @param options See {@link UseInjectOptions}.\n * @returns The resolved {@link T | dependency}.\n */\nexport function useInject<T>(provider: ProviderToken<T>, options?: UseInjectOptions): T {\n const componentModule = useComponentModule();\n\n return componentModule.get(provider, options?.isOptional);\n}\n\nexport type UseInjectOptions = {\n /** When set to `false` _(default)_ an exception will be thrown when the `providerOrIdentifier` isn't bound. */\n isOptional?: boolean;\n};\n","import type { ProviderModuleGetManyParam, ProviderModuleGetManySignature, ProviderToken } from '@adimm/x-injection';\n\nimport { useComponentModule } from './use-component-module';\n\n/**\n * Low-level hook which can be used to resolve multiple dependencies at once from the current\n * context module.\n *\n * **Note:** _In order to better modularize your code-base, you should strive to create custom hooks by using the_\n * _`hookFactory` method to compose a custom hook._\n *\n * @param deps Either one or more {@link ProviderToken}.\n * @returns Tuple containing the {@link D | dependencies}.\n */\nexport function useInjectMany<D extends (ProviderModuleGetManyParam<any> | ProviderToken)[]>(\n ...deps: D | unknown[]\n): ProviderModuleGetManySignature<D> {\n const componentModule = useComponentModule();\n\n return componentModule.getMany(...deps);\n}\n","import {\n InjectionScope,\n ProviderModule,\n ProviderModuleHelpers,\n type CloneParams,\n type IProviderModuleNaked,\n type ProviderModuleOptions,\n} from '@adimm/x-injection';\n\nimport type { IComponentProviderModule, IComponentProviderModuleNaked } from '../types';\n\n/** A superset of the {@link ProviderModule} used to integrate within a `React` component. */\nexport class ComponentProviderModule extends ProviderModule implements IComponentProviderModule {\n protected readonly _initializedFromComponent: IComponentProviderModuleNaked['_initializedFromComponent'];\n\n constructor(options: ProviderModuleOptions) {\n super(\n ProviderModuleHelpers.buildInternalConstructorParams({\n ...options,\n defaultScope: options.defaultScope ?? InjectionScope.Singleton,\n identifier: Symbol(`Component${options.identifier.description}`),\n })\n );\n\n this._initializedFromComponent = false;\n }\n\n override toNaked(): IComponentProviderModuleNaked & IProviderModuleNaked {\n return this as any;\n }\n\n /* istanbul ignore next */\n override clone(options?: CloneParams): IComponentProviderModule {\n let providers = [...this.providers];\n\n if (options?.providersMap) {\n providers = providers.map((provider) => options.providersMap!(provider, this));\n }\n\n const clonedModule = new ComponentProviderModule(\n ProviderModuleHelpers.buildInternalConstructorParams({\n isAppModule: this.isAppModule,\n markAsGlobal: this.isMarkedAsGlobal,\n identifier: Symbol(this.identifier.description!.replace('Component', '')),\n defaultScope: this.defaultScope.native,\n dynamicExports: this.dynamicExports,\n onReady: this.onReady,\n onDispose: this.onDispose,\n importedProvidersMap: options?.importedProvidersMap,\n imports: [...this.imports],\n providers,\n exports: [...this.exports],\n })\n );\n\n //@ts-expect-error Read-only method.\n clonedModule._initializedFromComponent = this._initializedFromComponent;\n\n return clonedModule;\n }\n\n /* istanbul ignore next */\n dispose(): void {\n this._dispose();\n }\n\n //#region IComponentProviderModuleNaked methods\n\n /**\n * **Publicly visible when the instance is casted to {@link IComponentProviderModuleNaked}.**\n *\n * See {@link IComponentProviderModuleNaked._createContextualizedComponentInstance}.\n */\n protected _createContextualizedComponentInstance(): IComponentProviderModule {\n if (this._initializedFromComponent) return this;\n\n const ctxModule = this.clone().toNaked();\n\n //@ts-expect-error Read-only property\n ctxModule.identifier = Symbol(`Contextualized${ctxModule.identifier.description}`);\n ctxModule._initializedFromComponent = true;\n\n return ctxModule;\n }\n\n //#endregion\n}\n","import React from 'react';\n\nimport { forwardPropsWithModule, useContextualizedModule } from '../../helpers';\nimport type { IComponentProviderModule, PropsWithModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\nconst ComponentRenderer = React.memo(_ComponentRenderer);\n\n/**\n * Can be used to easily provide a {@link module} to any component.\n *\n * @example\n * ```tsx\n * interface MyComponentProps {\n * firstName: string;\n * lastName: string;\n * }\n *\n * export const MyComponent = provideModuleToComponent(\n * MyComponentModule,\n * ({ firstName, lastName }: MyComponentProps) => {\n * const service = useInject(MyComponentService);\n *\n * return <h1>Hello {service.computeUserName(firstName, lastName)}!</h1>\n * }\n * );\n *\n * function App() {\n * return <MyComponent firstName={'John'} lastName={'Doe'} />;\n * }\n * ```\n *\n * @param module The {@link IComponentProviderModule | Module} which should be consumed by the {@link component}.\n * @returns The provided {@link toComponent | Component}.\n */\nexport function provideModuleToComponent<\n P extends Record<string, any>,\n C extends ReactElementWithProviderModule<P> = ReactElementWithProviderModule<P>,\n>(module: IComponentProviderModule, component: ReactElementWithProviderModule<P>): C {\n return ((componentProps: PropsWithModule<P>) => {\n const moduleCtx = useContextualizedModule(module, componentProps.module);\n\n return (\n <REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider value={moduleCtx}>\n <ComponentRenderer module={moduleCtx} componentProps={componentProps} component={component as any} />\n </REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider>\n );\n }) as any;\n}\n\nfunction _ComponentRenderer<P extends Record<string, any>>({\n module,\n component,\n componentProps,\n}: {\n module: IComponentProviderModule;\n component: ReactElementWithProviderModule<P>;\n componentProps: P;\n}) {\n return <>{component(forwardPropsWithModule(component, componentProps, module))}</>;\n}\n\nexport type ReactElementWithProviderModule<P extends Record<string, any>> = (p: PropsWithModule<P>) => React.ReactNode;\n","import { useMemo } from 'react';\n\nimport type { IComponentProviderModule } from '../../types';\nimport { useEffectOnce } from './use-effect-once';\n\nexport function useContextualizedModule(\n originalModule: IComponentProviderModule,\n forwardedModule?: IComponentProviderModule\n): IComponentProviderModule {\n const ctxModule = useMemo(() => {\n const module = (forwardedModule ?? originalModule).toNaked();\n\n if (module.isMarkedAsGlobal) return module;\n\n return module._createContextualizedComponentInstance();\n }, [originalModule, forwardedModule]);\n\n useEffectOnce(() => {\n return () => {\n ctxModule.dispose();\n };\n });\n\n return ctxModule;\n}\n","import { useEffect, useRef, useState } from 'react';\n\n// Credits: https://stackoverflow.com/a/74000921\n\n/** Custom {@link useEffect} hook which will be run once. _(In `StrictMode` as well)_ */\nexport function useEffectOnce(effect: () => React.EffectCallback) {\n const destroyFunc = useRef<React.EffectCallback>(undefined);\n const effectCalled = useRef(false);\n const renderAfterCalled = useRef(false);\n const [, forceRerender] = useState(0);\n\n if (effectCalled.current) renderAfterCalled.current = true;\n\n useEffect(() => {\n // only execute the effect first time around\n if (!effectCalled.current) {\n destroyFunc.current = effect();\n effectCalled.current = true;\n }\n\n // this forces one render after the effect is run\n forceRerender((x) => x + 1);\n\n return () => {\n // if the comp didn't render since the useEffect was called,\n // we know it's the dummy React cycle\n if (!renderAfterCalled.current) return;\n\n destroyFunc.current?.();\n };\n }, []);\n}\n","import { isFunction } from '@adimm/x-injection';\n\nimport type { ReactElementWithProviderModule } from '../core';\nimport type { IComponentProviderModule, PropsWithModule } from '../types';\n\nexport function forwardPropsWithModule<P extends Record<string, any>>(\n component: ReactElementWithProviderModule<P> | React.ReactElement,\n props: Record<string, any>,\n module: IComponentProviderModule\n): PropsWithModule<P> {\n const isReactElement = typeof component === 'object' && 'type' in component;\n\n const result = {\n ...props,\n } as any;\n\n if ((isReactElement && isFunction(component.type)) || isFunction(component)) {\n result['module'] = module;\n }\n\n return result;\n}\n","import React, { useMemo } from 'react';\n\nimport { forwardPropsWithModule, useContextualizedModule } from '../../helpers';\nimport type { IComponentProviderModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\n/**\n * Can be used to easily provide a {@link module} to any component.\n *\n * @example\n * ```tsx\n * interface MyComponentProps {\n * firstName: string;\n * lastName: string;\n * }\n *\n * function MyComponent({ firstName, lastName }: MyComponentProps) {\n * const service = useInject(MyComponentService);\n *\n * return <h1>Hello {service.computeUserName(firstName, lastName)}!</h1>\n * }\n *\n * function App() {\n * return (\n * <ProvideModule module={MyComponentModule}>\n * <MyComponent firstName={'John'} lastName={'Doe'} />\n * </ProvideModule>\n * );\n * }\n * ```\n *\n * @param param0 See {@link ProvideModuleFunctionParams}.\n * @returns The provided {@link toComponent | Component}.\n */\nexport function ProvideModule({ module, children }: ProvideModuleFunctionParams) {\n /* istanbul ignore next */\n const componentProps = (children.props ?? {}) as any;\n const moduleCtx = useContextualizedModule(module, componentProps.module);\n const component = useMemo(\n () => React.cloneElement(children, forwardPropsWithModule(children, componentProps, moduleCtx)),\n [componentProps, moduleCtx]\n );\n\n return (\n <REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider value={moduleCtx}>\n {component}\n </REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider>\n );\n}\n\nexport interface ProvideModuleFunctionParams {\n /** The {@link IComponentProviderModule | Module} which should be consumed by the {@link children | component}. */\n module: IComponentProviderModule;\n\n children: React.ReactElement;\n}\n","import type { ProviderToken } from '@adimm/x-injection';\nimport { useMemo } from 'react';\n\nimport { InjectionHookFactoryError } from '../errors';\nimport { useComponentModule } from './hooks';\n\nexport function hookFactory<P extends HookParams, D extends any[], T>({\n use: hook,\n inject,\n}: HookFactoryParams<P, D, T>): (p: P) => T {\n return (p: P) => {\n const componentModule = useComponentModule();\n\n const deps = useMemo(() => {\n if (inject.length === 0) {\n throw new InjectionHookFactoryError(componentModule, `The 'deps' property array is missing!`);\n }\n\n return componentModule.getMany(...inject);\n }, [inject]);\n\n return hook({ ...p, deps: [...deps] } as any);\n };\n}\n\nexport interface HookFactoryParams<P extends HookParams, D extends any[], T> {\n use: HookWithProviderModuleDependencies<P, D, T>;\n inject: ProviderToken[];\n}\n\nexport type HookWithProviderModuleDependencies<P extends HookParams, D extends any[], T> = (p: HookWithDeps<P, D>) => T;\n\nexport type HookWithDeps<P extends HookParams, D extends any[]> = P & {\n /** Array containing the resolved dependencies from the component context. */\n deps: D;\n};\n\ntype HookParams = Record<string, any> | void;\n","import { InjectionProviderModuleError } from '@adimm/x-injection';\n\nexport class InjectionHookFactoryError extends InjectionProviderModuleError {\n override name = InjectionHookFactoryError.name;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;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;AAGP;AAdgBP;;;ACjChB,IAAAe,gBAAwB;;;ACDxB,IAAAC,sBAA6C;AAEtC,IAAMC,4BAAN,MAAMA,mCAAkCC,iDAAAA;EAF/C,OAE+CA;;;EACpCC,OAAOF,2BAA0BE;AAC5C;;;ADEO,SAASC,YAAsD,EACpEC,KAAKC,MACLC,OAAM,GACqB;AAC3B,SAAO,CAACC,MAAAA;AACN,UAAMC,kBAAkBC,mBAAAA;AAExB,UAAMC,WAAOC,uBAAQ,MAAA;AACnB,UAAIL,OAAOM,WAAW,GAAG;AACvB,cAAM,IAAIC,0BAA0BL,iBAAiB,uCAAuC;MAC9F;AAEA,aAAOA,gBAAgBM,QAAO,GAAIR,MAAAA;IACpC,GAAG;MAACA;KAAO;AAEX,WAAOD,KAAK;MAAE,GAAGE;MAAGG,MAAM;WAAIA;;IAAM,CAAA;EACtC;AACF;AAjBgBP;","names":["REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","createContext","AppModule","import_react","useComponentModule","useContext","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","useInject","provider","options","componentModule","useComponentModule","get","isOptional","useInjectMany","deps","componentModule","useComponentModule","getMany","import_x_injection","ComponentProviderModule","ProviderModule","_initializedFromComponent","constructor","options","ProviderModuleHelpers","buildInternalConstructorParams","defaultScope","InjectionScope","Singleton","identifier","Symbol","description","toNaked","clone","providers","providersMap","map","provider","clonedModule","isAppModule","markAsGlobal","isMarkedAsGlobal","replace","native","dynamicExports","onReady","onDispose","importedProvidersMap","imports","exports","dispose","_dispose","_createContextualizedComponentInstance","ctxModule","import_react","import_react","import_react","useEffectOnce","effect","destroyFunc","useRef","undefined","effectCalled","renderAfterCalled","forceRerender","useState","current","useEffect","x","useContextualizedModule","originalModule","forwardedModule","ctxModule","useMemo","module","toNaked","isMarkedAsGlobal","_createContextualizedComponentInstance","useEffectOnce","dispose","import_x_injection","forwardPropsWithModule","component","props","module","isReactElement","result","isFunction","type","ComponentRenderer","React","memo","_ComponentRenderer","provideModuleToComponent","module","component","componentProps","moduleCtx","useContextualizedModule","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","Provider","value","forwardPropsWithModule","import_react","ProvideModule","module","children","componentProps","props","moduleCtx","useContextualizedModule","component","useMemo","React","cloneElement","forwardPropsWithModule","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","Provider","value","import_react","import_x_injection","InjectionHookFactoryError","InjectionProviderModuleError","name","hookFactory","use","hook","inject","p","componentModule","useComponentModule","deps","useMemo","length","InjectionHookFactoryError","getMany"]}
|
package/dist/index.js
CHANGED
|
@@ -15,15 +15,15 @@ function s() {
|
|
|
15
15
|
return i(r);
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
function
|
|
18
|
+
function a(e, t) {
|
|
19
19
|
return s().get(e, t?.isOptional);
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
function
|
|
22
|
+
function m(...e) {
|
|
23
23
|
return s().getMany(...e);
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
t(s, "useComponentModule"), t(
|
|
26
|
+
t(s, "useComponentModule"), t(a, "useInject"), t(m, "useInjectMany");
|
|
27
27
|
|
|
28
28
|
import { InjectionScope as c, ProviderModule as p, ProviderModuleHelpers as d } from "@adimm/x-injection";
|
|
29
29
|
|
|
@@ -47,6 +47,7 @@ var u = class e extends p {
|
|
|
47
47
|
t?.providersMap && (o = o.map((e => t.providersMap(e, this))));
|
|
48
48
|
const n = new e(d.buildInternalConstructorParams({
|
|
49
49
|
isAppModule: this.isAppModule,
|
|
50
|
+
markAsGlobal: this.isMarkedAsGlobal,
|
|
50
51
|
identifier: Symbol(this.identifier.description.replace("Component", "")),
|
|
51
52
|
defaultScope: this.defaultScope.native,
|
|
52
53
|
dynamicExports: this.dynamicExports,
|
|
@@ -76,7 +77,7 @@ import { useMemo as f } from "react";
|
|
|
76
77
|
|
|
77
78
|
import { useEffect as h, useRef as v, useState as C } from "react";
|
|
78
79
|
|
|
79
|
-
function
|
|
80
|
+
function M(e) {
|
|
80
81
|
const t = v(void 0), o = v(!1), n = v(!1), [, r] = C(0);
|
|
81
82
|
o.current && (n.current = !0), h((() => (o.current || (t.current = e(), o.current = !0),
|
|
82
83
|
r((e => e + 1)), () => {
|
|
@@ -84,14 +85,17 @@ function y(e) {
|
|
|
84
85
|
})), []);
|
|
85
86
|
}
|
|
86
87
|
|
|
87
|
-
function
|
|
88
|
-
const o = f((() =>
|
|
89
|
-
|
|
88
|
+
function y(e, t) {
|
|
89
|
+
const o = f((() => {
|
|
90
|
+
const o = (t ?? e).toNaked();
|
|
91
|
+
return o.isMarkedAsGlobal ? o : o._createContextualizedComponentInstance();
|
|
92
|
+
}), [ e, t ]);
|
|
93
|
+
return M((() => () => {
|
|
90
94
|
o.dispose();
|
|
91
95
|
})), o;
|
|
92
96
|
}
|
|
93
97
|
|
|
94
|
-
t(
|
|
98
|
+
t(M, "useEffectOnce"), t(y, "useContextualizedModule");
|
|
95
99
|
|
|
96
100
|
import { isFunction as x } from "@adimm/x-injection";
|
|
97
101
|
|
|
@@ -105,14 +109,14 @@ function P(e, t, o) {
|
|
|
105
109
|
|
|
106
110
|
t(P, "forwardPropsWithModule");
|
|
107
111
|
|
|
108
|
-
var
|
|
112
|
+
var b = l.memo(z);
|
|
109
113
|
|
|
110
|
-
function
|
|
114
|
+
function j(e, t) {
|
|
111
115
|
return o => {
|
|
112
|
-
const n =
|
|
116
|
+
const n = y(e, o.module);
|
|
113
117
|
return l.createElement(r.Provider, {
|
|
114
118
|
value: n
|
|
115
|
-
}, l.createElement(
|
|
119
|
+
}, l.createElement(b, {
|
|
116
120
|
module: n,
|
|
117
121
|
componentProps: o,
|
|
118
122
|
component: t
|
|
@@ -120,38 +124,38 @@ function z(e, t) {
|
|
|
120
124
|
};
|
|
121
125
|
}
|
|
122
126
|
|
|
123
|
-
function
|
|
127
|
+
function z({module: e, component: t, componentProps: o}) {
|
|
124
128
|
return l.createElement(l.Fragment, null, t(P(t, o, e)));
|
|
125
129
|
}
|
|
126
130
|
|
|
127
|
-
t(
|
|
131
|
+
t(j, "provideModuleToComponent"), t(z, "_ComponentRenderer");
|
|
128
132
|
|
|
129
|
-
import
|
|
133
|
+
import _, { useMemo as E } from "react";
|
|
130
134
|
|
|
131
|
-
function
|
|
132
|
-
const o = t.props ?? {}, n =
|
|
133
|
-
return
|
|
135
|
+
function F({module: e, children: t}) {
|
|
136
|
+
const o = t.props ?? {}, n = y(e, o.module), i = E((() => _.cloneElement(t, P(t, o, n))), [ o, n ]);
|
|
137
|
+
return _.createElement(r.Provider, {
|
|
134
138
|
value: n
|
|
135
139
|
}, i);
|
|
136
140
|
}
|
|
137
141
|
|
|
138
|
-
t(
|
|
142
|
+
t(F, "ProvideModule");
|
|
139
143
|
|
|
140
144
|
import { useMemo as g } from "react";
|
|
141
145
|
|
|
142
|
-
import { InjectionProviderModuleError as
|
|
146
|
+
import { InjectionProviderModuleError as k } from "@adimm/x-injection";
|
|
143
147
|
|
|
144
|
-
var
|
|
148
|
+
var S = class e extends k {
|
|
145
149
|
static {
|
|
146
150
|
t(this, "InjectionHookFactoryError");
|
|
147
151
|
}
|
|
148
152
|
name=e.name;
|
|
149
153
|
};
|
|
150
154
|
|
|
151
|
-
function
|
|
155
|
+
function I({use: e, inject: t}) {
|
|
152
156
|
return o => {
|
|
153
157
|
const n = s(), r = g((() => {
|
|
154
|
-
if (0 === t.length) throw new
|
|
158
|
+
if (0 === t.length) throw new S(n, "The 'deps' property array is missing!");
|
|
155
159
|
return n.getMany(...t);
|
|
156
160
|
}), [ t ]);
|
|
157
161
|
return e({
|
|
@@ -161,6 +165,6 @@ function k({use: e, inject: t}) {
|
|
|
161
165
|
};
|
|
162
166
|
}
|
|
163
167
|
|
|
164
|
-
t(
|
|
168
|
+
t(I, "hookFactory");
|
|
165
169
|
|
|
166
|
-
export { u as ComponentProviderModule,
|
|
170
|
+
export { u as ComponentProviderModule, F as ProvideModule, r as REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT, I as hookFactory, j as provideModuleToComponent, s as useComponentModule, a as useInject, m as useInjectMany };//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/react-context.ts","../src/core/hooks/use-component-module.ts","../src/core/hooks/use-inject.ts","../src/core/hooks/use-inject-many.ts","../src/core/component-provider-module.ts","../src/core/provide-module/provide-module.arrow-function.tsx","../src/helpers/hooks/use-contextualized-module.ts","../src/helpers/hooks/use-effect-once.ts","../src/helpers/forward-props-with-module.ts","../src/core/provide-module/provide-module.provider.tsx","../src/core/hook-factory.ts","../src/errors/hook-factory.ts"],"sourcesContent":["import { AppModule } from '@adimm/x-injection';\nimport { createContext } from 'react';\n\nimport type { IComponentProviderModule } from '../types';\n\nexport const REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT = createContext<IComponentProviderModule>(AppModule as any);\n","import { useContext } from 'react';\n\nimport type { IComponentProviderModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\n/** Can be used to retrieve the {@link IComponentProviderModule} from the current context. */\nexport function useComponentModule(): IComponentProviderModule {\n return useContext(REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT);\n}\n","import type { ProviderToken } from '@adimm/x-injection';\n\nimport { useComponentModule } from './use-component-module';\n\n/**\n * Low-level hook which can be used to resolve a single dependency from the current\n * context module.\n *\n * **Note:** _In order to better modularize your code-base, you should strive to create custom hooks by using the_\n * _`hookFactory` method to compose a custom hook._\n *\n * @param provider The {@link ProviderToken}.\n * @param options See {@link UseInjectOptions}.\n * @returns The resolved {@link T | dependency}.\n */\nexport function useInject<T>(provider: ProviderToken<T>, options?: UseInjectOptions): T {\n const componentModule = useComponentModule();\n\n return componentModule.get(provider, options?.isOptional);\n}\n\nexport type UseInjectOptions = {\n /** When set to `false` _(default)_ an exception will be thrown when the `providerOrIdentifier` isn't bound. */\n isOptional?: boolean;\n};\n","import type { ProviderModuleGetManyParam, ProviderModuleGetManySignature, ProviderToken } from '@adimm/x-injection';\n\nimport { useComponentModule } from './use-component-module';\n\n/**\n * Low-level hook which can be used to resolve multiple dependencies at once from the current\n * context module.\n *\n * **Note:** _In order to better modularize your code-base, you should strive to create custom hooks by using the_\n * _`hookFactory` method to compose a custom hook._\n *\n * @param deps Either one or more {@link ProviderToken}.\n * @returns Tuple containing the {@link D | dependencies}.\n */\nexport function useInjectMany<D extends (ProviderModuleGetManyParam<any> | ProviderToken)[]>(\n ...deps: D | unknown[]\n): ProviderModuleGetManySignature<D> {\n const componentModule = useComponentModule();\n\n return componentModule.getMany(...deps);\n}\n","import {\n InjectionScope,\n ProviderModule,\n ProviderModuleHelpers,\n type CloneParams,\n type IProviderModuleNaked,\n type ProviderModuleOptions,\n} from '@adimm/x-injection';\n\nimport type { IComponentProviderModule, IComponentProviderModuleNaked } from '../types';\n\n/** A superset of the {@link ProviderModule} used to integrate within a `React` component. */\nexport class ComponentProviderModule extends ProviderModule implements IComponentProviderModule {\n protected readonly _initializedFromComponent: IComponentProviderModuleNaked['_initializedFromComponent'];\n\n constructor(options: ProviderModuleOptions) {\n super(\n ProviderModuleHelpers.buildInternalConstructorParams({\n ...options,\n defaultScope: options.defaultScope ?? InjectionScope.Singleton,\n identifier: Symbol(`Component${options.identifier.description}`),\n })\n );\n\n this._initializedFromComponent = false;\n }\n\n override toNaked(): IComponentProviderModuleNaked & IProviderModuleNaked {\n return this as any;\n }\n\n /* istanbul ignore next */\n override clone(options?: CloneParams): IComponentProviderModule {\n let providers = [...this.providers];\n\n if (options?.providersMap) {\n providers = providers.map((provider) => options.providersMap!(provider, this));\n }\n\n const clonedModule = new ComponentProviderModule(\n ProviderModuleHelpers.buildInternalConstructorParams({\n isAppModule: this.isAppModule,\n identifier: Symbol(this.identifier.description!.replace('Component', '')),\n defaultScope: this.defaultScope.native,\n dynamicExports: this.dynamicExports,\n onReady: this.onReady,\n onDispose: this.onDispose,\n importedProvidersMap: options?.importedProvidersMap,\n imports: [...this.imports],\n providers,\n exports: [...this.exports],\n })\n );\n\n //@ts-expect-error Read-only method.\n clonedModule._initializedFromComponent = this._initializedFromComponent;\n\n return clonedModule;\n }\n\n /* istanbul ignore next */\n dispose(): void {\n this._dispose();\n }\n\n //#region IComponentProviderModuleNaked methods\n\n /**\n * **Publicly visible when the instance is casted to {@link IComponentProviderModuleNaked}.**\n *\n * See {@link IComponentProviderModuleNaked._createContextualizedComponentInstance}.\n */\n protected _createContextualizedComponentInstance(): IComponentProviderModule {\n if (this._initializedFromComponent) return this;\n\n const ctxModule = this.clone().toNaked();\n\n //@ts-expect-error Read-only property\n ctxModule.identifier = Symbol(`Contextualized${ctxModule.identifier.description}`);\n ctxModule._initializedFromComponent = true;\n\n return ctxModule;\n }\n\n //#endregion\n}\n","import React from 'react';\n\nimport { forwardPropsWithModule, useContextualizedModule } from '../../helpers';\nimport type { IComponentProviderModule, PropsWithModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\nconst ComponentRenderer = React.memo(_ComponentRenderer);\n\n/**\n * Can be used to easily provide a {@link module} to any component.\n *\n * @example\n * ```tsx\n * interface MyComponentProps {\n * firstName: string;\n * lastName: string;\n * }\n *\n * export const MyComponent = provideModuleToComponent(\n * MyComponentModule,\n * ({ firstName, lastName }: MyComponentProps) => {\n * const service = useInject(MyComponentService);\n *\n * return <h1>Hello {service.computeUserName(firstName, lastName)}!</h1>\n * }\n * );\n *\n * function App() {\n * return <MyComponent firstName={'John'} lastName={'Doe'} />;\n * }\n * ```\n *\n * @param module The {@link IComponentProviderModule | Module} which should be consumed by the {@link component}.\n * @returns The provided {@link toComponent | Component}.\n */\nexport function provideModuleToComponent<\n P extends Record<string, any>,\n C extends ReactElementWithProviderModule<P> = ReactElementWithProviderModule<P>,\n>(module: IComponentProviderModule, component: ReactElementWithProviderModule<P>): C {\n return ((componentProps: PropsWithModule<P>) => {\n const moduleCtx = useContextualizedModule(module, componentProps.module);\n\n return (\n <REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider value={moduleCtx}>\n <ComponentRenderer module={moduleCtx} componentProps={componentProps} component={component as any} />\n </REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider>\n );\n }) as any;\n}\n\nfunction _ComponentRenderer<P extends Record<string, any>>({\n module,\n component,\n componentProps,\n}: {\n module: IComponentProviderModule;\n component: ReactElementWithProviderModule<P>;\n componentProps: P;\n}) {\n return <>{component(forwardPropsWithModule(component, componentProps, module))}</>;\n}\n\nexport type ReactElementWithProviderModule<P extends Record<string, any>> = (p: PropsWithModule<P>) => React.ReactNode;\n","import { useMemo } from 'react';\n\nimport type { IComponentProviderModule } from '../../types';\nimport { useEffectOnce } from './use-effect-once';\n\nexport function useContextualizedModule(\n originalModule: IComponentProviderModule,\n forwardedModule?: IComponentProviderModule\n): IComponentProviderModule {\n const ctxModule = useMemo(() => {\n return (forwardedModule ?? originalModule).toNaked()._createContextualizedComponentInstance();\n }, [originalModule, forwardedModule]);\n\n useEffectOnce(() => {\n return () => {\n ctxModule.dispose();\n };\n });\n\n return ctxModule;\n}\n","import { useEffect, useRef, useState } from 'react';\n\n// Credits: https://stackoverflow.com/a/74000921\n\n/** Custom {@link useEffect} hook which will be run once. _(In `StrictMode` as well)_ */\nexport function useEffectOnce(effect: () => React.EffectCallback) {\n const destroyFunc = useRef<React.EffectCallback>(undefined);\n const effectCalled = useRef(false);\n const renderAfterCalled = useRef(false);\n const [, forceRerender] = useState(0);\n\n if (effectCalled.current) renderAfterCalled.current = true;\n\n useEffect(() => {\n // only execute the effect first time around\n if (!effectCalled.current) {\n destroyFunc.current = effect();\n effectCalled.current = true;\n }\n\n // this forces one render after the effect is run\n forceRerender((x) => x + 1);\n\n return () => {\n // if the comp didn't render since the useEffect was called,\n // we know it's the dummy React cycle\n if (!renderAfterCalled.current) return;\n\n destroyFunc.current?.();\n };\n }, []);\n}\n","import { isFunction } from '@adimm/x-injection';\n\nimport type { ReactElementWithProviderModule } from '../core';\nimport type { IComponentProviderModule, PropsWithModule } from '../types';\n\nexport function forwardPropsWithModule<P extends Record<string, any>>(\n component: ReactElementWithProviderModule<P> | React.ReactElement,\n props: Record<string, any>,\n module: IComponentProviderModule\n): PropsWithModule<P> {\n const isReactElement = typeof component === 'object' && 'type' in component;\n\n const result = {\n ...props,\n } as any;\n\n if ((isReactElement && isFunction(component.type)) || isFunction(component)) {\n result['module'] = module;\n }\n\n return result;\n}\n","import React, { useMemo } from 'react';\n\nimport { forwardPropsWithModule, useContextualizedModule } from '../../helpers';\nimport type { IComponentProviderModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\n/**\n * Can be used to easily provide a {@link module} to any component.\n *\n * @example\n * ```tsx\n * interface MyComponentProps {\n * firstName: string;\n * lastName: string;\n * }\n *\n * function MyComponent({ firstName, lastName }: MyComponentProps) {\n * const service = useInject(MyComponentService);\n *\n * return <h1>Hello {service.computeUserName(firstName, lastName)}!</h1>\n * }\n *\n * function App() {\n * return (\n * <ProvideModule module={MyComponentModule}>\n * <MyComponent firstName={'John'} lastName={'Doe'} />\n * </ProvideModule>\n * );\n * }\n * ```\n *\n * @param param0 See {@link ProvideModuleFunctionParams}.\n * @returns The provided {@link toComponent | Component}.\n */\nexport function ProvideModule({ module, children }: ProvideModuleFunctionParams) {\n /* istanbul ignore next */\n const componentProps = (children.props ?? {}) as any;\n const moduleCtx = useContextualizedModule(module, componentProps.module);\n const component = useMemo(\n () => React.cloneElement(children, forwardPropsWithModule(children, componentProps, moduleCtx)),\n [componentProps, moduleCtx]\n );\n\n return (\n <REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider value={moduleCtx}>\n {component}\n </REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider>\n );\n}\n\nexport interface ProvideModuleFunctionParams {\n /** The {@link IComponentProviderModule | Module} which should be consumed by the {@link children | component}. */\n module: IComponentProviderModule;\n\n children: React.ReactElement;\n}\n","import type { ProviderToken } from '@adimm/x-injection';\nimport { useMemo } from 'react';\n\nimport { InjectionHookFactoryError } from '../errors';\nimport { useComponentModule } from './hooks';\n\nexport function hookFactory<P extends HookParams, D extends any[], T>({\n use: hook,\n inject,\n}: HookFactoryParams<P, D, T>): (p: P) => T {\n return (p: P) => {\n const componentModule = useComponentModule();\n\n const deps = useMemo(() => {\n if (inject.length === 0) {\n throw new InjectionHookFactoryError(componentModule, `The 'deps' property array is missing!`);\n }\n\n return componentModule.getMany(...inject);\n }, [inject]);\n\n return hook({ ...p, deps: [...deps] } as any);\n };\n}\n\nexport interface HookFactoryParams<P extends HookParams, D extends any[], T> {\n use: HookWithProviderModuleDependencies<P, D, T>;\n inject: ProviderToken[];\n}\n\nexport type HookWithProviderModuleDependencies<P extends HookParams, D extends any[], T> = (p: HookWithDeps<P, D>) => T;\n\nexport type HookWithDeps<P extends HookParams, D extends any[]> = P & {\n /** Array containing the resolved dependencies from the component context. */\n deps: D;\n};\n\ntype HookParams = Record<string, any> | void;\n","import { InjectionProviderModuleError } from '@adimm/x-injection';\n\nexport class InjectionHookFactoryError extends InjectionProviderModuleError {\n override name = InjectionHookFactoryError.name;\n}\n"],"mappings":";;;;AAAA,SAASA,iBAAiB;AAC1B,SAASC,qBAAqB;AAIvB,IAAMC,4CAA4CD,cAAwCD,SAAAA;;;ACLjG,SAASG,kBAAkB;AAMpB,SAASC,qBAAAA;AACd,SAAOC,WAAWC,yCAAAA;AACpB;AAFgBF;;;ACST,SAASG,UAAaC,UAA4BC,SAA0B;AACjF,QAAMC,kBAAkBC,mBAAAA;AAExB,SAAOD,gBAAgBE,IAAIJ,UAAUC,SAASI,UAAAA;AAChD;AAJgBN;;;ACDT,SAASO,iBACXC,MAAmB;AAEtB,QAAMC,kBAAkBC,mBAAAA;AAExB,SAAOD,gBAAgBE,QAAO,GAAIH,IAAAA;AACpC;AANgBD;;;ACdhB,SACEK,gBACAC,gBACAC,6BAIK;AAKA,IAAMC,0BAAN,MAAMA,iCAAgCC,eAAAA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AAkBK,QAAQG;MAAWD;MAAgCD;;EAG5E;AACF;AAbgBF;AAehB,SAASD,mBAAkD,EACzDE,QACAC,WACAC,eAAc,GAKf;AACC,SAAO,sBAAA,cAAA,MAAA,UAAA,MAAGD,UAAUO,uBAAuBP,WAAWC,gBAAgBF,MAAAA,CAAAA,CAAAA;AACxE;AAVSF;;;AIlDT,OAAOW,UAASC,WAAAA,gBAAe;AAkCxB,SAASC,cAAc,EAAEC,QAAQC,SAAQ,GAA+B;AAE7E,QAAMC,iBAAkBD,SAASE,SAAS,CAAC;AAC3C,QAAMC,YAAYC,wBAAwBL,QAAQE,eAAeF,MAAM;AACvE,QAAMM,YAAYC,SAChB,MAAMC,gBAAAA,OAAMC,aAAaR,UAAUS,uBAAuBT,UAAUC,gBAAgBE,SAAAA,CAAAA,GACpF;IAACF;IAAgBE;GAAU;AAG7B,SACE,gBAAAI,OAAA,cAACG,0CAA0CC,UAAQ;IAACC,OAAOT;KACxDE,SAAAA;AAGP;AAdgBP;;;ACjChB,SAASe,WAAAA,gBAAe;;;ACDxB,SAASC,oCAAoC;AAEtC,IAAMC,4BAAN,MAAMA,mCAAkCC,6BAAAA;EAF/C,OAE+CA;;;EACpCC,OAAOF,2BAA0BE;AAC5C;;;ADEO,SAASC,YAAsD,EACpEC,KAAKC,MACLC,OAAM,GACqB;AAC3B,SAAO,CAACC,MAAAA;AACN,UAAMC,kBAAkBC,mBAAAA;AAExB,UAAMC,OAAOC,SAAQ,MAAA;AACnB,UAAIL,OAAOM,WAAW,GAAG;AACvB,cAAM,IAAIC,0BAA0BL,iBAAiB,uCAAuC;MAC9F;AAEA,aAAOA,gBAAgBM,QAAO,GAAIR,MAAAA;IACpC,GAAG;MAACA;KAAO;AAEX,WAAOD,KAAK;MAAE,GAAGE;MAAGG,MAAM;WAAIA;;IAAM,CAAA;EACtC;AACF;AAjBgBP;","names":["AppModule","createContext","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","useContext","useComponentModule","useContext","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","useInject","provider","options","componentModule","useComponentModule","get","isOptional","useInjectMany","deps","componentModule","useComponentModule","getMany","InjectionScope","ProviderModule","ProviderModuleHelpers","ComponentProviderModule","ProviderModule","_initializedFromComponent","constructor","options","ProviderModuleHelpers","buildInternalConstructorParams","defaultScope","InjectionScope","Singleton","identifier","Symbol","description","toNaked","clone","providers","providersMap","map","provider","clonedModule","isAppModule","replace","native","dynamicExports","onReady","onDispose","importedProvidersMap","imports","exports","dispose","_dispose","_createContextualizedComponentInstance","ctxModule","React","useMemo","useEffect","useRef","useState","useEffectOnce","effect","destroyFunc","useRef","undefined","effectCalled","renderAfterCalled","forceRerender","useState","current","useEffect","x","useContextualizedModule","originalModule","forwardedModule","ctxModule","useMemo","toNaked","_createContextualizedComponentInstance","useEffectOnce","dispose","isFunction","forwardPropsWithModule","component","props","module","isReactElement","result","isFunction","type","ComponentRenderer","React","memo","_ComponentRenderer","provideModuleToComponent","module","component","componentProps","moduleCtx","useContextualizedModule","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","Provider","value","forwardPropsWithModule","React","useMemo","ProvideModule","module","children","componentProps","props","moduleCtx","useContextualizedModule","component","useMemo","React","cloneElement","forwardPropsWithModule","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","Provider","value","useMemo","InjectionProviderModuleError","InjectionHookFactoryError","InjectionProviderModuleError","name","hookFactory","use","hook","inject","p","componentModule","useComponentModule","deps","useMemo","length","InjectionHookFactoryError","getMany"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/react-context.ts","../src/core/hooks/use-component-module.ts","../src/core/hooks/use-inject.ts","../src/core/hooks/use-inject-many.ts","../src/core/component-provider-module.ts","../src/core/provide-module/provide-module.arrow-function.tsx","../src/helpers/hooks/use-contextualized-module.ts","../src/helpers/hooks/use-effect-once.ts","../src/helpers/forward-props-with-module.ts","../src/core/provide-module/provide-module.provider.tsx","../src/core/hook-factory.ts","../src/errors/hook-factory.ts"],"sourcesContent":["import { AppModule } from '@adimm/x-injection';\nimport { createContext } from 'react';\n\nimport type { IComponentProviderModule } from '../types';\n\nexport const REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT = createContext<IComponentProviderModule>(AppModule as any);\n","import { useContext } from 'react';\n\nimport type { IComponentProviderModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\n/** Can be used to retrieve the {@link IComponentProviderModule} from the current context. */\nexport function useComponentModule(): IComponentProviderModule {\n return useContext(REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT);\n}\n","import type { ProviderToken } from '@adimm/x-injection';\n\nimport { useComponentModule } from './use-component-module';\n\n/**\n * Low-level hook which can be used to resolve a single dependency from the current\n * context module.\n *\n * **Note:** _In order to better modularize your code-base, you should strive to create custom hooks by using the_\n * _`hookFactory` method to compose a custom hook._\n *\n * @param provider The {@link ProviderToken}.\n * @param options See {@link UseInjectOptions}.\n * @returns The resolved {@link T | dependency}.\n */\nexport function useInject<T>(provider: ProviderToken<T>, options?: UseInjectOptions): T {\n const componentModule = useComponentModule();\n\n return componentModule.get(provider, options?.isOptional);\n}\n\nexport type UseInjectOptions = {\n /** When set to `false` _(default)_ an exception will be thrown when the `providerOrIdentifier` isn't bound. */\n isOptional?: boolean;\n};\n","import type { ProviderModuleGetManyParam, ProviderModuleGetManySignature, ProviderToken } from '@adimm/x-injection';\n\nimport { useComponentModule } from './use-component-module';\n\n/**\n * Low-level hook which can be used to resolve multiple dependencies at once from the current\n * context module.\n *\n * **Note:** _In order to better modularize your code-base, you should strive to create custom hooks by using the_\n * _`hookFactory` method to compose a custom hook._\n *\n * @param deps Either one or more {@link ProviderToken}.\n * @returns Tuple containing the {@link D | dependencies}.\n */\nexport function useInjectMany<D extends (ProviderModuleGetManyParam<any> | ProviderToken)[]>(\n ...deps: D | unknown[]\n): ProviderModuleGetManySignature<D> {\n const componentModule = useComponentModule();\n\n return componentModule.getMany(...deps);\n}\n","import {\n InjectionScope,\n ProviderModule,\n ProviderModuleHelpers,\n type CloneParams,\n type IProviderModuleNaked,\n type ProviderModuleOptions,\n} from '@adimm/x-injection';\n\nimport type { IComponentProviderModule, IComponentProviderModuleNaked } from '../types';\n\n/** A superset of the {@link ProviderModule} used to integrate within a `React` component. */\nexport class ComponentProviderModule extends ProviderModule implements IComponentProviderModule {\n protected readonly _initializedFromComponent: IComponentProviderModuleNaked['_initializedFromComponent'];\n\n constructor(options: ProviderModuleOptions) {\n super(\n ProviderModuleHelpers.buildInternalConstructorParams({\n ...options,\n defaultScope: options.defaultScope ?? InjectionScope.Singleton,\n identifier: Symbol(`Component${options.identifier.description}`),\n })\n );\n\n this._initializedFromComponent = false;\n }\n\n override toNaked(): IComponentProviderModuleNaked & IProviderModuleNaked {\n return this as any;\n }\n\n /* istanbul ignore next */\n override clone(options?: CloneParams): IComponentProviderModule {\n let providers = [...this.providers];\n\n if (options?.providersMap) {\n providers = providers.map((provider) => options.providersMap!(provider, this));\n }\n\n const clonedModule = new ComponentProviderModule(\n ProviderModuleHelpers.buildInternalConstructorParams({\n isAppModule: this.isAppModule,\n markAsGlobal: this.isMarkedAsGlobal,\n identifier: Symbol(this.identifier.description!.replace('Component', '')),\n defaultScope: this.defaultScope.native,\n dynamicExports: this.dynamicExports,\n onReady: this.onReady,\n onDispose: this.onDispose,\n importedProvidersMap: options?.importedProvidersMap,\n imports: [...this.imports],\n providers,\n exports: [...this.exports],\n })\n );\n\n //@ts-expect-error Read-only method.\n clonedModule._initializedFromComponent = this._initializedFromComponent;\n\n return clonedModule;\n }\n\n /* istanbul ignore next */\n dispose(): void {\n this._dispose();\n }\n\n //#region IComponentProviderModuleNaked methods\n\n /**\n * **Publicly visible when the instance is casted to {@link IComponentProviderModuleNaked}.**\n *\n * See {@link IComponentProviderModuleNaked._createContextualizedComponentInstance}.\n */\n protected _createContextualizedComponentInstance(): IComponentProviderModule {\n if (this._initializedFromComponent) return this;\n\n const ctxModule = this.clone().toNaked();\n\n //@ts-expect-error Read-only property\n ctxModule.identifier = Symbol(`Contextualized${ctxModule.identifier.description}`);\n ctxModule._initializedFromComponent = true;\n\n return ctxModule;\n }\n\n //#endregion\n}\n","import React from 'react';\n\nimport { forwardPropsWithModule, useContextualizedModule } from '../../helpers';\nimport type { IComponentProviderModule, PropsWithModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\nconst ComponentRenderer = React.memo(_ComponentRenderer);\n\n/**\n * Can be used to easily provide a {@link module} to any component.\n *\n * @example\n * ```tsx\n * interface MyComponentProps {\n * firstName: string;\n * lastName: string;\n * }\n *\n * export const MyComponent = provideModuleToComponent(\n * MyComponentModule,\n * ({ firstName, lastName }: MyComponentProps) => {\n * const service = useInject(MyComponentService);\n *\n * return <h1>Hello {service.computeUserName(firstName, lastName)}!</h1>\n * }\n * );\n *\n * function App() {\n * return <MyComponent firstName={'John'} lastName={'Doe'} />;\n * }\n * ```\n *\n * @param module The {@link IComponentProviderModule | Module} which should be consumed by the {@link component}.\n * @returns The provided {@link toComponent | Component}.\n */\nexport function provideModuleToComponent<\n P extends Record<string, any>,\n C extends ReactElementWithProviderModule<P> = ReactElementWithProviderModule<P>,\n>(module: IComponentProviderModule, component: ReactElementWithProviderModule<P>): C {\n return ((componentProps: PropsWithModule<P>) => {\n const moduleCtx = useContextualizedModule(module, componentProps.module);\n\n return (\n <REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider value={moduleCtx}>\n <ComponentRenderer module={moduleCtx} componentProps={componentProps} component={component as any} />\n </REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider>\n );\n }) as any;\n}\n\nfunction _ComponentRenderer<P extends Record<string, any>>({\n module,\n component,\n componentProps,\n}: {\n module: IComponentProviderModule;\n component: ReactElementWithProviderModule<P>;\n componentProps: P;\n}) {\n return <>{component(forwardPropsWithModule(component, componentProps, module))}</>;\n}\n\nexport type ReactElementWithProviderModule<P extends Record<string, any>> = (p: PropsWithModule<P>) => React.ReactNode;\n","import { useMemo } from 'react';\n\nimport type { IComponentProviderModule } from '../../types';\nimport { useEffectOnce } from './use-effect-once';\n\nexport function useContextualizedModule(\n originalModule: IComponentProviderModule,\n forwardedModule?: IComponentProviderModule\n): IComponentProviderModule {\n const ctxModule = useMemo(() => {\n const module = (forwardedModule ?? originalModule).toNaked();\n\n if (module.isMarkedAsGlobal) return module;\n\n return module._createContextualizedComponentInstance();\n }, [originalModule, forwardedModule]);\n\n useEffectOnce(() => {\n return () => {\n ctxModule.dispose();\n };\n });\n\n return ctxModule;\n}\n","import { useEffect, useRef, useState } from 'react';\n\n// Credits: https://stackoverflow.com/a/74000921\n\n/** Custom {@link useEffect} hook which will be run once. _(In `StrictMode` as well)_ */\nexport function useEffectOnce(effect: () => React.EffectCallback) {\n const destroyFunc = useRef<React.EffectCallback>(undefined);\n const effectCalled = useRef(false);\n const renderAfterCalled = useRef(false);\n const [, forceRerender] = useState(0);\n\n if (effectCalled.current) renderAfterCalled.current = true;\n\n useEffect(() => {\n // only execute the effect first time around\n if (!effectCalled.current) {\n destroyFunc.current = effect();\n effectCalled.current = true;\n }\n\n // this forces one render after the effect is run\n forceRerender((x) => x + 1);\n\n return () => {\n // if the comp didn't render since the useEffect was called,\n // we know it's the dummy React cycle\n if (!renderAfterCalled.current) return;\n\n destroyFunc.current?.();\n };\n }, []);\n}\n","import { isFunction } from '@adimm/x-injection';\n\nimport type { ReactElementWithProviderModule } from '../core';\nimport type { IComponentProviderModule, PropsWithModule } from '../types';\n\nexport function forwardPropsWithModule<P extends Record<string, any>>(\n component: ReactElementWithProviderModule<P> | React.ReactElement,\n props: Record<string, any>,\n module: IComponentProviderModule\n): PropsWithModule<P> {\n const isReactElement = typeof component === 'object' && 'type' in component;\n\n const result = {\n ...props,\n } as any;\n\n if ((isReactElement && isFunction(component.type)) || isFunction(component)) {\n result['module'] = module;\n }\n\n return result;\n}\n","import React, { useMemo } from 'react';\n\nimport { forwardPropsWithModule, useContextualizedModule } from '../../helpers';\nimport type { IComponentProviderModule } from '../../types';\nimport { REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT } from '../react-context';\n\n/**\n * Can be used to easily provide a {@link module} to any component.\n *\n * @example\n * ```tsx\n * interface MyComponentProps {\n * firstName: string;\n * lastName: string;\n * }\n *\n * function MyComponent({ firstName, lastName }: MyComponentProps) {\n * const service = useInject(MyComponentService);\n *\n * return <h1>Hello {service.computeUserName(firstName, lastName)}!</h1>\n * }\n *\n * function App() {\n * return (\n * <ProvideModule module={MyComponentModule}>\n * <MyComponent firstName={'John'} lastName={'Doe'} />\n * </ProvideModule>\n * );\n * }\n * ```\n *\n * @param param0 See {@link ProvideModuleFunctionParams}.\n * @returns The provided {@link toComponent | Component}.\n */\nexport function ProvideModule({ module, children }: ProvideModuleFunctionParams) {\n /* istanbul ignore next */\n const componentProps = (children.props ?? {}) as any;\n const moduleCtx = useContextualizedModule(module, componentProps.module);\n const component = useMemo(\n () => React.cloneElement(children, forwardPropsWithModule(children, componentProps, moduleCtx)),\n [componentProps, moduleCtx]\n );\n\n return (\n <REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider value={moduleCtx}>\n {component}\n </REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT.Provider>\n );\n}\n\nexport interface ProvideModuleFunctionParams {\n /** The {@link IComponentProviderModule | Module} which should be consumed by the {@link children | component}. */\n module: IComponentProviderModule;\n\n children: React.ReactElement;\n}\n","import type { ProviderToken } from '@adimm/x-injection';\nimport { useMemo } from 'react';\n\nimport { InjectionHookFactoryError } from '../errors';\nimport { useComponentModule } from './hooks';\n\nexport function hookFactory<P extends HookParams, D extends any[], T>({\n use: hook,\n inject,\n}: HookFactoryParams<P, D, T>): (p: P) => T {\n return (p: P) => {\n const componentModule = useComponentModule();\n\n const deps = useMemo(() => {\n if (inject.length === 0) {\n throw new InjectionHookFactoryError(componentModule, `The 'deps' property array is missing!`);\n }\n\n return componentModule.getMany(...inject);\n }, [inject]);\n\n return hook({ ...p, deps: [...deps] } as any);\n };\n}\n\nexport interface HookFactoryParams<P extends HookParams, D extends any[], T> {\n use: HookWithProviderModuleDependencies<P, D, T>;\n inject: ProviderToken[];\n}\n\nexport type HookWithProviderModuleDependencies<P extends HookParams, D extends any[], T> = (p: HookWithDeps<P, D>) => T;\n\nexport type HookWithDeps<P extends HookParams, D extends any[]> = P & {\n /** Array containing the resolved dependencies from the component context. */\n deps: D;\n};\n\ntype HookParams = Record<string, any> | void;\n","import { InjectionProviderModuleError } from '@adimm/x-injection';\n\nexport class InjectionHookFactoryError extends InjectionProviderModuleError {\n override name = InjectionHookFactoryError.name;\n}\n"],"mappings":";;;;AAAA,SAASA,iBAAiB;AAC1B,SAASC,qBAAqB;AAIvB,IAAMC,4CAA4CD,cAAwCD,SAAAA;;;ACLjG,SAASG,kBAAkB;AAMpB,SAASC,qBAAAA;AACd,SAAOC,WAAWC,yCAAAA;AACpB;AAFgBF;;;ACST,SAASG,UAAaC,UAA4BC,SAA0B;AACjF,QAAMC,kBAAkBC,mBAAAA;AAExB,SAAOD,gBAAgBE,IAAIJ,UAAUC,SAASI,UAAAA;AAChD;AAJgBN;;;ACDT,SAASO,iBACXC,MAAmB;AAEtB,QAAMC,kBAAkBC,mBAAAA;AAExB,SAAOD,gBAAgBE,QAAO,GAAIH,IAAAA;AACpC;AANgBD;;;ACdhB,SACEK,gBACAC,gBACAC,6BAIK;AAKA,IAAMC,0BAAN,MAAMA,iCAAgCC,eAAAA;EAZ7C,OAY6CA;;;EACxBC;EAEnBC,YAAYC,SAAgC;AAC1C,UACEC,sBAAsBC,+BAA+B;MACnD,GAAGF;MACHG,cAAcH,QAAQG,gBAAgBC,eAAeC;MACrDC,YAAYC,OAAO,YAAYP,QAAQM,WAAWE,WAAW,EAAE;IACjE,CAAA,CAAA;AAGF,SAAKV,4BAA4B;EACnC;EAESW,UAAgE;AACvE,WAAO;EACT;;EAGSC,MAAMV,SAAiD;AAC9D,QAAIW,YAAY;SAAI,KAAKA;;AAEzB,QAAIX,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AkCxB,SAASC,cAAc,EAAEC,QAAQC,SAAQ,GAA+B;AAE7E,QAAMC,iBAAkBD,SAASE,SAAS,CAAC;AAC3C,QAAMC,YAAYC,wBAAwBL,QAAQE,eAAeF,MAAM;AACvE,QAAMM,YAAYC,SAChB,MAAMC,gBAAAA,OAAMC,aAAaR,UAAUS,uBAAuBT,UAAUC,gBAAgBE,SAAAA,CAAAA,GACpF;IAACF;IAAgBE;GAAU;AAG7B,SACE,gBAAAI,OAAA,cAACG,0CAA0CC,UAAQ;IAACC,OAAOT;KACxDE,SAAAA;AAGP;AAdgBP;;;ACjChB,SAASe,WAAAA,gBAAe;;;ACDxB,SAASC,oCAAoC;AAEtC,IAAMC,4BAAN,MAAMA,mCAAkCC,6BAAAA;EAF/C,OAE+CA;;;EACpCC,OAAOF,2BAA0BE;AAC5C;;;ADEO,SAASC,YAAsD,EACpEC,KAAKC,MACLC,OAAM,GACqB;AAC3B,SAAO,CAACC,MAAAA;AACN,UAAMC,kBAAkBC,mBAAAA;AAExB,UAAMC,OAAOC,SAAQ,MAAA;AACnB,UAAIL,OAAOM,WAAW,GAAG;AACvB,cAAM,IAAIC,0BAA0BL,iBAAiB,uCAAuC;MAC9F;AAEA,aAAOA,gBAAgBM,QAAO,GAAIR,MAAAA;IACpC,GAAG;MAACA;KAAO;AAEX,WAAOD,KAAK;MAAE,GAAGE;MAAGG,MAAM;WAAIA;;IAAM,CAAA;EACtC;AACF;AAjBgBP;","names":["AppModule","createContext","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","useContext","useComponentModule","useContext","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","useInject","provider","options","componentModule","useComponentModule","get","isOptional","useInjectMany","deps","componentModule","useComponentModule","getMany","InjectionScope","ProviderModule","ProviderModuleHelpers","ComponentProviderModule","ProviderModule","_initializedFromComponent","constructor","options","ProviderModuleHelpers","buildInternalConstructorParams","defaultScope","InjectionScope","Singleton","identifier","Symbol","description","toNaked","clone","providers","providersMap","map","provider","clonedModule","isAppModule","markAsGlobal","isMarkedAsGlobal","replace","native","dynamicExports","onReady","onDispose","importedProvidersMap","imports","exports","dispose","_dispose","_createContextualizedComponentInstance","ctxModule","React","useMemo","useEffect","useRef","useState","useEffectOnce","effect","destroyFunc","useRef","undefined","effectCalled","renderAfterCalled","forceRerender","useState","current","useEffect","x","useContextualizedModule","originalModule","forwardedModule","ctxModule","useMemo","module","toNaked","isMarkedAsGlobal","_createContextualizedComponentInstance","useEffectOnce","dispose","isFunction","forwardPropsWithModule","component","props","module","isReactElement","result","isFunction","type","ComponentRenderer","React","memo","_ComponentRenderer","provideModuleToComponent","module","component","componentProps","moduleCtx","useContextualizedModule","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","Provider","value","forwardPropsWithModule","React","useMemo","ProvideModule","module","children","componentProps","props","moduleCtx","useContextualizedModule","component","useMemo","React","cloneElement","forwardPropsWithModule","REACT_X_INJECTION_PROVIDER_MODULE_CONTEXT","Provider","value","useMemo","InjectionProviderModuleError","InjectionHookFactoryError","InjectionProviderModuleError","name","hookFactory","use","hook","inject","p","componentModule","useComponentModule","deps","useMemo","length","InjectionHookFactoryError","getMany"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adimm/x-injection-reactjs",
|
|
3
3
|
"description": "ReactJS integration of the `xInjection` library.",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.4",
|
|
5
5
|
"author": "Adi-Marian Mutu",
|
|
6
6
|
"homepage": "https://github.com/AdiMarianMutu/x-injection-reactjs#readme",
|
|
7
7
|
"bugs": "https://github.com/AdiMarianMutu/x-injection-reactjs/issues",
|
|
@@ -32,12 +32,13 @@
|
|
|
32
32
|
"start:watch": "tsup src/index.ts --config ./config/tsup.config.ts --watch --onSuccess 'node dist/index.js'",
|
|
33
33
|
"test": "jest --config ./config/jest.config.ts",
|
|
34
34
|
"test:coverage": "npm run test && http-server ./coverage/lcov-report --cors -p 8081 -c-1",
|
|
35
|
+
"update-base-lib": "npm i @adimm/x-injection@latest & git add package.json package-lock.json & git commit -m \"chore: install latest version of the `xInjection` base lib\"",
|
|
35
36
|
"v:bump-patch": "npm version patch -m \"chore: update lib patch version to %s\"",
|
|
36
37
|
"v:bump-minor": "npm version minor -m \"chore: update lib minor version to %s\"",
|
|
37
38
|
"v:bump-major": "npm version major -m \"chore: update lib major version %s\""
|
|
38
39
|
},
|
|
39
40
|
"dependencies": {
|
|
40
|
-
"@adimm/x-injection": "^0.6.
|
|
41
|
+
"@adimm/x-injection": "^0.6.4",
|
|
41
42
|
"react": ">=18.0.0"
|
|
42
43
|
},
|
|
43
44
|
"devDependencies": {
|