react-chain-of-responsibility 0.4.0-main.6548dd9 → 0.4.0-main.d864102
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/dist/{chunk-3IVASMVM.mjs → chunk-U4UF7NZV.mjs} +3 -6
- package/dist/chunk-U4UF7NZV.mjs.map +1 -0
- package/dist/{index-Cx9W9BxD.d.mts → index-Dm_KqEiI.d.mts} +5 -9
- package/dist/{index-Cx9W9BxD.d.ts → index-Dm_KqEiI.d.ts} +5 -9
- package/dist/react-chain-of-responsibility.d.mts +2 -1
- package/dist/react-chain-of-responsibility.d.ts +2 -1
- package/dist/react-chain-of-responsibility.fluentUI.d.mts +2 -1
- package/dist/react-chain-of-responsibility.fluentUI.d.ts +2 -1
- package/dist/react-chain-of-responsibility.fluentUI.js +3 -15
- package/dist/react-chain-of-responsibility.fluentUI.js.map +1 -1
- package/dist/react-chain-of-responsibility.fluentUI.mjs +1 -2
- package/dist/react-chain-of-responsibility.fluentUI.mjs.map +1 -1
- package/dist/react-chain-of-responsibility.js +3 -15
- package/dist/react-chain-of-responsibility.js.map +1 -1
- package/dist/react-chain-of-responsibility.mjs +1 -2
- package/dist/react-chain-of-responsibility.preview.d.mts +15 -8
- package/dist/react-chain-of-responsibility.preview.d.ts +15 -8
- package/dist/react-chain-of-responsibility.preview.js +10 -22
- package/dist/react-chain-of-responsibility.preview.js.map +1 -1
- package/dist/react-chain-of-responsibility.preview.mjs +9 -12
- package/dist/react-chain-of-responsibility.preview.mjs.map +1 -1
- package/package.json +21 -9
- package/dist/chunk-3IVASMVM.mjs.map +0 -1
- package/dist/chunk-TNTIZJJ5.mjs +0 -17
- package/dist/chunk-TNTIZJJ5.mjs.map +0 -1
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
applyMiddleware
|
|
3
|
-
} from "./chunk-TNTIZJJ5.mjs";
|
|
4
|
-
|
|
5
1
|
// src/createChainOfResponsibility.tsx
|
|
2
|
+
import { applyMiddleware } from "handler-chain";
|
|
6
3
|
import React, {
|
|
7
4
|
createContext,
|
|
8
5
|
isValidElement,
|
|
@@ -91,7 +88,7 @@ function createChainOfResponsibility(options = {}) {
|
|
|
91
88
|
// - With reverse, [a, b, c] will become a(b(c(fn)))
|
|
92
89
|
// - Without reverse, [a, b, c] will become c(b(a(fn)))
|
|
93
90
|
applyMiddleware(
|
|
94
|
-
...[...patchedMiddleware, ...parentEnhancer ? [() => parentEnhancer] : []]
|
|
91
|
+
...[...patchedMiddleware, ...parentEnhancer ? [() => parentEnhancer] : []]
|
|
95
92
|
)(init)
|
|
96
93
|
),
|
|
97
94
|
[init, middleware, parentEnhancer]
|
|
@@ -150,4 +147,4 @@ var createChainOfResponsibility_default = createChainOfResponsibility;
|
|
|
150
147
|
export {
|
|
151
148
|
createChainOfResponsibility_default
|
|
152
149
|
};
|
|
153
|
-
//# sourceMappingURL=chunk-
|
|
150
|
+
//# sourceMappingURL=chunk-U4UF7NZV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/createChainOfResponsibility.tsx","../src/isReactComponent.ts"],"sourcesContent":["import { applyMiddleware } from 'handler-chain';\nimport React, {\n createContext,\n isValidElement,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren\n} from 'react';\n\nimport isReactComponent from './isReactComponent.ts';\nimport { type ComponentEnhancer, type ComponentMiddleware } from './types.ts';\n\n// TODO: Simplify to ComponentType<Props> | undefined.\ntype ResultComponent<Props> = ComponentType<Props> | false | null | undefined;\n\ntype UseBuildComponentCallbackOptions<Props> = {\n fallbackComponent?: ResultComponent<Props> | undefined;\n};\n\ninterface UseBuildComponentCallback<Request, Props> {\n (request: Request, options?: undefined | UseBuildComponentCallbackOptions<Props>): ComponentType<Props> | undefined;\n}\n\ntype ProviderContext<Request, Props> = {\n get enhancer(): ComponentEnhancer<Request, Props> | undefined;\n useBuildComponentCallback: UseBuildComponentCallback<Request, Props>;\n};\n\ntype ProviderProps<Request, Props, Init> = PropsWithChildren<{\n middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends object> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * However, middleware could modify the request object before calling its next middleware. It is recommended\n * to use Object.freeze() to prevent middleware from modifying the request object.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype AsMiddlewareProps<Request, Props, Init> = {\n readonly init: Init;\n readonly Next: ComponentType<Partial<Props>>;\n readonly request: Request;\n};\n\ntype AsMiddlewareComponentProps<Request, Props, Init> = Props & {\n readonly middleware: AsMiddlewareProps<Request, Props, Init>;\n};\n\ntype ChainOfResponsibility<Request, Props extends object, Init> = {\n readonly asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init>;\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly types: {\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly middlewareComponentProps: AsMiddlewareComponentProps<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly request: Request;\n };\n readonly useBuildComponentCallback: () => UseBuildComponentCallback<Request, Props>;\n};\n\nfunction createChainOfResponsibility<Request = void, Props extends object = { readonly children?: never }, Init = void>(\n options: CreateChainOfResponsibilityOptions = {}\n): ChainOfResponsibility<Request, Props, Init> {\n const defaultUseBuildComponentCallback: ProviderContext<Request, Props> = {\n get enhancer() {\n return undefined;\n },\n useBuildComponentCallback(_request, options): ComponentType<Props> {\n if (!options?.fallbackComponent) {\n throw new Error('This component/hook cannot be used outside of its corresponding <Provider>');\n }\n\n return options.fallbackComponent;\n }\n };\n\n const context = createContext<ProviderContext<Request, Props>>(defaultUseBuildComponentCallback);\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n // TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n // typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\n // After removing \"as unknown\", `middleware` on the next line become `any[]`.\n if (!Array.isArray(middleware as unknown) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('middleware prop must be an array of functions');\n }\n\n const patchedMiddleware: readonly ComponentMiddleware<Request, Props, Init>[] = Object.freeze(\n middleware\n ? middleware.map(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return (next: (request: Request) => ComponentType<Props> | false | null | undefined) =>\n (originalRequest: Request) => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error('next() cannot be called after the function had returned synchronously');\n }\n\n !options.passModifiedRequest &&\n nextRequest !== originalRequest &&\n console.warn(\n 'react-chain-of-responsibility: \"options.passModifiedRequest\" must be set to true to pass a different request object to next().'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n if (isValidElement(returnValue)) {\n throw new Error('middleware must not return React element directly');\n } else if (\n returnValue !== false &&\n returnValue !== null &&\n typeof returnValue !== 'undefined' &&\n !isReactComponent(returnValue)\n ) {\n throw new Error(\n 'middleware must return false, null, undefined, function component, or class component'\n );\n }\n\n return returnValue;\n };\n })\n : []\n );\n\n const { enhancer: parentEnhancer } = useContext(context);\n\n const enhancer = useMemo(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<ResultComponent<Props>, Request, Init>(\n ...[...patchedMiddleware, ...(parentEnhancer ? [() => parentEnhancer] : [])]\n )(init as Init),\n [init, middleware, parentEnhancer]\n );\n\n const useBuildComponentCallback = useCallback<UseBuildComponentCallback<Request, Props>>(\n (request, options = {}) => enhancer(() => options.fallbackComponent)(request) || undefined,\n [enhancer]\n );\n\n const contextValue = useMemo<ProviderContext<Request, Props>>(\n () => ({ enhancer, useBuildComponentCallback }),\n [enhancer, useBuildComponentCallback]\n );\n\n return <context.Provider value={contextValue}>{children}</context.Provider>;\n }\n\n const useBuildComponentCallback = () => useContext(context).useBuildComponentCallback;\n\n function Proxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const enhancer = useBuildComponentCallback();\n\n const Component = enhancer(request as Request, { fallbackComponent });\n\n return Component ? <Component {...(props as Props)} /> : null;\n }\n\n const asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init> =\n (\n MiddlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ): ComponentMiddleware<Request, Props, Init> =>\n init =>\n next =>\n request => {\n const RawNextComponent = next(request);\n\n // TODO: Can we pre-build this component during init?\n const MiddlewareOf = (props: Props) => {\n const middleware = useMemo(\n () =>\n Object.freeze({\n init,\n Next: memo<Partial<Props>>(\n RawNextComponent\n ? (overridingProps: Partial<Props>) => <RawNextComponent {...props} {...overridingProps} />\n : () => null\n ),\n request\n }),\n []\n );\n\n return <MiddlewareComponent {...props} middleware={middleware} />;\n };\n\n MiddlewareOf.displayName = `MiddlewareOf<${MiddlewareComponent.displayName || ''}>`;\n\n return memo<Props>(MiddlewareOf);\n };\n\n return Object.freeze({\n asMiddleware,\n Provider: memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider),\n Proxy: memo<ProxyProps<Request, Props>>(Proxy),\n types: Object.freeze({\n middlewareComponentProps: undefined as unknown as AsMiddlewareComponentProps<Request, Props, Init>,\n init: undefined as unknown as Init,\n middleware: undefined as unknown as ComponentMiddleware<Request, Props, Init>,\n props: undefined as unknown as Props,\n proxyProps: undefined as unknown as ProxyProps<Request, Props>,\n request: undefined as unknown as Request\n }),\n useBuildComponentCallback\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type CreateChainOfResponsibilityOptions,\n type ProxyProps,\n type UseBuildComponentCallback\n};\n","import {\n type ComponentClass,\n type ComponentType,\n type Consumer,\n type Fragment,\n type FunctionComponent,\n type Provider\n} from 'react';\nimport { custom } from 'valibot';\n\nfunction isConsumer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Consumer<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.context)';\n}\n\nfunction isProvider(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Provider<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.provider)';\n}\n\nfunction isFragment(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is typeof Fragment {\n return component?.toString() === 'Symbol(react.fragment)';\n}\n\nfunction isFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n if (typeof component === 'function') {\n return true;\n }\n\n return isPureFunctionComponent(component);\n}\n\nfunction isPureFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n return component?.$$typeof?.toString() === 'Symbol(react.memo)' && isFunctionComponent(component.type);\n}\n\nfunction isComponentClass(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentClass {\n return typeof component === 'object' && typeof component?.['render'] === 'function';\n}\n\n// There are no definitive ways to check if an object is a React component or not.\n// We are checking if the object has a render function (classic component).\n// Note: \"forwardRef()\" returns plain object, not class instance.\nfunction isReactComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentType {\n return (\n isFunctionComponent(component) ||\n isComponentClass(component) ||\n isFragment(component) ||\n isConsumer(component) ||\n isProvider(component)\n );\n}\n\nconst reactComponent = () =>\n custom<ComponentType<unknown>>(value => isReactComponent(value), 'not a valid React component');\n\nexport default isReactComponent;\nexport { reactComponent };\n"],"mappings":";AAAA,SAAS,uBAAuB;AAChC,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACFP,SAAS,cAAc;AAEvB,SAAS,WAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAAM;AAC7C;AAEA,SAAS,WAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAAM;AAC7C;AAEA,SAAS,WAEP,WAC8B;AAC9B,SAAO,WAAW,SAAS,MAAM;AACnC;AAEA,SAAS,oBAEP,WACgC;AAChC,MAAI,OAAO,cAAc,YAAY;AACnC,WAAO;AAAA,EACT;AAEA,SAAO,wBAAwB,SAAS;AAC1C;AAEA,SAAS,wBAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAAM,wBAAwB,oBAAoB,UAAU,IAAI;AACvG;AAEA,SAAS,iBAEP,WAC6B;AAC7B,SAAO,OAAO,cAAc,YAAY,OAAO,YAAY,QAAQ,MAAM;AAC3E;AAKA,SAAS,iBAEP,WAC4B;AAC5B,SACE,oBAAoB,SAAS,KAC7B,iBAAiB,SAAS,KAC1B,WAAW,SAAS,KACpB,WAAW,SAAS,KACpB,WAAW,SAAS;AAExB;AAKA,IAAO,2BAAQ;;;ADOf,SAAS,4BACP,UAA8C,CAAC,GACF;AAC7C,QAAM,mCAAoE;AAAA,IACxE,IAAI,WAAW;AACb,aAAO;AAAA,IACT;AAAA,IACA,0BAA0B,UAAUA,UAA+B;AACjE,UAAI,CAACA,UAAS,mBAAmB;AAC/B,cAAM,IAAI,MAAM,4EAA4E;AAAA,MAC9F;AAEA,aAAOA,SAAQ;AAAA,IACjB;AAAA,EACF;AAEA,QAAM,UAAU,c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;AAAA,MACZ,SAAS;AAAA,IACX,CAAC;AAAA,IACD;AAAA,EACF,CAAC;AACH;AAEA,IAAO,sCAAQ;","names":["options","middleware","init","enhancer","useBuildComponentCallback"]}
|
|
@@ -1,16 +1,12 @@
|
|
|
1
1
|
import { ComponentType, PropsWithChildren } from 'react';
|
|
2
|
+
import { Middleware } from 'handler-chain';
|
|
2
3
|
|
|
3
|
-
type
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
type ComponentResult<Props = {
|
|
5
|
+
children?: never;
|
|
6
|
+
}> = ComponentType<Props> | false | null | undefined;
|
|
7
7
|
type ComponentMiddleware<Request, Props = {
|
|
8
8
|
children?: never;
|
|
9
|
-
}, Init = undefined> = Middleware<
|
|
10
|
-
Request
|
|
11
|
-
], ComponentType<Props> | false | null | undefined, [
|
|
12
|
-
Init
|
|
13
|
-
]>;
|
|
9
|
+
}, Init = undefined> = Middleware<ComponentResult<Props>, Request, Init>;
|
|
14
10
|
|
|
15
11
|
type ResultComponent<Props> = ComponentType<Props> | false | null | undefined;
|
|
16
12
|
type UseBuildComponentCallbackOptions<Props> = {
|
|
@@ -1,16 +1,12 @@
|
|
|
1
1
|
import { ComponentType, PropsWithChildren } from 'react';
|
|
2
|
+
import { Middleware } from 'handler-chain';
|
|
2
3
|
|
|
3
|
-
type
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
type ComponentResult<Props = {
|
|
5
|
+
children?: never;
|
|
6
|
+
}> = ComponentType<Props> | false | null | undefined;
|
|
7
7
|
type ComponentMiddleware<Request, Props = {
|
|
8
8
|
children?: never;
|
|
9
|
-
}, Init = undefined> = Middleware<
|
|
10
|
-
Request
|
|
11
|
-
], ComponentType<Props> | false | null | undefined, [
|
|
12
|
-
Init
|
|
13
|
-
]>;
|
|
9
|
+
}, Init = undefined> = Middleware<ComponentResult<Props>, Request, Init>;
|
|
14
10
|
|
|
15
11
|
type ResultComponent<Props> = ComponentType<Props> | false | null | undefined;
|
|
16
12
|
type UseBuildComponentCallbackOptions<Props> = {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { IRenderFunction } from '@fluentui/react';
|
|
2
2
|
import { Key } from 'react';
|
|
3
|
-
import { C as CreateChainOfResponsibilityOptions, c as createChainOfResponsibility } from './index-
|
|
3
|
+
import { C as CreateChainOfResponsibilityOptions, c as createChainOfResponsibility } from './index-Dm_KqEiI.mjs';
|
|
4
|
+
import 'handler-chain';
|
|
4
5
|
|
|
5
6
|
type UseBuildRenderFunctionOptions<Props> = {
|
|
6
7
|
getKey?: (props: Props | undefined) => Key;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { IRenderFunction } from '@fluentui/react';
|
|
2
2
|
import { Key } from 'react';
|
|
3
|
-
import { C as CreateChainOfResponsibilityOptions, c as createChainOfResponsibility } from './index-
|
|
3
|
+
import { C as CreateChainOfResponsibilityOptions, c as createChainOfResponsibility } from './index-Dm_KqEiI.js';
|
|
4
|
+
import 'handler-chain';
|
|
4
5
|
|
|
5
6
|
type UseBuildRenderFunctionOptions<Props> = {
|
|
6
7
|
getKey?: (props: Props | undefined) => Key;
|
|
@@ -38,6 +38,7 @@ module.exports = __toCommonJS(index_fluentUI_exports);
|
|
|
38
38
|
var import_react2 = __toESM(require("react"));
|
|
39
39
|
|
|
40
40
|
// src/createChainOfResponsibility.tsx
|
|
41
|
+
var import_handler_chain = require("handler-chain");
|
|
41
42
|
var import_react = __toESM(require("react"));
|
|
42
43
|
|
|
43
44
|
// src/isReactComponent.ts
|
|
@@ -68,19 +69,6 @@ function isReactComponent(component) {
|
|
|
68
69
|
}
|
|
69
70
|
var isReactComponent_default = isReactComponent;
|
|
70
71
|
|
|
71
|
-
// src/private/compose.ts
|
|
72
|
-
function compose(...fns) {
|
|
73
|
-
return (fn) => fns.reduce((chain, fn2) => fn2(chain), fn);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// src/private/applyMiddleware.ts
|
|
77
|
-
function applyMiddleware(...arrayOfMiddleware) {
|
|
78
|
-
return (...init) => {
|
|
79
|
-
const chain = arrayOfMiddleware.map((middleware) => middleware(...init));
|
|
80
|
-
return compose(...chain);
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
|
|
84
72
|
// src/createChainOfResponsibility.tsx
|
|
85
73
|
function createChainOfResponsibility(options = {}) {
|
|
86
74
|
const defaultUseBuildComponentCallback = {
|
|
@@ -131,8 +119,8 @@ function createChainOfResponsibility(options = {}) {
|
|
|
131
119
|
// We are reversing because it is easier to read:
|
|
132
120
|
// - With reverse, [a, b, c] will become a(b(c(fn)))
|
|
133
121
|
// - Without reverse, [a, b, c] will become c(b(a(fn)))
|
|
134
|
-
applyMiddleware(
|
|
135
|
-
...[...patchedMiddleware, ...parentEnhancer ? [() => parentEnhancer] : []]
|
|
122
|
+
(0, import_handler_chain.applyMiddleware)(
|
|
123
|
+
...[...patchedMiddleware, ...parentEnhancer ? [() => parentEnhancer] : []]
|
|
136
124
|
)(init)
|
|
137
125
|
),
|
|
138
126
|
[init, middleware, parentEnhancer]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.fluentUI.ts","../src/createChainOfResponsibilityForFluentUI.tsx","../src/createChainOfResponsibility.tsx","../src/isReactComponent.ts","../src/private/compose.ts","../src/private/applyMiddleware.ts"],"sourcesContent":["// eslint-disable-next-line import/no-deprecated\nimport createChainOfResponsibilityForFluentUI from './createChainOfResponsibilityForFluentUI.tsx';\n\n// eslint-disable-next-line import/no-deprecated\nexport { createChainOfResponsibilityForFluentUI };\n","import { type IRenderFunction } from '@fluentui/react';\nimport React, { useCallback, type Key } from 'react';\n\nimport createChainOfResponsibility, {\n type CreateChainOfResponsibilityOptions\n} from './createChainOfResponsibility.tsx';\n\ntype UseBuildRenderFunctionOptions<Props> = { getKey?: (props: Props | undefined) => Key };\n\ntype UseBuildRenderFunction<Props> = (options?: UseBuildRenderFunctionOptions<Props>) => IRenderFunction<Props>;\n\n// We are using the props as both \"Request\" and \"Props\".\n// This should eases migration from `onRender` to chain of responsibility.\n// Downside is, web developers could accidentally pass request as props and not honoring props modified by upstreamers.\n\n/**\n * @deprecated Fluent UI v9 no longer use `IRenderFunction` for custom render. We no longer validate the correctness of this function.\n */\nexport default function createChainOfResponsibilityForFluentUI<Props extends object, Init = undefined>(\n options?: CreateChainOfResponsibilityOptions\n): ReturnType<typeof createChainOfResponsibility<Props | undefined, Props, Init>> & {\n useBuildRenderFunction: UseBuildRenderFunction<Props>;\n} {\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const returnValue = createChainOfResponsibility<Props | undefined, Props, Init>(options as any);\n\n const { Proxy } = returnValue;\n\n const useBuildRenderFunction: UseBuildRenderFunction<Props> = (options = {}) => {\n const { getKey } = options;\n\n return useCallback<IRenderFunction<Props>>(\n (props, defaultRender) => (\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n <Proxy {...(props as Props)} fallbackComponent={defaultRender as any} key={getKey?.(props)} request={props} />\n ),\n [getKey]\n );\n };\n\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { ...returnValue, useBuildRenderFunction } as any;\n}\n","import React, {\n createContext,\n isValidElement,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren\n} from 'react';\n\nimport isReactComponent from './isReactComponent.ts';\nimport applyMiddleware, { type Enhancer } from './private/applyMiddleware.ts';\nimport { type ComponentMiddleware } from './types.ts';\n\n// TODO: Simplify to ComponentType<Props> | undefined.\ntype ResultComponent<Props> = ComponentType<Props> | false | null | undefined;\n\ntype UseBuildComponentCallbackOptions<Props> = {\n fallbackComponent?: ResultComponent<Props> | undefined;\n};\n\ninterface UseBuildComponentCallback<Request, Props> {\n (request: Request, options?: undefined | UseBuildComponentCallbackOptions<Props>): ComponentType<Props> | undefined;\n}\n\ntype ProviderContext<Request, Props> = {\n get enhancer(): Enhancer<[Request], ResultComponent<Props>> | undefined;\n useBuildComponentCallback: UseBuildComponentCallback<Request, Props>;\n};\n\ntype ProviderProps<Request, Props, Init> = PropsWithChildren<{\n middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends object> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * However, middleware could modify the request object before calling its next middleware. It is recommended\n * to use Object.freeze() to prevent middleware from modifying the request object.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype AsMiddlewareProps<Request, Props, Init> = {\n readonly init: Init;\n readonly Next: ComponentType<Partial<Props>>;\n readonly request: Request;\n};\n\ntype AsMiddlewareComponentProps<Request, Props, Init> = Props & {\n readonly middleware: AsMiddlewareProps<Request, Props, Init>;\n};\n\ntype ChainOfResponsibility<Request, Props extends object, Init> = {\n readonly asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init>;\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly types: {\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly middlewareComponentProps: AsMiddlewareComponentProps<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly request: Request;\n };\n readonly useBuildComponentCallback: () => UseBuildComponentCallback<Request, Props>;\n};\n\nfunction createChainOfResponsibility<Request = void, Props extends object = { readonly children?: never }, Init = void>(\n options: CreateChainOfResponsibilityOptions = {}\n): ChainOfResponsibility<Request, Props, Init> {\n const defaultUseBuildComponentCallback: ProviderContext<Request, Props> = {\n get enhancer() {\n return undefined;\n },\n useBuildComponentCallback(_request, options): ComponentType<Props> {\n if (!options?.fallbackComponent) {\n throw new Error('This component/hook cannot be used outside of its corresponding <Provider>');\n }\n\n return options.fallbackComponent;\n }\n };\n\n const context = createContext<ProviderContext<Request, Props>>(defaultUseBuildComponentCallback);\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n // TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n // typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\n // After removing \"as unknown\", `middleware` on the next line become `any[]`.\n if (!Array.isArray(middleware as unknown) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('middleware prop must be an array of functions');\n }\n\n const patchedMiddleware: readonly ComponentMiddleware<Request, Props, Init>[] = Object.freeze(\n middleware\n ? middleware.map(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return (next: (request: Request) => ComponentType<Props> | false | null | undefined) =>\n (originalRequest: Request) => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error('next() cannot be called after the function had returned synchronously');\n }\n\n !options.passModifiedRequest &&\n nextRequest !== originalRequest &&\n console.warn(\n 'react-chain-of-responsibility: \"options.passModifiedRequest\" must be set to true to pass a different request object to next().'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n if (isValidElement(returnValue)) {\n throw new Error('middleware must not return React element directly');\n } else if (\n returnValue !== false &&\n returnValue !== null &&\n typeof returnValue !== 'undefined' &&\n !isReactComponent(returnValue)\n ) {\n throw new Error(\n 'middleware must return false, null, undefined, function component, or class component'\n );\n }\n\n return returnValue;\n };\n })\n : []\n );\n\n const { enhancer: parentEnhancer } = useContext(context);\n\n const enhancer = useMemo(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<[Request], ResultComponent<Props>, [Init]>(\n ...[...patchedMiddleware, ...(parentEnhancer ? [() => parentEnhancer] : [])].reverse()\n )(init as Init),\n [init, middleware, parentEnhancer]\n );\n\n const useBuildComponentCallback = useCallback<UseBuildComponentCallback<Request, Props>>(\n (request, options = {}) => enhancer(() => options.fallbackComponent)(request) || undefined,\n [enhancer]\n );\n\n const contextValue = useMemo<ProviderContext<Request, Props>>(\n () => ({ enhancer, useBuildComponentCallback }),\n [enhancer, useBuildComponentCallback]\n );\n\n return <context.Provider value={contextValue}>{children}</context.Provider>;\n }\n\n const useBuildComponentCallback = () => useContext(context).useBuildComponentCallback;\n\n function Proxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const enhancer = useBuildComponentCallback();\n\n const Component = enhancer(request as Request, { fallbackComponent });\n\n return Component ? <Component {...(props as Props)} /> : null;\n }\n\n const asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init> =\n (\n MiddlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ): ComponentMiddleware<Request, Props, Init> =>\n init =>\n next =>\n request => {\n const RawNextComponent = next(request);\n\n // TODO: Can we pre-build this component during init?\n const MiddlewareOf = (props: Props) => {\n const middleware = useMemo(\n () =>\n Object.freeze({\n init,\n Next: memo<Partial<Props>>(\n RawNextComponent\n ? (overridingProps: Partial<Props>) => <RawNextComponent {...props} {...overridingProps} />\n : () => null\n ),\n request\n }),\n []\n );\n\n return <MiddlewareComponent {...props} middleware={middleware} />;\n };\n\n MiddlewareOf.displayName = `MiddlewareOf<${MiddlewareComponent.displayName || ''}>`;\n\n return memo<Props>(MiddlewareOf);\n };\n\n return Object.freeze({\n asMiddleware,\n Provider: memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider),\n Proxy: memo<ProxyProps<Request, Props>>(Proxy),\n types: Object.freeze({\n middlewareComponentProps: undefined as unknown as AsMiddlewareComponentProps<Request, Props, Init>,\n init: undefined as unknown as Init,\n middleware: undefined as unknown as ComponentMiddleware<Request, Props, Init>,\n props: undefined as unknown as Props,\n proxyProps: undefined as unknown as ProxyProps<Request, Props>,\n request: undefined as unknown as Request\n }),\n useBuildComponentCallback\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type CreateChainOfResponsibilityOptions,\n type ProxyProps,\n type UseBuildComponentCallback\n};\n","import {\n type ComponentClass,\n type ComponentType,\n type Consumer,\n type Fragment,\n type FunctionComponent,\n type Provider\n} from 'react';\nimport { custom } from 'valibot';\n\nfunction isConsumer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Consumer<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.context)';\n}\n\nfunction isProvider(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Provider<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.provider)';\n}\n\nfunction isFragment(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is typeof Fragment {\n return component?.toString() === 'Symbol(react.fragment)';\n}\n\nfunction isFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n if (typeof component === 'function') {\n return true;\n }\n\n return isPureFunctionComponent(component);\n}\n\nfunction isPureFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n return component?.$$typeof?.toString() === 'Symbol(react.memo)' && isFunctionComponent(component.type);\n}\n\nfunction isComponentClass(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentClass {\n return typeof component === 'object' && typeof component?.['render'] === 'function';\n}\n\n// There are no definitive ways to check if an object is a React component or not.\n// We are checking if the object has a render function (classic component).\n// Note: \"forwardRef()\" returns plain object, not class instance.\nfunction isReactComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentType {\n return (\n isFunctionComponent(component) ||\n isComponentClass(component) ||\n isFragment(component) ||\n isConsumer(component) ||\n isProvider(component)\n );\n}\n\nconst reactComponent = () =>\n custom<ComponentType<unknown>>(value => isReactComponent(value), 'not a valid React component');\n\nexport default isReactComponent;\nexport { reactComponent };\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn<P extends any[], R> = (...args: P) => R;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function compose<P extends any[], R>(...fns: Enhancer<P, R>[]): Enhancer<P, R> {\n return (fn: Fn<P, R>): Fn<P, R> => fns.reduce((chain, fn) => fn(chain), fn);\n}\n","import compose from './compose.ts';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn<P extends any[], R> = (...args: P) => R;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Middleware<P extends any[], R, S extends any[]> = (...init: S) => Enhancer<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function applyMiddleware<P extends any[], R, S extends any[]>(\n ...arrayOfMiddleware: Middleware<P, R, S>[]\n) {\n return (...init: S) => {\n const chain = arrayOfMiddleware.map(middleware => middleware(...init));\n\n return compose(...chain);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAAA,gBAA6C;;;ACD7C,mBASO;;;ACDP,qBAAuB;AAEvB,SAAS,WAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAAM;AAC7C;AAEA,SAAS,WAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAA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C;AACH;AAEA,IAAO,sCAAQ;;;AD/NA,SAAR,uCACL,SAGA;AAGA,QAAM,cAAc,oCAA4D,OAAc;AAE9F,QAAM,EAAE,OAAAC,OAAM,IAAI;AAElB,QAAM,yBAAwD,CAACC,WAAU,CAAC,MAAM;AAC9E,UAAM,EAAE,OAAO,IAAIA;AAEnB,eAAO;AAAA,MACL,CAAC,OAAO;AAAA;AAAA;AAAA,QAGN,8BAAAC,QAAA,cAACF,QAAA,EAAO,GAAI,OAAiB,mBAAmB,eAAsB,KAAK,SAAS,KAAK,GAAG,SAAS,OAAO;AAAA;AAAA,MAE9G,CAAC,MAAM;AAAA,IACT;AAAA,EACF;AAIA,SAAO,EAAE,GAAG,aAAa,uBAAuB;AAClD;","names":["import_react","fn","options","middleware","init","enhancer","useBuildComponentCallback","React","Proxy","Proxy","options","React"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.fluentUI.ts","../src/createChainOfResponsibilityForFluentUI.tsx","../src/createChainOfResponsibility.tsx","../src/isReactComponent.ts"],"sourcesContent":["// eslint-disable-next-line import/no-deprecated\nimport createChainOfResponsibilityForFluentUI from './createChainOfResponsibilityForFluentUI.tsx';\n\n// eslint-disable-next-line import/no-deprecated\nexport { createChainOfResponsibilityForFluentUI };\n","import { type IRenderFunction } from '@fluentui/react';\nimport React, { useCallback, type Key } from 'react';\n\nimport createChainOfResponsibility, {\n type CreateChainOfResponsibilityOptions\n} from './createChainOfResponsibility.tsx';\n\ntype UseBuildRenderFunctionOptions<Props> = { getKey?: (props: Props | undefined) => Key };\n\ntype UseBuildRenderFunction<Props> = (options?: UseBuildRenderFunctionOptions<Props>) => IRenderFunction<Props>;\n\n// We are using the props as both \"Request\" and \"Props\".\n// This should eases migration from `onRender` to chain of responsibility.\n// Downside is, web developers could accidentally pass request as props and not honoring props modified by upstreamers.\n\n/**\n * @deprecated Fluent UI v9 no longer use `IRenderFunction` for custom render. We no longer validate the correctness of this function.\n */\nexport default function createChainOfResponsibilityForFluentUI<Props extends object, Init = undefined>(\n options?: CreateChainOfResponsibilityOptions\n): ReturnType<typeof createChainOfResponsibility<Props | undefined, Props, Init>> & {\n useBuildRenderFunction: UseBuildRenderFunction<Props>;\n} {\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const returnValue = createChainOfResponsibility<Props | undefined, Props, Init>(options as any);\n\n const { Proxy } = returnValue;\n\n const useBuildRenderFunction: UseBuildRenderFunction<Props> = (options = {}) => {\n const { getKey } = options;\n\n return useCallback<IRenderFunction<Props>>(\n (props, defaultRender) => (\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n <Proxy {...(props as Props)} fallbackComponent={defaultRender as any} key={getKey?.(props)} request={props} />\n ),\n [getKey]\n );\n };\n\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { ...returnValue, useBuildRenderFunction } as any;\n}\n","import { applyMiddleware } from 'handler-chain';\nimport React, {\n createContext,\n isValidElement,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren\n} from 'react';\n\nimport isReactComponent from './isReactComponent.ts';\nimport { type ComponentEnhancer, type ComponentMiddleware } from './types.ts';\n\n// TODO: Simplify to ComponentType<Props> | undefined.\ntype ResultComponent<Props> = ComponentType<Props> | false | null | undefined;\n\ntype UseBuildComponentCallbackOptions<Props> = {\n fallbackComponent?: ResultComponent<Props> | undefined;\n};\n\ninterface UseBuildComponentCallback<Request, Props> {\n (request: Request, options?: undefined | UseBuildComponentCallbackOptions<Props>): ComponentType<Props> | undefined;\n}\n\ntype ProviderContext<Request, Props> = {\n get enhancer(): ComponentEnhancer<Request, Props> | undefined;\n useBuildComponentCallback: UseBuildComponentCallback<Request, Props>;\n};\n\ntype ProviderProps<Request, Props, Init> = PropsWithChildren<{\n middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends object> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * However, middleware could modify the request object before calling its next middleware. It is recommended\n * to use Object.freeze() to prevent middleware from modifying the request object.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype AsMiddlewareProps<Request, Props, Init> = {\n readonly init: Init;\n readonly Next: ComponentType<Partial<Props>>;\n readonly request: Request;\n};\n\ntype AsMiddlewareComponentProps<Request, Props, Init> = Props & {\n readonly middleware: AsMiddlewareProps<Request, Props, Init>;\n};\n\ntype ChainOfResponsibility<Request, Props extends object, Init> = {\n readonly asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init>;\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly types: {\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly middlewareComponentProps: AsMiddlewareComponentProps<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly request: Request;\n };\n readonly useBuildComponentCallback: () => UseBuildComponentCallback<Request, Props>;\n};\n\nfunction createChainOfResponsibility<Request = void, Props extends object = { readonly children?: never }, Init = void>(\n options: CreateChainOfResponsibilityOptions = {}\n): ChainOfResponsibility<Request, Props, Init> {\n const defaultUseBuildComponentCallback: ProviderContext<Request, Props> = {\n get enhancer() {\n return undefined;\n },\n useBuildComponentCallback(_request, options): ComponentType<Props> {\n if (!options?.fallbackComponent) {\n throw new Error('This component/hook cannot be used outside of its corresponding <Provider>');\n }\n\n return options.fallbackComponent;\n }\n };\n\n const context = createContext<ProviderContext<Request, Props>>(defaultUseBuildComponentCallback);\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n // TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n // typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\n // After removing \"as unknown\", `middleware` on the next line become `any[]`.\n if (!Array.isArray(middleware as unknown) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('middleware prop must be an array of functions');\n }\n\n const patchedMiddleware: readonly ComponentMiddleware<Request, Props, Init>[] = Object.freeze(\n middleware\n ? middleware.map(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return (next: (request: Request) => ComponentType<Props> | false | null | undefined) =>\n (originalRequest: Request) => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error('next() cannot be called after the function had returned synchronously');\n }\n\n !options.passModifiedRequest &&\n nextRequest !== originalRequest &&\n console.warn(\n 'react-chain-of-responsibility: \"options.passModifiedRequest\" must be set to true to pass a different request object to next().'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n if (isValidElement(returnValue)) {\n throw new Error('middleware must not return React element directly');\n } else if (\n returnValue !== false &&\n returnValue !== null &&\n typeof returnValue !== 'undefined' &&\n !isReactComponent(returnValue)\n ) {\n throw new Error(\n 'middleware must return false, null, undefined, function component, or class component'\n );\n }\n\n return returnValue;\n };\n })\n : []\n );\n\n const { enhancer: parentEnhancer } = useContext(context);\n\n const enhancer = useMemo(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<ResultComponent<Props>, Request, Init>(\n ...[...patchedMiddleware, ...(parentEnhancer ? [() => parentEnhancer] : [])]\n )(init as Init),\n [init, middleware, parentEnhancer]\n );\n\n const useBuildComponentCallback = useCallback<UseBuildComponentCallback<Request, Props>>(\n (request, options = {}) => enhancer(() => options.fallbackComponent)(request) || undefined,\n [enhancer]\n );\n\n const contextValue = useMemo<ProviderContext<Request, Props>>(\n () => ({ enhancer, useBuildComponentCallback }),\n [enhancer, useBuildComponentCallback]\n );\n\n return <context.Provider value={contextValue}>{children}</context.Provider>;\n }\n\n const useBuildComponentCallback = () => useContext(context).useBuildComponentCallback;\n\n function Proxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const enhancer = useBuildComponentCallback();\n\n const Component = enhancer(request as Request, { fallbackComponent });\n\n return Component ? <Component {...(props as Props)} /> : null;\n }\n\n const asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init> =\n (\n MiddlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ): ComponentMiddleware<Request, Props, Init> =>\n init =>\n next =>\n request => {\n const RawNextComponent = next(request);\n\n // TODO: Can we pre-build this component during init?\n const MiddlewareOf = (props: Props) => {\n const middleware = useMemo(\n () =>\n Object.freeze({\n init,\n Next: memo<Partial<Props>>(\n RawNextComponent\n ? (overridingProps: Partial<Props>) => <RawNextComponent {...props} {...overridingProps} />\n : () => null\n ),\n request\n }),\n []\n );\n\n return <MiddlewareComponent {...props} middleware={middleware} />;\n };\n\n MiddlewareOf.displayName = `MiddlewareOf<${MiddlewareComponent.displayName || ''}>`;\n\n return memo<Props>(MiddlewareOf);\n };\n\n return Object.freeze({\n asMiddleware,\n Provider: memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider),\n Proxy: memo<ProxyProps<Request, Props>>(Proxy),\n types: Object.freeze({\n middlewareComponentProps: undefined as unknown as AsMiddlewareComponentProps<Request, Props, Init>,\n init: undefined as unknown as Init,\n middleware: undefined as unknown as ComponentMiddleware<Request, Props, Init>,\n props: undefined as unknown as Props,\n proxyProps: undefined as unknown as ProxyProps<Request, Props>,\n request: undefined as unknown as Request\n }),\n useBuildComponentCallback\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type CreateChainOfResponsibilityOptions,\n type ProxyProps,\n type UseBuildComponentCallback\n};\n","import {\n type ComponentClass,\n type ComponentType,\n type Consumer,\n type Fragment,\n type FunctionComponent,\n type Provider\n} from 'react';\nimport { custom } from 'valibot';\n\nfunction isConsumer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Consumer<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.context)';\n}\n\nfunction isProvider(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Provider<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.provider)';\n}\n\nfunction isFragment(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is typeof Fragment {\n return component?.toString() === 'Symbol(react.fragment)';\n}\n\nfunction isFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n if (typeof component === 'function') {\n return true;\n }\n\n return isPureFunctionComponent(component);\n}\n\nfunction isPureFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n return component?.$$typeof?.toString() === 'Symbol(react.memo)' && isFunctionComponent(component.type);\n}\n\nfunction isComponentClass(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentClass {\n return typeof component === 'object' && typeof component?.['render'] === 'function';\n}\n\n// There are no definitive ways to check if an object is a React component or not.\n// We are checking if the object has a render function (classic component).\n// Note: \"forwardRef()\" returns plain object, not class instance.\nfunction isReactComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentType {\n return (\n isFunctionComponent(component) ||\n isComponentClass(component) ||\n isFragment(component) ||\n isConsumer(component) ||\n isProvider(component)\n );\n}\n\nconst reactComponent = () =>\n custom<ComponentType<unknown>>(value => isReactComponent(value), 'not a valid React component');\n\nexport default isReactComponent;\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EA,IAAO,sCAAQ;;;AD/NA,SAAR,uCACL,SAGA;AAGA,QAAM,cAAc,oCAA4D,OAAc;AAE9F,QAAM,EAAE,OAAAC,OAAM,IAAI;AAElB,QAAM,yBAAwD,CAACC,WAAU,CAAC,MAAM;AAC9E,UAAM,EAAE,OAAO,IAAIA;AAEnB,eAAO;AAAA,MACL,CAAC,OAAO;AAAA;AAAA;AAAA,QAGN,8BAAAC,QAAA,cAACF,QAAA,EAAO,GAAI,OAAiB,mBAAmB,eAAsB,KAAK,SAAS,KAAK,GAAG,SAAS,OAAO;AAAA;AAAA,MAE9G,CAAC,MAAM;AAAA,IACT;AAAA,EACF;AAIA,SAAO,EAAE,GAAG,aAAa,uBAAuB;AAClD;","names":["import_react","options","middleware","init","enhancer","useBuildComponentCallback","React","Proxy","Proxy","options","React"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createChainOfResponsibilityForFluentUI.tsx"],"sourcesContent":["import { type IRenderFunction } from '@fluentui/react';\nimport React, { useCallback, type Key } from 'react';\n\nimport createChainOfResponsibility, {\n type CreateChainOfResponsibilityOptions\n} from './createChainOfResponsibility.tsx';\n\ntype UseBuildRenderFunctionOptions<Props> = { getKey?: (props: Props | undefined) => Key };\n\ntype UseBuildRenderFunction<Props> = (options?: UseBuildRenderFunctionOptions<Props>) => IRenderFunction<Props>;\n\n// We are using the props as both \"Request\" and \"Props\".\n// This should eases migration from `onRender` to chain of responsibility.\n// Downside is, web developers could accidentally pass request as props and not honoring props modified by upstreamers.\n\n/**\n * @deprecated Fluent UI v9 no longer use `IRenderFunction` for custom render. We no longer validate the correctness of this function.\n */\nexport default function createChainOfResponsibilityForFluentUI<Props extends object, Init = undefined>(\n options?: CreateChainOfResponsibilityOptions\n): ReturnType<typeof createChainOfResponsibility<Props | undefined, Props, Init>> & {\n useBuildRenderFunction: UseBuildRenderFunction<Props>;\n} {\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const returnValue = createChainOfResponsibility<Props | undefined, Props, Init>(options as any);\n\n const { Proxy } = returnValue;\n\n const useBuildRenderFunction: UseBuildRenderFunction<Props> = (options = {}) => {\n const { getKey } = options;\n\n return useCallback<IRenderFunction<Props>>(\n (props, defaultRender) => (\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n <Proxy {...(props as Props)} fallbackComponent={defaultRender as any} key={getKey?.(props)} request={props} />\n ),\n [getKey]\n );\n };\n\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { ...returnValue, useBuildRenderFunction } as any;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/createChainOfResponsibilityForFluentUI.tsx"],"sourcesContent":["import { type IRenderFunction } from '@fluentui/react';\nimport React, { useCallback, type Key } from 'react';\n\nimport createChainOfResponsibility, {\n type CreateChainOfResponsibilityOptions\n} from './createChainOfResponsibility.tsx';\n\ntype UseBuildRenderFunctionOptions<Props> = { getKey?: (props: Props | undefined) => Key };\n\ntype UseBuildRenderFunction<Props> = (options?: UseBuildRenderFunctionOptions<Props>) => IRenderFunction<Props>;\n\n// We are using the props as both \"Request\" and \"Props\".\n// This should eases migration from `onRender` to chain of responsibility.\n// Downside is, web developers could accidentally pass request as props and not honoring props modified by upstreamers.\n\n/**\n * @deprecated Fluent UI v9 no longer use `IRenderFunction` for custom render. We no longer validate the correctness of this function.\n */\nexport default function createChainOfResponsibilityForFluentUI<Props extends object, Init = undefined>(\n options?: CreateChainOfResponsibilityOptions\n): ReturnType<typeof createChainOfResponsibility<Props | undefined, Props, Init>> & {\n useBuildRenderFunction: UseBuildRenderFunction<Props>;\n} {\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const returnValue = createChainOfResponsibility<Props | undefined, Props, Init>(options as any);\n\n const { Proxy } = returnValue;\n\n const useBuildRenderFunction: UseBuildRenderFunction<Props> = (options = {}) => {\n const { getKey } = options;\n\n return useCallback<IRenderFunction<Props>>(\n (props, defaultRender) => (\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n <Proxy {...(props as Props)} fallbackComponent={defaultRender as any} key={getKey?.(props)} request={props} />\n ),\n [getKey]\n );\n };\n\n // We no longer validate the correctness of this function.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { ...returnValue, useBuildRenderFunction } as any;\n}\n"],"mappings":";;;;;AACA,OAAO,SAAS,mBAA6B;AAiB9B,SAAR,uCACL,SAGA;AAGA,QAAM,cAAc,oCAA4D,OAAc;AAE9F,QAAM,EAAE,MAAM,IAAI;AAElB,QAAM,yBAAwD,CAACA,WAAU,CAAC,MAAM;AAC9E,UAAM,EAAE,OAAO,IAAIA;AAEnB,WAAO;AAAA,MACL,CAAC,OAAO;AAAA;AAAA;AAAA,QAGN,oCAAC,SAAO,GAAI,OAAiB,mBAAmB,eAAsB,KAAK,SAAS,KAAK,GAAG,SAAS,OAAO;AAAA;AAAA,MAE9G,CAAC,MAAM;AAAA,IACT;AAAA,EACF;AAIA,SAAO,EAAE,GAAG,aAAa,uBAAuB;AAClD;","names":["options"]}
|
|
@@ -35,6 +35,7 @@ __export(src_exports, {
|
|
|
35
35
|
module.exports = __toCommonJS(src_exports);
|
|
36
36
|
|
|
37
37
|
// src/createChainOfResponsibility.tsx
|
|
38
|
+
var import_handler_chain = require("handler-chain");
|
|
38
39
|
var import_react = __toESM(require("react"));
|
|
39
40
|
|
|
40
41
|
// src/isReactComponent.ts
|
|
@@ -65,19 +66,6 @@ function isReactComponent(component) {
|
|
|
65
66
|
}
|
|
66
67
|
var isReactComponent_default = isReactComponent;
|
|
67
68
|
|
|
68
|
-
// src/private/compose.ts
|
|
69
|
-
function compose(...fns) {
|
|
70
|
-
return (fn) => fns.reduce((chain, fn2) => fn2(chain), fn);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// src/private/applyMiddleware.ts
|
|
74
|
-
function applyMiddleware(...arrayOfMiddleware) {
|
|
75
|
-
return (...init) => {
|
|
76
|
-
const chain = arrayOfMiddleware.map((middleware) => middleware(...init));
|
|
77
|
-
return compose(...chain);
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
|
|
81
69
|
// src/createChainOfResponsibility.tsx
|
|
82
70
|
function createChainOfResponsibility(options = {}) {
|
|
83
71
|
const defaultUseBuildComponentCallback = {
|
|
@@ -128,8 +116,8 @@ function createChainOfResponsibility(options = {}) {
|
|
|
128
116
|
// We are reversing because it is easier to read:
|
|
129
117
|
// - With reverse, [a, b, c] will become a(b(c(fn)))
|
|
130
118
|
// - Without reverse, [a, b, c] will become c(b(a(fn)))
|
|
131
|
-
applyMiddleware(
|
|
132
|
-
...[...patchedMiddleware, ...parentEnhancer ? [() => parentEnhancer] : []]
|
|
119
|
+
(0, import_handler_chain.applyMiddleware)(
|
|
120
|
+
...[...patchedMiddleware, ...parentEnhancer ? [() => parentEnhancer] : []]
|
|
133
121
|
)(init)
|
|
134
122
|
),
|
|
135
123
|
[init, middleware, parentEnhancer]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/createChainOfResponsibility.tsx","../src/isReactComponent.ts","../src/private/compose.ts","../src/private/applyMiddleware.ts"],"sourcesContent":["export { default as createChainOfResponsibility } from './createChainOfResponsibility.tsx';\nexport { type ComponentMiddleware } from './types.ts';\n","import React, {\n createContext,\n isValidElement,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren\n} from 'react';\n\nimport isReactComponent from './isReactComponent.ts';\nimport applyMiddleware, { type Enhancer } from './private/applyMiddleware.ts';\nimport { type ComponentMiddleware } from './types.ts';\n\n// TODO: Simplify to ComponentType<Props> | undefined.\ntype ResultComponent<Props> = ComponentType<Props> | false | null | undefined;\n\ntype UseBuildComponentCallbackOptions<Props> = {\n fallbackComponent?: ResultComponent<Props> | undefined;\n};\n\ninterface UseBuildComponentCallback<Request, Props> {\n (request: Request, options?: undefined | UseBuildComponentCallbackOptions<Props>): ComponentType<Props> | undefined;\n}\n\ntype ProviderContext<Request, Props> = {\n get enhancer(): Enhancer<[Request], ResultComponent<Props>> | undefined;\n useBuildComponentCallback: UseBuildComponentCallback<Request, Props>;\n};\n\ntype ProviderProps<Request, Props, Init> = PropsWithChildren<{\n middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends object> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * However, middleware could modify the request object before calling its next middleware. It is recommended\n * to use Object.freeze() to prevent middleware from modifying the request object.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype AsMiddlewareProps<Request, Props, Init> = {\n readonly init: Init;\n readonly Next: ComponentType<Partial<Props>>;\n readonly request: Request;\n};\n\ntype AsMiddlewareComponentProps<Request, Props, Init> = Props & {\n readonly middleware: AsMiddlewareProps<Request, Props, Init>;\n};\n\ntype ChainOfResponsibility<Request, Props extends object, Init> = {\n readonly asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init>;\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly types: {\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly middlewareComponentProps: AsMiddlewareComponentProps<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly request: Request;\n };\n readonly useBuildComponentCallback: () => UseBuildComponentCallback<Request, Props>;\n};\n\nfunction createChainOfResponsibility<Request = void, Props extends object = { readonly children?: never }, Init = void>(\n options: CreateChainOfResponsibilityOptions = {}\n): ChainOfResponsibility<Request, Props, Init> {\n const defaultUseBuildComponentCallback: ProviderContext<Request, Props> = {\n get enhancer() {\n return undefined;\n },\n useBuildComponentCallback(_request, options): ComponentType<Props> {\n if (!options?.fallbackComponent) {\n throw new Error('This component/hook cannot be used outside of its corresponding <Provider>');\n }\n\n return options.fallbackComponent;\n }\n };\n\n const context = createContext<ProviderContext<Request, Props>>(defaultUseBuildComponentCallback);\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n // TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n // typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\n // After removing \"as unknown\", `middleware` on the next line become `any[]`.\n if (!Array.isArray(middleware as unknown) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('middleware prop must be an array of functions');\n }\n\n const patchedMiddleware: readonly ComponentMiddleware<Request, Props, Init>[] = Object.freeze(\n middleware\n ? middleware.map(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return (next: (request: Request) => ComponentType<Props> | false | null | undefined) =>\n (originalRequest: Request) => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error('next() cannot be called after the function had returned synchronously');\n }\n\n !options.passModifiedRequest &&\n nextRequest !== originalRequest &&\n console.warn(\n 'react-chain-of-responsibility: \"options.passModifiedRequest\" must be set to true to pass a different request object to next().'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n if (isValidElement(returnValue)) {\n throw new Error('middleware must not return React element directly');\n } else if (\n returnValue !== false &&\n returnValue !== null &&\n typeof returnValue !== 'undefined' &&\n !isReactComponent(returnValue)\n ) {\n throw new Error(\n 'middleware must return false, null, undefined, function component, or class component'\n );\n }\n\n return returnValue;\n };\n })\n : []\n );\n\n const { enhancer: parentEnhancer } = useContext(context);\n\n const enhancer = useMemo(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<[Request], ResultComponent<Props>, [Init]>(\n ...[...patchedMiddleware, ...(parentEnhancer ? [() => parentEnhancer] : [])].reverse()\n )(init as Init),\n [init, middleware, parentEnhancer]\n );\n\n const useBuildComponentCallback = useCallback<UseBuildComponentCallback<Request, Props>>(\n (request, options = {}) => enhancer(() => options.fallbackComponent)(request) || undefined,\n [enhancer]\n );\n\n const contextValue = useMemo<ProviderContext<Request, Props>>(\n () => ({ enhancer, useBuildComponentCallback }),\n [enhancer, useBuildComponentCallback]\n );\n\n return <context.Provider value={contextValue}>{children}</context.Provider>;\n }\n\n const useBuildComponentCallback = () => useContext(context).useBuildComponentCallback;\n\n function Proxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const enhancer = useBuildComponentCallback();\n\n const Component = enhancer(request as Request, { fallbackComponent });\n\n return Component ? <Component {...(props as Props)} /> : null;\n }\n\n const asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init> =\n (\n MiddlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ): ComponentMiddleware<Request, Props, Init> =>\n init =>\n next =>\n request => {\n const RawNextComponent = next(request);\n\n // TODO: Can we pre-build this component during init?\n const MiddlewareOf = (props: Props) => {\n const middleware = useMemo(\n () =>\n Object.freeze({\n init,\n Next: memo<Partial<Props>>(\n RawNextComponent\n ? (overridingProps: Partial<Props>) => <RawNextComponent {...props} {...overridingProps} />\n : () => null\n ),\n request\n }),\n []\n );\n\n return <MiddlewareComponent {...props} middleware={middleware} />;\n };\n\n MiddlewareOf.displayName = `MiddlewareOf<${MiddlewareComponent.displayName || ''}>`;\n\n return memo<Props>(MiddlewareOf);\n };\n\n return Object.freeze({\n asMiddleware,\n Provider: memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider),\n Proxy: memo<ProxyProps<Request, Props>>(Proxy),\n types: Object.freeze({\n middlewareComponentProps: undefined as unknown as AsMiddlewareComponentProps<Request, Props, Init>,\n init: undefined as unknown as Init,\n middleware: undefined as unknown as ComponentMiddleware<Request, Props, Init>,\n props: undefined as unknown as Props,\n proxyProps: undefined as unknown as ProxyProps<Request, Props>,\n request: undefined as unknown as Request\n }),\n useBuildComponentCallback\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type CreateChainOfResponsibilityOptions,\n type ProxyProps,\n type UseBuildComponentCallback\n};\n","import {\n type ComponentClass,\n type ComponentType,\n type Consumer,\n type Fragment,\n type FunctionComponent,\n type Provider\n} from 'react';\nimport { custom } from 'valibot';\n\nfunction isConsumer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Consumer<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.context)';\n}\n\nfunction isProvider(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Provider<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.provider)';\n}\n\nfunction isFragment(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is typeof Fragment {\n return component?.toString() === 'Symbol(react.fragment)';\n}\n\nfunction isFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n if (typeof component === 'function') {\n return true;\n }\n\n return isPureFunctionComponent(component);\n}\n\nfunction isPureFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n return component?.$$typeof?.toString() === 'Symbol(react.memo)' && isFunctionComponent(component.type);\n}\n\nfunction isComponentClass(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentClass {\n return typeof component === 'object' && typeof component?.['render'] === 'function';\n}\n\n// There are no definitive ways to check if an object is a React component or not.\n// We are checking if the object has a render function (classic component).\n// Note: \"forwardRef()\" returns plain object, not class instance.\nfunction isReactComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentType {\n return (\n isFunctionComponent(component) ||\n isComponentClass(component) ||\n isFragment(component) ||\n isConsumer(component) ||\n isProvider(component)\n );\n}\n\nconst reactComponent = () =>\n custom<ComponentType<unknown>>(value => isReactComponent(value), 'not a valid React component');\n\nexport default isReactComponent;\nexport { reactComponent };\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn<P extends any[], R> = (...args: P) => R;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function compose<P extends any[], R>(...fns: Enhancer<P, R>[]): Enhancer<P, R> {\n return (fn: Fn<P, R>): Fn<P, R> => fns.reduce((chain, fn) => fn(chain), fn);\n}\n","import compose from './compose.ts';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn<P extends any[], R> = (...args: P) => R;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Middleware<P extends any[], R, S extends any[]> = (...init: S) => Enhancer<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function applyMiddleware<P extends any[], R, S extends any[]>(\n ...arrayOfMiddleware: Middleware<P, R, S>[]\n) {\n return (...init: S) => {\n const chain = arrayOfMiddleware.map(middleware => middleware(...init));\n\n return compose(...chain);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBASO;;;ACDP,qBAAuB;AAEvB,SAAS,WAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAA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A,MACP,YAAY;AAAA,MACZ,SAAS;AAAA,IACX,CAAC;AAAA,IACD;AAAA,EACF,CAAC;AACH;AAEA,IAAO,sCAAQ;","names":["fn","options","middleware","init","enhancer","useBuildComponentCallback","React","Proxy"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/createChainOfResponsibility.tsx","../src/isReactComponent.ts"],"sourcesContent":["export { default as createChainOfResponsibility } from './createChainOfResponsibility.tsx';\nexport { type ComponentMiddleware } from './types.ts';\n","import { applyMiddleware } from 'handler-chain';\nimport React, {\n createContext,\n isValidElement,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren\n} from 'react';\n\nimport isReactComponent from './isReactComponent.ts';\nimport { type ComponentEnhancer, type ComponentMiddleware } from './types.ts';\n\n// TODO: Simplify to ComponentType<Props> | undefined.\ntype ResultComponent<Props> = ComponentType<Props> | false | null | undefined;\n\ntype UseBuildComponentCallbackOptions<Props> = {\n fallbackComponent?: ResultComponent<Props> | undefined;\n};\n\ninterface UseBuildComponentCallback<Request, Props> {\n (request: Request, options?: undefined | UseBuildComponentCallbackOptions<Props>): ComponentType<Props> | undefined;\n}\n\ntype ProviderContext<Request, Props> = {\n get enhancer(): ComponentEnhancer<Request, Props> | undefined;\n useBuildComponentCallback: UseBuildComponentCallback<Request, Props>;\n};\n\ntype ProviderProps<Request, Props, Init> = PropsWithChildren<{\n middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends object> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * However, middleware could modify the request object before calling its next middleware. It is recommended\n * to use Object.freeze() to prevent middleware from modifying the request object.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype AsMiddlewareProps<Request, Props, Init> = {\n readonly init: Init;\n readonly Next: ComponentType<Partial<Props>>;\n readonly request: Request;\n};\n\ntype AsMiddlewareComponentProps<Request, Props, Init> = Props & {\n readonly middleware: AsMiddlewareProps<Request, Props, Init>;\n};\n\ntype ChainOfResponsibility<Request, Props extends object, Init> = {\n readonly asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init>;\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly types: {\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly middlewareComponentProps: AsMiddlewareComponentProps<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly request: Request;\n };\n readonly useBuildComponentCallback: () => UseBuildComponentCallback<Request, Props>;\n};\n\nfunction createChainOfResponsibility<Request = void, Props extends object = { readonly children?: never }, Init = void>(\n options: CreateChainOfResponsibilityOptions = {}\n): ChainOfResponsibility<Request, Props, Init> {\n const defaultUseBuildComponentCallback: ProviderContext<Request, Props> = {\n get enhancer() {\n return undefined;\n },\n useBuildComponentCallback(_request, options): ComponentType<Props> {\n if (!options?.fallbackComponent) {\n throw new Error('This component/hook cannot be used outside of its corresponding <Provider>');\n }\n\n return options.fallbackComponent;\n }\n };\n\n const context = createContext<ProviderContext<Request, Props>>(defaultUseBuildComponentCallback);\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n // TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n // typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\n // After removing \"as unknown\", `middleware` on the next line become `any[]`.\n if (!Array.isArray(middleware as unknown) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('middleware prop must be an array of functions');\n }\n\n const patchedMiddleware: readonly ComponentMiddleware<Request, Props, Init>[] = Object.freeze(\n middleware\n ? middleware.map(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return (next: (request: Request) => ComponentType<Props> | false | null | undefined) =>\n (originalRequest: Request) => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error('next() cannot be called after the function had returned synchronously');\n }\n\n !options.passModifiedRequest &&\n nextRequest !== originalRequest &&\n console.warn(\n 'react-chain-of-responsibility: \"options.passModifiedRequest\" must be set to true to pass a different request object to next().'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n if (isValidElement(returnValue)) {\n throw new Error('middleware must not return React element directly');\n } else if (\n returnValue !== false &&\n returnValue !== null &&\n typeof returnValue !== 'undefined' &&\n !isReactComponent(returnValue)\n ) {\n throw new Error(\n 'middleware must return false, null, undefined, function component, or class component'\n );\n }\n\n return returnValue;\n };\n })\n : []\n );\n\n const { enhancer: parentEnhancer } = useContext(context);\n\n const enhancer = useMemo(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<ResultComponent<Props>, Request, Init>(\n ...[...patchedMiddleware, ...(parentEnhancer ? [() => parentEnhancer] : [])]\n )(init as Init),\n [init, middleware, parentEnhancer]\n );\n\n const useBuildComponentCallback = useCallback<UseBuildComponentCallback<Request, Props>>(\n (request, options = {}) => enhancer(() => options.fallbackComponent)(request) || undefined,\n [enhancer]\n );\n\n const contextValue = useMemo<ProviderContext<Request, Props>>(\n () => ({ enhancer, useBuildComponentCallback }),\n [enhancer, useBuildComponentCallback]\n );\n\n return <context.Provider value={contextValue}>{children}</context.Provider>;\n }\n\n const useBuildComponentCallback = () => useContext(context).useBuildComponentCallback;\n\n function Proxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const enhancer = useBuildComponentCallback();\n\n const Component = enhancer(request as Request, { fallbackComponent });\n\n return Component ? <Component {...(props as Props)} /> : null;\n }\n\n const asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init> =\n (\n MiddlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ): ComponentMiddleware<Request, Props, Init> =>\n init =>\n next =>\n request => {\n const RawNextComponent = next(request);\n\n // TODO: Can we pre-build this component during init?\n const MiddlewareOf = (props: Props) => {\n const middleware = useMemo(\n () =>\n Object.freeze({\n init,\n Next: memo<Partial<Props>>(\n RawNextComponent\n ? (overridingProps: Partial<Props>) => <RawNextComponent {...props} {...overridingProps} />\n : () => null\n ),\n request\n }),\n []\n );\n\n return <MiddlewareComponent {...props} middleware={middleware} />;\n };\n\n MiddlewareOf.displayName = `MiddlewareOf<${MiddlewareComponent.displayName || ''}>`;\n\n return memo<Props>(MiddlewareOf);\n };\n\n return Object.freeze({\n asMiddleware,\n Provider: memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider),\n Proxy: memo<ProxyProps<Request, Props>>(Proxy),\n types: Object.freeze({\n middlewareComponentProps: undefined as unknown as AsMiddlewareComponentProps<Request, Props, Init>,\n init: undefined as unknown as Init,\n middleware: undefined as unknown as ComponentMiddleware<Request, Props, Init>,\n props: undefined as unknown as Props,\n proxyProps: undefined as unknown as ProxyProps<Request, Props>,\n request: undefined as unknown as Request\n }),\n useBuildComponentCallback\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type CreateChainOfResponsibilityOptions,\n type ProxyProps,\n type UseBuildComponentCallback\n};\n","import {\n type ComponentClass,\n type ComponentType,\n type Consumer,\n type Fragment,\n type FunctionComponent,\n type Provider\n} from 'react';\nimport { custom } from 'valibot';\n\nfunction isConsumer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Consumer<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.context)';\n}\n\nfunction isProvider(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Provider<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.provider)';\n}\n\nfunction isFragment(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is typeof Fragment {\n return component?.toString() === 'Symbol(react.fragment)';\n}\n\nfunction isFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n if (typeof component === 'function') {\n return true;\n }\n\n return isPureFunctionComponent(component);\n}\n\nfunction isPureFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n return component?.$$typeof?.toString() === 'Symbol(react.memo)' && isFunctionComponent(component.type);\n}\n\nfunction isComponentClass(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentClass {\n return typeof component === 'object' && typeof component?.['render'] === 'function';\n}\n\n// There are no definitive ways to check if an object is a React component or not.\n// We are checking if the object has a render function (classic component).\n// Note: \"forwardRef()\" returns plain object, not class instance.\nfunction isReactComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentType {\n return (\n isFunctionComponent(component) ||\n isComponentClass(component) ||\n isFragment(component) ||\n isConsumer(component) ||\n isProvider(component)\n );\n}\n\nconst reactComponent = () =>\n custom<ComponentType<unknown>>(value => isReactComponent(value), 'not a valid React component');\n\nexport default isReactComponent;\nexport { reactComponent };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,2BAAgC;AAChC,mBASO;;;ACFP,qBAAuB;AAEvB,SAAS,WAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAAM;AAC7C;AAEA,SAAS,WAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAAM;AAC7C;AA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AAM,YAAY,SAAS,SAAoB,EAAE,kBAAkB,CAAC;AAEpE,WAAO,YAAY,6BAAAD,QAAA,cAAC,aAAW,GAAI,OAAiB,IAAK;AAAA,EAC3D;AAEA,QAAM,eAGJ,CACE,wBAEF,UACA,UACA,aAAW;AACT,UAAM,mBAAmB,KAAK,OAAO;AAGrC,UAAM,eAAe,CAAC,UAAiB;AACrC,YAAM,iBAAa;AAAA,QACjB,MACE,OAAO,OAAO;AAAA,UACZ;AAAA,UACA,UAAM;AAAA,YACJ,mBACI,CAAC,oBAAoC,6BAAAA,QAAA,cAAC,oBAAkB,GAAG,OAAQ,GAAG,iBAAiB,IACvF,MAAM;AAAA,UACZ;AAAA,UACA;AAAA,QACF,CAAC;AAAA,QACH,CAAC;AAAA,MACH;AAEA,aAAO,6BAAAA,QAAA,cAAC,uBAAqB,GAAG,OAAO,YAAwB;AAAA,IACjE;AAEA,iBAAa,cAAc,gBAAgB,oBAAoB,eAAe,EAAE;AAEhF,eAAO,mBAAY,YAAY;AAAA,EACjC;AAEF,SAAO,OAAO,OAAO;AAAA,IACnB;AAAA,IACA,cAAU,mBAA0C,6BAA6B;AAAA,IACjF,WAAO,mBAAiCC,MAAK;AAAA,IAC7C,OAAO,OAAO,OAAO;AAAA,MACnB,0BAA0B;AAAA,MAC1B,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,OAAO;AAAA,MACP,YAAY;AAAA,MACZ,SAAS;AAAA,IACX,CAAC;AAAA,IACD;AAAA,EACF,CAAC;AACH;AAEA,IAAO,sCAAQ;","names":["options","middleware","init","enhancer","useBuildComponentCallback","React","Proxy"]}
|
|
@@ -6,7 +6,6 @@ declare global {
|
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
8
|
type BaseProps = object;
|
|
9
|
-
type RenderCallback<Props extends BaseProps> = (props: Props) => ReactNode;
|
|
10
9
|
type CreateChainOfResponsibilityOptions = {
|
|
11
10
|
/**
|
|
12
11
|
* Allows one component to pass different set of props to its downstream component. Default is false.
|
|
@@ -26,22 +25,24 @@ type CreateChainOfResponsibilityOptions = {
|
|
|
26
25
|
type ChainOfResponsibility<Request, Props extends BaseProps, Init> = {
|
|
27
26
|
readonly Provider: ComponentType<ProviderProps<Request, Props, Init>> & InferenceHelper<Request, Props, Init>;
|
|
28
27
|
readonly Proxy: ComponentType<ProxyProps<Request, Props>>;
|
|
29
|
-
readonly reactComponent: <
|
|
28
|
+
readonly reactComponent: ReactComponentHandlerResult<Props>;
|
|
30
29
|
readonly useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props>;
|
|
31
30
|
};
|
|
32
31
|
declare const DO_NOT_CREATE_THIS_OBJECT_YOURSELF: unique symbol;
|
|
33
|
-
|
|
32
|
+
type ComponentRenderer<Props> = (props: Props) => ReactNode;
|
|
33
|
+
interface ComponentHandlerResult<Props extends BaseProps> {
|
|
34
34
|
readonly [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined;
|
|
35
35
|
readonly render: (overridingProps?: Partial<Props> | undefined) => ReactNode;
|
|
36
36
|
}
|
|
37
|
-
type
|
|
38
|
-
type ComponentEnhancer<Request, Props extends BaseProps> = (next:
|
|
37
|
+
type ComponentHandler<Request, Props extends BaseProps> = (request: Request) => ComponentHandlerResult<Props> | undefined;
|
|
38
|
+
type ComponentEnhancer<Request, Props extends BaseProps> = (next: ComponentHandler<Request, Props>) => ComponentHandler<Request, Props>;
|
|
39
39
|
type ComponentMiddleware<Request, Props extends BaseProps, Init = undefined> = (init: Init) => ComponentEnhancer<Request, Props>;
|
|
40
|
+
type ReactComponentHandlerResult<Props extends object> = <P extends Props>(component: ComponentType<P>, bindProps?: (Partial<Props> & Omit<P, keyof Props>) | ((props: Props) => Partial<Props> & Omit<P, keyof Props>) | undefined) => ComponentHandlerResult<Props>;
|
|
40
41
|
type UseBuildRenderCallbackOptions<Props> = {
|
|
41
42
|
readonly fallbackComponent?: ComponentType<Props> | undefined;
|
|
42
43
|
};
|
|
43
44
|
interface UseBuildRenderCallback<Request, Props extends BaseProps> {
|
|
44
|
-
(request: Request, options?: undefined | UseBuildRenderCallbackOptions<Props>):
|
|
45
|
+
(request: Request, options?: undefined | UseBuildRenderCallbackOptions<Props>): ComponentRenderer<Props> | undefined;
|
|
45
46
|
}
|
|
46
47
|
type ProviderProps<Request, Props extends BaseProps, Init> = PropsWithChildren<{
|
|
47
48
|
readonly middleware: readonly ComponentMiddleware<Request, Props, Init>[];
|
|
@@ -58,16 +59,22 @@ type ProxyProps<Request, Props extends BaseProps> = Props & {
|
|
|
58
59
|
};
|
|
59
60
|
type InferenceHelper<Request, Props extends BaseProps, Init> = {
|
|
60
61
|
readonly '~types': {
|
|
61
|
-
readonly component: ComponentType<Props>;
|
|
62
62
|
readonly init: Init;
|
|
63
63
|
readonly middleware: ComponentMiddleware<Request, Props, Init>;
|
|
64
64
|
readonly props: Props;
|
|
65
65
|
readonly proxyProps: ProxyProps<Request, Props>;
|
|
66
|
+
readonly providerProps: ProviderProps<Request, Props, Init>;
|
|
66
67
|
readonly request: Request;
|
|
67
68
|
};
|
|
68
69
|
};
|
|
70
|
+
type InferInit<T extends InferenceHelper<any, any, any>> = T['~types']['init'];
|
|
71
|
+
type InferMiddleware<T extends InferenceHelper<any, any, any>> = T['~types']['middleware'];
|
|
72
|
+
type InferProps<T extends InferenceHelper<any, any, any>> = T['~types']['props'];
|
|
73
|
+
type InferProxyProps<T extends InferenceHelper<any, any, any>> = T['~types']['proxyProps'];
|
|
74
|
+
type InferProviderProps<T extends InferenceHelper<any, any, any>> = T['~types']['providerProps'];
|
|
75
|
+
type InferRequest<T extends InferenceHelper<any, any, any>> = T['~types']['request'];
|
|
69
76
|
declare function createChainOfResponsibility<Request = void, Props extends BaseProps = {
|
|
70
77
|
readonly children?: never;
|
|
71
78
|
}, Init = void>(options?: CreateChainOfResponsibilityOptions): ChainOfResponsibility<Request, Props, Init>;
|
|
72
79
|
|
|
73
|
-
export { createChainOfResponsibility };
|
|
80
|
+
export { type ChainOfResponsibility, type ComponentEnhancer, type ComponentHandler, type ComponentHandlerResult, type ComponentMiddleware, type ComponentRenderer, type CreateChainOfResponsibilityOptions, type InferInit, type InferMiddleware, type InferProps, type InferProviderProps, type InferProxyProps, type InferRequest, type InferenceHelper, type ProviderProps, type ProxyProps, type ReactComponentHandlerResult, type UseBuildRenderCallback, type UseBuildRenderCallbackOptions, createChainOfResponsibility };
|
|
@@ -6,7 +6,6 @@ declare global {
|
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
8
|
type BaseProps = object;
|
|
9
|
-
type RenderCallback<Props extends BaseProps> = (props: Props) => ReactNode;
|
|
10
9
|
type CreateChainOfResponsibilityOptions = {
|
|
11
10
|
/**
|
|
12
11
|
* Allows one component to pass different set of props to its downstream component. Default is false.
|
|
@@ -26,22 +25,24 @@ type CreateChainOfResponsibilityOptions = {
|
|
|
26
25
|
type ChainOfResponsibility<Request, Props extends BaseProps, Init> = {
|
|
27
26
|
readonly Provider: ComponentType<ProviderProps<Request, Props, Init>> & InferenceHelper<Request, Props, Init>;
|
|
28
27
|
readonly Proxy: ComponentType<ProxyProps<Request, Props>>;
|
|
29
|
-
readonly reactComponent: <
|
|
28
|
+
readonly reactComponent: ReactComponentHandlerResult<Props>;
|
|
30
29
|
readonly useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props>;
|
|
31
30
|
};
|
|
32
31
|
declare const DO_NOT_CREATE_THIS_OBJECT_YOURSELF: unique symbol;
|
|
33
|
-
|
|
32
|
+
type ComponentRenderer<Props> = (props: Props) => ReactNode;
|
|
33
|
+
interface ComponentHandlerResult<Props extends BaseProps> {
|
|
34
34
|
readonly [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined;
|
|
35
35
|
readonly render: (overridingProps?: Partial<Props> | undefined) => ReactNode;
|
|
36
36
|
}
|
|
37
|
-
type
|
|
38
|
-
type ComponentEnhancer<Request, Props extends BaseProps> = (next:
|
|
37
|
+
type ComponentHandler<Request, Props extends BaseProps> = (request: Request) => ComponentHandlerResult<Props> | undefined;
|
|
38
|
+
type ComponentEnhancer<Request, Props extends BaseProps> = (next: ComponentHandler<Request, Props>) => ComponentHandler<Request, Props>;
|
|
39
39
|
type ComponentMiddleware<Request, Props extends BaseProps, Init = undefined> = (init: Init) => ComponentEnhancer<Request, Props>;
|
|
40
|
+
type ReactComponentHandlerResult<Props extends object> = <P extends Props>(component: ComponentType<P>, bindProps?: (Partial<Props> & Omit<P, keyof Props>) | ((props: Props) => Partial<Props> & Omit<P, keyof Props>) | undefined) => ComponentHandlerResult<Props>;
|
|
40
41
|
type UseBuildRenderCallbackOptions<Props> = {
|
|
41
42
|
readonly fallbackComponent?: ComponentType<Props> | undefined;
|
|
42
43
|
};
|
|
43
44
|
interface UseBuildRenderCallback<Request, Props extends BaseProps> {
|
|
44
|
-
(request: Request, options?: undefined | UseBuildRenderCallbackOptions<Props>):
|
|
45
|
+
(request: Request, options?: undefined | UseBuildRenderCallbackOptions<Props>): ComponentRenderer<Props> | undefined;
|
|
45
46
|
}
|
|
46
47
|
type ProviderProps<Request, Props extends BaseProps, Init> = PropsWithChildren<{
|
|
47
48
|
readonly middleware: readonly ComponentMiddleware<Request, Props, Init>[];
|
|
@@ -58,16 +59,22 @@ type ProxyProps<Request, Props extends BaseProps> = Props & {
|
|
|
58
59
|
};
|
|
59
60
|
type InferenceHelper<Request, Props extends BaseProps, Init> = {
|
|
60
61
|
readonly '~types': {
|
|
61
|
-
readonly component: ComponentType<Props>;
|
|
62
62
|
readonly init: Init;
|
|
63
63
|
readonly middleware: ComponentMiddleware<Request, Props, Init>;
|
|
64
64
|
readonly props: Props;
|
|
65
65
|
readonly proxyProps: ProxyProps<Request, Props>;
|
|
66
|
+
readonly providerProps: ProviderProps<Request, Props, Init>;
|
|
66
67
|
readonly request: Request;
|
|
67
68
|
};
|
|
68
69
|
};
|
|
70
|
+
type InferInit<T extends InferenceHelper<any, any, any>> = T['~types']['init'];
|
|
71
|
+
type InferMiddleware<T extends InferenceHelper<any, any, any>> = T['~types']['middleware'];
|
|
72
|
+
type InferProps<T extends InferenceHelper<any, any, any>> = T['~types']['props'];
|
|
73
|
+
type InferProxyProps<T extends InferenceHelper<any, any, any>> = T['~types']['proxyProps'];
|
|
74
|
+
type InferProviderProps<T extends InferenceHelper<any, any, any>> = T['~types']['providerProps'];
|
|
75
|
+
type InferRequest<T extends InferenceHelper<any, any, any>> = T['~types']['request'];
|
|
69
76
|
declare function createChainOfResponsibility<Request = void, Props extends BaseProps = {
|
|
70
77
|
readonly children?: never;
|
|
71
78
|
}, Init = void>(options?: CreateChainOfResponsibilityOptions): ChainOfResponsibility<Request, Props, Init>;
|
|
72
79
|
|
|
73
|
-
export { createChainOfResponsibility };
|
|
80
|
+
export { type ChainOfResponsibility, type ComponentEnhancer, type ComponentHandler, type ComponentHandlerResult, type ComponentMiddleware, type ComponentRenderer, type CreateChainOfResponsibilityOptions, type InferInit, type InferMiddleware, type InferProps, type InferProviderProps, type InferProxyProps, type InferRequest, type InferenceHelper, type ProviderProps, type ProxyProps, type ReactComponentHandlerResult, type UseBuildRenderCallback, type UseBuildRenderCallbackOptions, createChainOfResponsibility };
|
|
@@ -34,24 +34,12 @@ __export(index_preview_exports, {
|
|
|
34
34
|
});
|
|
35
35
|
module.exports = __toCommonJS(index_preview_exports);
|
|
36
36
|
|
|
37
|
-
// src/createChainOfResponsibilityAsRenderCallback.tsx
|
|
37
|
+
// src/preview/createChainOfResponsibilityAsRenderCallback.tsx
|
|
38
|
+
var import_handler_chain = require("handler-chain");
|
|
38
39
|
var import_react2 = __toESM(require("react"));
|
|
39
40
|
var import_valibot = require("valibot");
|
|
40
41
|
|
|
41
|
-
// src/private/
|
|
42
|
-
function compose(...fns) {
|
|
43
|
-
return (fn) => fns.reduce((chain, fn2) => fn2(chain), fn);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// src/private/applyMiddleware.ts
|
|
47
|
-
function applyMiddleware(...arrayOfMiddleware) {
|
|
48
|
-
return (...init) => {
|
|
49
|
-
const chain = arrayOfMiddleware.map((middleware) => middleware(...init));
|
|
50
|
-
return compose(...chain);
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// src/private/arePropsEqual.ts
|
|
42
|
+
// src/preview/private/arePropsEqual.ts
|
|
55
43
|
function arePropsEqual(x, y) {
|
|
56
44
|
if (Object.is(x, y)) {
|
|
57
45
|
return true;
|
|
@@ -70,7 +58,7 @@ function arePropsEqual(x, y) {
|
|
|
70
58
|
return true;
|
|
71
59
|
}
|
|
72
60
|
|
|
73
|
-
// src/private/useMemoValueWithEquality.ts
|
|
61
|
+
// src/preview/private/useMemoValueWithEquality.ts
|
|
74
62
|
var import_react = require("react");
|
|
75
63
|
var NOT_INITIALIZED = Symbol();
|
|
76
64
|
function useMemoValueWithEquality(factory, equalityFn) {
|
|
@@ -83,9 +71,9 @@ function useMemoValueWithEquality(factory, equalityFn) {
|
|
|
83
71
|
return current;
|
|
84
72
|
}
|
|
85
73
|
|
|
86
|
-
// src/createChainOfResponsibilityAsRenderCallback.tsx
|
|
74
|
+
// src/preview/createChainOfResponsibilityAsRenderCallback.tsx
|
|
87
75
|
var DO_NOT_CREATE_THIS_OBJECT_YOURSELF = Symbol();
|
|
88
|
-
var
|
|
76
|
+
var componentHandlerResultSchema = (0, import_valibot.custom)(
|
|
89
77
|
(value) => (0, import_valibot.safeParse)((0, import_valibot.object)({ render: (0, import_valibot.function_)() }), value).success && !!value && typeof value === "object" && DO_NOT_CREATE_THIS_OBJECT_YOURSELF in value,
|
|
90
78
|
"react-chain-of-responsibility: middleware must return value constructed by reactComponent()"
|
|
91
79
|
);
|
|
@@ -148,7 +136,7 @@ function createChainOfResponsibility(options = {}) {
|
|
|
148
136
|
return;
|
|
149
137
|
}
|
|
150
138
|
return Object.freeze({
|
|
151
|
-
//
|
|
139
|
+
// Convert fallback component as renderer.
|
|
152
140
|
[DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: void 0,
|
|
153
141
|
render: () => (
|
|
154
142
|
// Currently, there are no ways to set `bindProps` to `fallbackComponent`.
|
|
@@ -192,7 +180,7 @@ function createChainOfResponsibility(options = {}) {
|
|
|
192
180
|
return next(options.passModifiedRequest ? nextRequest : originalRequest);
|
|
193
181
|
})(originalRequest);
|
|
194
182
|
hasReturned = true;
|
|
195
|
-
return returnValue && (0, import_valibot.parse)(
|
|
183
|
+
return returnValue && (0, import_valibot.parse)(componentHandlerResultSchema, returnValue);
|
|
196
184
|
};
|
|
197
185
|
})
|
|
198
186
|
),
|
|
@@ -204,8 +192,8 @@ function createChainOfResponsibility(options = {}) {
|
|
|
204
192
|
// We are reversing because it is easier to read:
|
|
205
193
|
// - With reverse, [a, b, c] will become a(b(c(fn)))
|
|
206
194
|
// - Without reverse, [a, b, c] will become c(b(a(fn)))
|
|
207
|
-
applyMiddleware(
|
|
208
|
-
...[...fortifiedMiddleware, ...[() => parentEnhancer]]
|
|
195
|
+
(0, import_handler_chain.applyMiddleware)(
|
|
196
|
+
...[...fortifiedMiddleware, ...[() => parentEnhancer]]
|
|
209
197
|
)(init)
|
|
210
198
|
),
|
|
211
199
|
[init, fortifiedMiddleware, parentEnhancer]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.preview.ts","../src/createChainOfResponsibilityAsRenderCallback.tsx","../src/private/compose.ts","../src/private/applyMiddleware.ts","../src/private/arePropsEqual.ts","../src/private/useMemoValueWithEquality.ts"],"sourcesContent":["export { default as createChainOfResponsibility } from './createChainOfResponsibilityAsRenderCallback.tsx';\n","import React, {\n createContext,\n Fragment,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren,\n type ReactNode\n} from 'react';\nimport { custom, function_, object, parse, safeParse } from 'valibot';\n\nimport applyMiddleware from './private/applyMiddleware.ts';\nimport arePropsEqual from './private/arePropsEqual.ts';\nimport useMemoValueWithEquality from './private/useMemoValueWithEquality.ts';\n\n// TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n// typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\ndeclare global {\n interface ArrayConstructor {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n isArray(arg: any): arg is readonly any[];\n }\n}\n\ntype BaseProps = object;\n\ntype RenderCallback<Props extends BaseProps> = (props: Props) => ReactNode;\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows one component to pass different set of props to its downstream component. Default is false.\n *\n * It is recommended to keep this settings as default to prevent newly added component from unexpectedly changing behavior of downstream components.\n */\n readonly allowOverrideProps?: boolean | undefined;\n\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * It is recommended to keep this settings as default ot prevent newly added middleware from unexpectedly changing behavior of downstream middleware.\n *\n * To prevent upstream middleware from modifying the request, the request object should be set to be immutable through `Object.freeze`.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype ChainOfResponsibility<Request, Props extends BaseProps, Init> = {\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>> & InferenceHelper<Request, Props, Init>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly reactComponent: <P extends Props>(\n component: ComponentType<P>,\n bindProps?:\n | (Partial<Props> & Omit<P, keyof Props>)\n | ((props: Props) => Partial<Props> & Omit<P, keyof Props>)\n | undefined\n ) => ComponentFunctorReturnValue<Props>;\n readonly useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props>;\n};\n\nconst DO_NOT_CREATE_THIS_OBJECT_YOURSELF = Symbol();\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst componentFunctorReturnValueSchema = custom<ComponentFunctorReturnValue<any>>(\n value =>\n safeParse(object({ render: function_() }), value).success &&\n !!value &&\n typeof value === 'object' &&\n DO_NOT_CREATE_THIS_OBJECT_YOURSELF in value,\n 'react-chain-of-responsibility: middleware must return value constructed by reactComponent()'\n);\n\ninterface ComponentFunctorReturnValue<Props extends BaseProps> {\n readonly [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined;\n readonly render: (overridingProps?: Partial<Props> | undefined) => ReactNode;\n}\n\ntype ComponentFunctor<Request, Props extends BaseProps> = (\n request: Request\n) => ComponentFunctorReturnValue<Props> | undefined;\n\ntype ComponentEnhancer<Request, Props extends BaseProps> = (\n next: ComponentFunctor<Request, Props>\n) => ComponentFunctor<Request, Props>;\n\ntype ComponentMiddleware<Request, Props extends BaseProps, Init = undefined> = (\n init: Init\n) => ComponentEnhancer<Request, Props>;\n\ntype UseBuildRenderCallbackOptions<Props> = {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n};\n\ninterface UseBuildRenderCallback<Request, Props extends BaseProps> {\n (request: Request, options?: undefined | UseBuildRenderCallbackOptions<Props>): RenderCallback<Props> | undefined;\n}\n\ntype BuildContextType<Request, Props extends BaseProps> = {\n readonly enhancer: ComponentEnhancer<Request, Props>;\n};\n\ntype RenderContextType<Props> = {\n readonly renderCallbackProps: Props;\n};\n\ntype ProviderProps<Request, Props extends BaseProps, Init> = PropsWithChildren<{\n readonly middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends BaseProps> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype InferenceHelper<Request, Props extends BaseProps, Init> = {\n readonly '~types': {\n readonly component: ComponentType<Props>;\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly request: Request;\n };\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferComponent<T extends InferenceHelper<any, any, any>> = T['~types']['component'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferInit<T extends InferenceHelper<any, any, any>> = T['~types']['init'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferMiddleware<T extends InferenceHelper<any, any, any>> = T['~types']['middleware'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProps<T extends InferenceHelper<any, any, any>> = T['~types']['props'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProxyProps<T extends InferenceHelper<any, any, any>> = T['~types']['proxyProps'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferRequest<T extends InferenceHelper<any, any, any>> = T['~types']['request'];\n\nfunction createChainOfResponsibility<\n Request = void,\n Props extends BaseProps = { readonly children?: never },\n Init = void\n>(options: CreateChainOfResponsibilityOptions = {}): ChainOfResponsibility<Request, Props, Init> {\n // Freeze options to prevent accidental change.\n options = Object.freeze({ ...options });\n\n const BuildContext = createContext<BuildContextType<Request, Props>>(\n Object.freeze({ enhancer: next => request => next(request) })\n );\n\n const RenderContext = createContext<RenderContextType<Props>>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new Proxy({} as any, {\n get() {\n // The following is assertion, there is no way to hit this line.\n /* istanbul ignore next */\n throw new Error(\n 'react-chain-of-responsibility: this hook cannot be used outside of <Proxy> and useBuildRenderCallback()'\n );\n }\n })\n );\n\n function reactComponent<P extends Props>(\n component: ComponentType<P>,\n bindProps?:\n | (Partial<Props> & Omit<P, keyof Props>)\n | ((props: Props) => Partial<Props> & Omit<P, keyof Props>)\n | undefined\n ): ComponentFunctorReturnValue<Props> {\n return Object.freeze({\n [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined,\n render: (overridingProps?: Partial<Props> | undefined) => (\n <ComponentWithProps\n bindProps={bindProps}\n component={component as ComponentType<Props>}\n overridingProps={overridingProps}\n />\n )\n });\n }\n\n const ComponentWithProps = memo(function ComponentWithProps({\n bindProps,\n component: Component,\n overridingProps\n }: {\n readonly bindProps?: Partial<Props> | ((props: Props) => Partial<Props>) | undefined;\n readonly component: ComponentType<Props>;\n readonly overridingProps?: Partial<Props> | undefined;\n }) {\n const { allowOverrideProps } = options;\n const { renderCallbackProps } = useContext(RenderContext);\n\n if (overridingProps && !arePropsEqual(overridingProps, renderCallbackProps) && !allowOverrideProps) {\n console.warn('react-chain-of-responsibility: \"allowOverrideProps\" must be set to true to override props');\n }\n\n const props = Object.freeze(\n allowOverrideProps ? { ...renderCallbackProps, ...overridingProps } : { ...renderCallbackProps }\n );\n\n return <Component {...props} {...(typeof bindProps === 'function' ? bindProps(props) : bindProps)} />;\n });\n\n const useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props> = () => {\n const { enhancer } = useContext(BuildContext);\n\n return useCallback(\n (request, buildOptions = {}) => {\n const result =\n // Put the \"fallbackComponent\" as the last one in the chain.\n enhancer(() => {\n const { fallbackComponent } = buildOptions;\n\n if (!fallbackComponent) {\n console.warn(\n 'react-chain-of-responsibility: the request has fall through all middleware, set \"fallbackComponent\" as a catchall',\n request\n );\n\n // For clarity, we are returning `undefined` instead of `() => undefined`.\n return;\n }\n\n return Object.freeze({\n // Mark fallback render callback as functor return value.\n [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined,\n render: () => (\n // Currently, there are no ways to set `bindProps` to `fallbackComponent`.\n // `fallbackComponent` do not need `overridingProps` because it is the last one in the chain, it would not have the next() function.\n <ComponentWithProps component={fallbackComponent} />\n )\n });\n })(request);\n\n return (\n result &&\n ((props: Props) => {\n const renderCallbackProps = useMemoValueWithEquality<Props>(() => props, arePropsEqual);\n\n const context = useMemo<RenderContextType<Props>>(\n () => Object.freeze({ renderCallbackProps }),\n [renderCallbackProps]\n );\n\n return <RenderContext.Provider value={context}>{result.render()}</RenderContext.Provider>;\n })\n );\n },\n [enhancer]\n );\n };\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n if (!Array.isArray(middleware) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('react-chain-of-responsibility: \"middleware\" prop must be an array of functions');\n }\n\n // Remap the middleware, so all inputs/outputs are validated.\n const fortifiedMiddleware = useMemo(\n () =>\n Object.freeze(\n middleware.map<ComponentMiddleware<Request, Props, Init>>(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return next => originalRequest => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error(\n 'react-chain-of-responsibility: next() cannot be called after the function had returned synchronously'\n );\n }\n\n // We do not allow passing void/undefined to next() because it would be confusing whether to keep the original request or pass an undefined.\n !options.passModifiedRequest &&\n !Object.is(nextRequest, originalRequest) &&\n console.warn(\n 'react-chain-of-responsibility: next() must be called with the original request, otherwise, set \"options.passModifiedRequest\" to true to pass a different request object downstream'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n // Make sure the return value is built using our helper function for forward-compatibility reason.\n return returnValue && parse(componentFunctorReturnValueSchema, returnValue);\n };\n })\n ),\n [middleware]\n );\n\n const { enhancer: parentEnhancer } = useContext(BuildContext);\n\n const enhancer = useMemo<ComponentEnhancer<Request, Props>>(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<[Request], ComponentFunctorReturnValue<Props> | undefined, [Init]>(\n ...[...fortifiedMiddleware, ...[() => parentEnhancer]].reverse()\n )(init as Init),\n [init, fortifiedMiddleware, parentEnhancer]\n );\n\n const contextValue = useMemo<BuildContextType<Request, Props>>(() => Object.freeze({ enhancer }), [enhancer]);\n\n return <BuildContext.Provider value={contextValue}>{children}</BuildContext.Provider>;\n }\n\n function ChainOfResponsibilityProxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const result = useBuildRenderCallback()(request, { fallbackComponent })?.(props as Props);\n\n return result ? <Fragment>{result}</Fragment> : null;\n }\n\n const MemoizedChainOfResponsibilityProvider =\n memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider);\n\n return Object.freeze({\n Provider: MemoizedChainOfResponsibilityProvider as typeof MemoizedChainOfResponsibilityProvider &\n InferenceHelper<Request, Props, Init>,\n Proxy: memo<ProxyProps<Request, Props>>(ChainOfResponsibilityProxy),\n reactComponent,\n useBuildRenderCallback\n\n // TODO: Consider adding back `asMiddleware`.\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type CreateChainOfResponsibilityOptions,\n type InferComponent,\n type InferInit,\n type InferMiddleware,\n type InferProps,\n type InferProxyProps,\n type InferRequest,\n type UseBuildRenderCallback\n};\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn<P extends any[], R> = (...args: P) => R;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function compose<P extends any[], R>(...fns: Enhancer<P, R>[]): Enhancer<P, R> {\n return (fn: Fn<P, R>): Fn<P, R> => fns.reduce((chain, fn) => fn(chain), fn);\n}\n","import compose from './compose.ts';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn<P extends any[], R> = (...args: P) => R;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Middleware<P extends any[], R, S extends any[]> = (...init: S) => Enhancer<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function applyMiddleware<P extends any[], R, S extends any[]>(\n ...arrayOfMiddleware: Middleware<P, R, S>[]\n) {\n return (...init: S) => {\n const chain = arrayOfMiddleware.map(middleware => middleware(...init));\n\n return compose(...chain);\n };\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function arePropsEqual<T extends Record<string, any>>(x: T, y: T): boolean {\n if (Object.is(x, y)) {\n return true;\n }\n\n const mapOfX = new Map(Object.entries(x));\n const mapOfY = new Map(Object.entries(y));\n\n if (mapOfX.size !== mapOfY.size) {\n return false;\n }\n\n const keys = new Set([...mapOfX.keys(), ...mapOfY.keys()]);\n\n for (const key of keys) {\n if (!Object.is(mapOfX.get(key), mapOfY.get(key))) {\n return false;\n }\n }\n\n return true;\n}\n","import { useEffect, useRef } from 'react';\n\nconst NOT_INITIALIZED = Symbol();\n\nexport default function useMemoValueWithEquality<T>(factory: () => T, equalityFn: (x: T, y: T) => boolean): T {\n const prevRef = useRef<T | typeof NOT_INITIALIZED>(NOT_INITIALIZED);\n const next: T = factory();\n const current: T = prevRef.current !== NOT_INITIALIZED && equalityFn(prevRef.current, next) ? prevRef.current : next;\n\n useEffect(() => {\n prevRef.current = current;\n });\n\n return current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAUO;AACP,qBAA4D;;;ACJ7C,SAAR,WAAgD,KAAuC;AAC5F,SAAO,CAAC,OAA2B,IAAI,OAAO,CAAC,OAAOC,QAAOA,IAAG,KAAK,GAAG,EAAE;AAC5E;;;ACGe,SAAR,mBACF,mBACH;AACA,SAAO,IAAI,SAAY;AACrB,UAAM,QAAQ,kBAAkB,IAAI,gBAAc,WAAW,GAAG,IAAI,CAAC;AAErE,WAAO,QAAQ,GAAG,KAAK;AAAA,EACzB;AACF;;;ACnBe,SAAR,cAA8D,GAAM,GAAe;AACxF,MAAI,OAAO,GAAG,GAAG,CAAC,GAAG;AACnB,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,IAAI,IAAI,OAAO,QAAQ,CAAC,CAAC;AACxC,QAAM,SAAS,IAAI,IAAI,OAAO,QAAQ,CAAC,CAAC;AAExC,MAAI,OAAO,SAAS,OAAO,MAAM;AAC/B,WAAO;AAAA,EACT;AAEA,QAAM,OAAO,oBAAI,IAAI,CAAC,GAAG,OAAO,KAAK,GAAG,GAAG,OAAO,KAAK,CAAC,CAAC;AAEzD,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EAAE,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC;AAE5G,WAAO,8BAAAJ,QAAA,cAAC,aAAa,UAAb,EAAsB,OAAO,gBAAe,QAAS;AAAA,EAC/D;AAEA,WAAS,2BAA2B,EAAE,mBAAmB,SAAS,GAAG,MAAM,GAA+B;AACxG,UAAM,SAAS,uBAAuB,EAAE,SAAS,EAAE,kBAAkB,CAAC,IAAI,KAAc;AAExF,WAAO,SAAS,8BAAAA,QAAA,cAAC,8BAAU,MAAO,IAAc;AAAA,EAClD;AAEA,QAAM,4CACJ,oBAA0C,6BAA6B;AAEzE,SAAO,OAAO,OAAO;AAAA,IACnB,UAAU;AAAA,IAEV,WAAO,oBAAiC,0BAA0B;AAAA,IAClE;AAAA,IACA;AAAA;AAAA,EAGF,CAAC;AACH;AAEA,IAAO,sDAAQ;","names":["import_react","fn","React","ComponentWithProps","middleware","init","enhancer"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.preview.ts","../src/preview/createChainOfResponsibilityAsRenderCallback.tsx","../src/preview/private/arePropsEqual.ts","../src/preview/private/useMemoValueWithEquality.ts"],"sourcesContent":["export {\n default as createChainOfResponsibility,\n type ChainOfResponsibility,\n type ComponentEnhancer,\n type ComponentHandler,\n type ComponentHandlerResult,\n type ComponentMiddleware,\n type ComponentRenderer,\n type CreateChainOfResponsibilityOptions,\n type InferenceHelper,\n type InferInit,\n type InferMiddleware,\n type InferProps,\n type InferProviderProps,\n type InferProxyProps,\n type InferRequest,\n type ProviderProps,\n type ProxyProps,\n type ReactComponentHandlerResult,\n type UseBuildRenderCallback,\n type UseBuildRenderCallbackOptions\n} from './preview/createChainOfResponsibilityAsRenderCallback.tsx';\n","import { applyMiddleware } from 'handler-chain';\nimport React, {\n createContext,\n Fragment,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren,\n type ReactNode\n} from 'react';\nimport { custom, function_, object, parse, safeParse } from 'valibot';\n\nimport arePropsEqual from './private/arePropsEqual.ts';\nimport useMemoValueWithEquality from './private/useMemoValueWithEquality.ts';\n\n// TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n// typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\ndeclare global {\n interface ArrayConstructor {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n isArray(arg: any): arg is readonly any[];\n }\n}\n\ntype BaseProps = object;\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows one component to pass different set of props to its downstream component. Default is false.\n *\n * It is recommended to keep this settings as default to prevent newly added component from unexpectedly changing behavior of downstream components.\n */\n readonly allowOverrideProps?: boolean | undefined;\n\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * It is recommended to keep this settings as default ot prevent newly added middleware from unexpectedly changing behavior of downstream middleware.\n *\n * To prevent upstream middleware from modifying the request, the request object should be set to be immutable through `Object.freeze`.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype ChainOfResponsibility<Request, Props extends BaseProps, Init> = {\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>> & InferenceHelper<Request, Props, Init>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly reactComponent: ReactComponentHandlerResult<Props>;\n readonly useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props>;\n};\n\n// TODO: Maybe this one should be local.\n// Verify that reactComponent() from an instance of CoR should throw error when used in another instance of CoR.\nconst DO_NOT_CREATE_THIS_OBJECT_YOURSELF = Symbol();\n\ntype ComponentRenderer<Props> = (props: Props) => ReactNode;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst componentHandlerResultSchema = custom<ComponentHandlerResult<any>>(\n value =>\n safeParse(object({ render: function_() }), value).success &&\n !!value &&\n typeof value === 'object' &&\n DO_NOT_CREATE_THIS_OBJECT_YOURSELF in value,\n 'react-chain-of-responsibility: middleware must return value constructed by reactComponent()'\n);\n\ninterface ComponentHandlerResult<Props extends BaseProps> {\n readonly [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined;\n readonly render: (overridingProps?: Partial<Props> | undefined) => ReactNode;\n}\n\ntype ComponentHandler<Request, Props extends BaseProps> = (\n request: Request\n) => ComponentHandlerResult<Props> | undefined;\n\ntype ComponentEnhancer<Request, Props extends BaseProps> = (\n next: ComponentHandler<Request, Props>\n) => ComponentHandler<Request, Props>;\n\ntype ComponentMiddleware<Request, Props extends BaseProps, Init = undefined> = (\n init: Init\n) => ComponentEnhancer<Request, Props>;\n\ntype ReactComponentHandlerResult<Props extends object> = <P extends Props>(\n component: ComponentType<P>,\n bindProps?:\n | (Partial<Props> & Omit<P, keyof Props>)\n | ((props: Props) => Partial<Props> & Omit<P, keyof Props>)\n | undefined\n) => ComponentHandlerResult<Props>;\n\ntype UseBuildRenderCallbackOptions<Props> = {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n};\n\ninterface UseBuildRenderCallback<Request, Props extends BaseProps> {\n (request: Request, options?: undefined | UseBuildRenderCallbackOptions<Props>): ComponentRenderer<Props> | undefined;\n}\n\ntype BuildContextType<Request, Props extends BaseProps> = {\n readonly enhancer: ComponentEnhancer<Request, Props>;\n};\n\ntype RenderContextType<Props> = {\n readonly renderCallbackProps: Props;\n};\n\ntype ProviderProps<Request, Props extends BaseProps, Init> = PropsWithChildren<{\n readonly middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends BaseProps> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype InferenceHelper<Request, Props extends BaseProps, Init> = {\n readonly '~types': {\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly providerProps: ProviderProps<Request, Props, Init>;\n readonly request: Request;\n };\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferInit<T extends InferenceHelper<any, any, any>> = T['~types']['init'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferMiddleware<T extends InferenceHelper<any, any, any>> = T['~types']['middleware'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProps<T extends InferenceHelper<any, any, any>> = T['~types']['props'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProxyProps<T extends InferenceHelper<any, any, any>> = T['~types']['proxyProps'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProviderProps<T extends InferenceHelper<any, any, any>> = T['~types']['providerProps'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferRequest<T extends InferenceHelper<any, any, any>> = T['~types']['request'];\n\nfunction createChainOfResponsibility<\n Request = void,\n Props extends BaseProps = { readonly children?: never },\n Init = void\n>(options: CreateChainOfResponsibilityOptions = {}): ChainOfResponsibility<Request, Props, Init> {\n // Freeze options to prevent accidental change.\n options = Object.freeze({ ...options });\n\n const BuildContext = createContext<BuildContextType<Request, Props>>(\n Object.freeze({ enhancer: next => request => next(request) })\n );\n\n const RenderContext = createContext<RenderContextType<Props>>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new Proxy({} as any, {\n get() {\n // The following is assertion, there is no way to hit this line.\n /* istanbul ignore next */\n throw new Error(\n 'react-chain-of-responsibility: this hook cannot be used outside of <Proxy> and useBuildRenderCallback()'\n );\n }\n })\n );\n\n function reactComponent<P extends Props>(\n component: ComponentType<P>,\n bindProps?:\n | (Partial<Props> & Omit<P, keyof Props>)\n | ((props: Props) => Partial<Props> & Omit<P, keyof Props>)\n | undefined\n ): ComponentHandlerResult<Props> {\n return Object.freeze({\n [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined,\n render: (overridingProps?: Partial<Props> | undefined) => (\n <ComponentWithProps\n bindProps={bindProps}\n component={component as ComponentType<Props>}\n overridingProps={overridingProps}\n />\n )\n });\n }\n\n const ComponentWithProps = memo(function ComponentWithProps({\n bindProps,\n component: Component,\n overridingProps\n }: {\n readonly bindProps?: Partial<Props> | ((props: Props) => Partial<Props>) | undefined;\n readonly component: ComponentType<Props>;\n readonly overridingProps?: Partial<Props> | undefined;\n }) {\n const { allowOverrideProps } = options;\n const { renderCallbackProps } = useContext(RenderContext);\n\n if (overridingProps && !arePropsEqual(overridingProps, renderCallbackProps) && !allowOverrideProps) {\n console.warn('react-chain-of-responsibility: \"allowOverrideProps\" must be set to true to override props');\n }\n\n const props = Object.freeze(\n allowOverrideProps ? { ...renderCallbackProps, ...overridingProps } : { ...renderCallbackProps }\n );\n\n return <Component {...props} {...(typeof bindProps === 'function' ? bindProps(props) : bindProps)} />;\n });\n\n const useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props> = () => {\n const { enhancer } = useContext(BuildContext);\n\n return useCallback(\n (request, buildOptions = {}) => {\n const result =\n // Put the \"fallbackComponent\" as the last one in the chain.\n enhancer(() => {\n const { fallbackComponent } = buildOptions;\n\n if (!fallbackComponent) {\n console.warn(\n 'react-chain-of-responsibility: the request has fall through all middleware, set \"fallbackComponent\" as a catchall',\n request\n );\n\n // For clarity, we are returning `undefined` instead of `() => undefined`.\n return;\n }\n\n return Object.freeze({\n // Convert fallback component as renderer.\n [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined,\n render: () => (\n // Currently, there are no ways to set `bindProps` to `fallbackComponent`.\n // `fallbackComponent` do not need `overridingProps` because it is the last one in the chain, it would not have the next() function.\n <ComponentWithProps component={fallbackComponent} />\n )\n });\n })(request);\n\n return (\n result &&\n ((props: Props) => {\n const renderCallbackProps = useMemoValueWithEquality<Props>(() => props, arePropsEqual);\n\n const context = useMemo<RenderContextType<Props>>(\n () => Object.freeze({ renderCallbackProps }),\n [renderCallbackProps]\n );\n\n return <RenderContext.Provider value={context}>{result.render()}</RenderContext.Provider>;\n })\n );\n },\n [enhancer]\n );\n };\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n if (!Array.isArray(middleware) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('react-chain-of-responsibility: \"middleware\" prop must be an array of functions');\n }\n\n // Remap the middleware, so all inputs/outputs are validated.\n const fortifiedMiddleware = useMemo(\n () =>\n Object.freeze(\n middleware.map<ComponentMiddleware<Request, Props, Init>>(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return next => originalRequest => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error(\n 'react-chain-of-responsibility: next() cannot be called after the function had returned synchronously'\n );\n }\n\n // We do not allow passing void/undefined to next() because it would be confusing whether to keep the original request or pass an undefined.\n !options.passModifiedRequest &&\n !Object.is(nextRequest, originalRequest) &&\n console.warn(\n 'react-chain-of-responsibility: next() must be called with the original request, otherwise, set \"options.passModifiedRequest\" to true to pass a different request object downstream'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n // Make sure the return value is built using our helper function for forward-compatibility reason.\n return returnValue && parse(componentHandlerResultSchema, returnValue);\n };\n })\n ),\n [middleware]\n );\n\n const { enhancer: parentEnhancer } = useContext(BuildContext);\n\n const enhancer = useMemo<ComponentEnhancer<Request, Props>>(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<ComponentHandlerResult<Props> | undefined, Request, Init>(\n ...[...fortifiedMiddleware, ...[() => parentEnhancer]]\n )(init as Init),\n [init, fortifiedMiddleware, parentEnhancer]\n );\n\n const contextValue = useMemo<BuildContextType<Request, Props>>(() => Object.freeze({ enhancer }), [enhancer]);\n\n return <BuildContext.Provider value={contextValue}>{children}</BuildContext.Provider>;\n }\n\n function ChainOfResponsibilityProxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const result = useBuildRenderCallback()(request, { fallbackComponent })?.(props as Props);\n\n return result ? <Fragment>{result}</Fragment> : null;\n }\n\n const MemoizedChainOfResponsibilityProvider =\n memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider);\n\n return Object.freeze({\n Provider: MemoizedChainOfResponsibilityProvider as typeof MemoizedChainOfResponsibilityProvider &\n InferenceHelper<Request, Props, Init>,\n Proxy: memo<ProxyProps<Request, Props>>(ChainOfResponsibilityProxy),\n reactComponent,\n useBuildRenderCallback\n\n // TODO: Consider adding back `asMiddleware`.\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type ComponentEnhancer,\n type ComponentHandler,\n type ComponentHandlerResult,\n type ComponentMiddleware,\n type ComponentRenderer,\n type CreateChainOfResponsibilityOptions,\n type InferenceHelper,\n type InferInit,\n type InferMiddleware,\n type InferProps,\n type InferProviderProps,\n type InferProxyProps,\n type InferRequest,\n type ProviderProps,\n type ProxyProps,\n type ReactComponentHandlerResult,\n type UseBuildRenderCallback,\n type UseBuildRenderCallbackOptions\n};\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function arePropsEqual<T extends Record<string, any>>(x: T, y: T): boolean {\n if (Object.is(x, y)) {\n return true;\n }\n\n const mapOfX = new Map(Object.entries(x));\n const mapOfY = new Map(Object.entries(y));\n\n if (mapOfX.size !== mapOfY.size) {\n return false;\n }\n\n const keys = new Set([...mapOfX.keys(), ...mapOfY.keys()]);\n\n for (const key of keys) {\n if (!Object.is(mapOfX.get(key), mapOfY.get(key))) {\n return false;\n }\n }\n\n return true;\n}\n","import { useEffect, useRef } from 'react';\n\nconst NOT_INITIALIZED = Symbol();\n\nexport default function useMemoValueWithEquality<T>(factory: () => T, equalityFn: (x: T, y: T) => boolean): T {\n const prevRef = useRef<T | typeof NOT_INITIALIZED>(NOT_INITIALIZED);\n const next: T = factory();\n const current: T = prevRef.current !== NOT_INITIALIZED && equalityFn(prevRef.current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sRenderCallback.tsx
|
|
1
|
+
// src/preview/createChainOfResponsibilityAsRenderCallback.tsx
|
|
2
|
+
import { applyMiddleware } from "handler-chain";
|
|
6
3
|
import React, {
|
|
7
4
|
createContext,
|
|
8
5
|
Fragment,
|
|
@@ -13,7 +10,7 @@ import React, {
|
|
|
13
10
|
} from "react";
|
|
14
11
|
import { custom, function_, object, parse, safeParse } from "valibot";
|
|
15
12
|
|
|
16
|
-
// src/private/arePropsEqual.ts
|
|
13
|
+
// src/preview/private/arePropsEqual.ts
|
|
17
14
|
function arePropsEqual(x, y) {
|
|
18
15
|
if (Object.is(x, y)) {
|
|
19
16
|
return true;
|
|
@@ -32,7 +29,7 @@ function arePropsEqual(x, y) {
|
|
|
32
29
|
return true;
|
|
33
30
|
}
|
|
34
31
|
|
|
35
|
-
// src/private/useMemoValueWithEquality.ts
|
|
32
|
+
// src/preview/private/useMemoValueWithEquality.ts
|
|
36
33
|
import { useEffect, useRef } from "react";
|
|
37
34
|
var NOT_INITIALIZED = Symbol();
|
|
38
35
|
function useMemoValueWithEquality(factory, equalityFn) {
|
|
@@ -45,9 +42,9 @@ function useMemoValueWithEquality(factory, equalityFn) {
|
|
|
45
42
|
return current;
|
|
46
43
|
}
|
|
47
44
|
|
|
48
|
-
// src/createChainOfResponsibilityAsRenderCallback.tsx
|
|
45
|
+
// src/preview/createChainOfResponsibilityAsRenderCallback.tsx
|
|
49
46
|
var DO_NOT_CREATE_THIS_OBJECT_YOURSELF = Symbol();
|
|
50
|
-
var
|
|
47
|
+
var componentHandlerResultSchema = custom(
|
|
51
48
|
(value) => safeParse(object({ render: function_() }), value).success && !!value && typeof value === "object" && DO_NOT_CREATE_THIS_OBJECT_YOURSELF in value,
|
|
52
49
|
"react-chain-of-responsibility: middleware must return value constructed by reactComponent()"
|
|
53
50
|
);
|
|
@@ -110,7 +107,7 @@ function createChainOfResponsibility(options = {}) {
|
|
|
110
107
|
return;
|
|
111
108
|
}
|
|
112
109
|
return Object.freeze({
|
|
113
|
-
//
|
|
110
|
+
// Convert fallback component as renderer.
|
|
114
111
|
[DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: void 0,
|
|
115
112
|
render: () => (
|
|
116
113
|
// Currently, there are no ways to set `bindProps` to `fallbackComponent`.
|
|
@@ -154,7 +151,7 @@ function createChainOfResponsibility(options = {}) {
|
|
|
154
151
|
return next(options.passModifiedRequest ? nextRequest : originalRequest);
|
|
155
152
|
})(originalRequest);
|
|
156
153
|
hasReturned = true;
|
|
157
|
-
return returnValue && parse(
|
|
154
|
+
return returnValue && parse(componentHandlerResultSchema, returnValue);
|
|
158
155
|
};
|
|
159
156
|
})
|
|
160
157
|
),
|
|
@@ -167,7 +164,7 @@ function createChainOfResponsibility(options = {}) {
|
|
|
167
164
|
// - With reverse, [a, b, c] will become a(b(c(fn)))
|
|
168
165
|
// - Without reverse, [a, b, c] will become c(b(a(fn)))
|
|
169
166
|
applyMiddleware(
|
|
170
|
-
...[...fortifiedMiddleware, ...[() => parentEnhancer]]
|
|
167
|
+
...[...fortifiedMiddleware, ...[() => parentEnhancer]]
|
|
171
168
|
)(init)
|
|
172
169
|
),
|
|
173
170
|
[init, fortifiedMiddleware, parentEnhancer]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createChainOfResponsibilityAsRenderCallback.tsx","../src/private/arePropsEqual.ts","../src/private/useMemoValueWithEquality.ts"],"sourcesContent":["import React, {\n createContext,\n Fragment,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren,\n type ReactNode\n} from 'react';\nimport { custom, function_, object, parse, safeParse } from 'valibot';\n\nimport applyMiddleware from './private/applyMiddleware.ts';\nimport arePropsEqual from './private/arePropsEqual.ts';\nimport useMemoValueWithEquality from './private/useMemoValueWithEquality.ts';\n\n// TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n// typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\ndeclare global {\n interface ArrayConstructor {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n isArray(arg: any): arg is readonly any[];\n }\n}\n\ntype BaseProps = object;\n\ntype RenderCallback<Props extends BaseProps> = (props: Props) => ReactNode;\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows one component to pass different set of props to its downstream component. Default is false.\n *\n * It is recommended to keep this settings as default to prevent newly added component from unexpectedly changing behavior of downstream components.\n */\n readonly allowOverrideProps?: boolean | undefined;\n\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * It is recommended to keep this settings as default ot prevent newly added middleware from unexpectedly changing behavior of downstream middleware.\n *\n * To prevent upstream middleware from modifying the request, the request object should be set to be immutable through `Object.freeze`.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype ChainOfResponsibility<Request, Props extends BaseProps, Init> = {\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>> & InferenceHelper<Request, Props, Init>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly reactComponent: <P extends Props>(\n component: ComponentType<P>,\n bindProps?:\n | (Partial<Props> & Omit<P, keyof Props>)\n | ((props: Props) => Partial<Props> & Omit<P, keyof Props>)\n | undefined\n ) => ComponentFunctorReturnValue<Props>;\n readonly useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props>;\n};\n\nconst DO_NOT_CREATE_THIS_OBJECT_YOURSELF = Symbol();\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst componentFunctorReturnValueSchema = custom<ComponentFunctorReturnValue<any>>(\n value =>\n safeParse(object({ render: function_() }), value).success &&\n !!value &&\n typeof value === 'object' &&\n DO_NOT_CREATE_THIS_OBJECT_YOURSELF in value,\n 'react-chain-of-responsibility: middleware must return value constructed by reactComponent()'\n);\n\ninterface ComponentFunctorReturnValue<Props extends BaseProps> {\n readonly [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined;\n readonly render: (overridingProps?: Partial<Props> | undefined) => ReactNode;\n}\n\ntype ComponentFunctor<Request, Props extends BaseProps> = (\n request: Request\n) => ComponentFunctorReturnValue<Props> | undefined;\n\ntype ComponentEnhancer<Request, Props extends BaseProps> = (\n next: ComponentFunctor<Request, Props>\n) => ComponentFunctor<Request, Props>;\n\ntype ComponentMiddleware<Request, Props extends BaseProps, Init = undefined> = (\n init: Init\n) => ComponentEnhancer<Request, Props>;\n\ntype UseBuildRenderCallbackOptions<Props> = {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n};\n\ninterface UseBuildRenderCallback<Request, Props extends BaseProps> {\n (request: Request, options?: undefined | UseBuildRenderCallbackOptions<Props>): RenderCallback<Props> | undefined;\n}\n\ntype BuildContextType<Request, Props extends BaseProps> = {\n readonly enhancer: ComponentEnhancer<Request, Props>;\n};\n\ntype RenderContextType<Props> = {\n readonly renderCallbackProps: Props;\n};\n\ntype ProviderProps<Request, Props extends BaseProps, Init> = PropsWithChildren<{\n readonly middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends BaseProps> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype InferenceHelper<Request, Props extends BaseProps, Init> = {\n readonly '~types': {\n readonly component: ComponentType<Props>;\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly request: Request;\n };\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferComponent<T extends InferenceHelper<any, any, any>> = T['~types']['component'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferInit<T extends InferenceHelper<any, any, any>> = T['~types']['init'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferMiddleware<T extends InferenceHelper<any, any, any>> = T['~types']['middleware'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProps<T extends InferenceHelper<any, any, any>> = T['~types']['props'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProxyProps<T extends InferenceHelper<any, any, any>> = T['~types']['proxyProps'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferRequest<T extends InferenceHelper<any, any, any>> = T['~types']['request'];\n\nfunction createChainOfResponsibility<\n Request = void,\n Props extends BaseProps = { readonly children?: never },\n Init = void\n>(options: CreateChainOfResponsibilityOptions = {}): ChainOfResponsibility<Request, Props, Init> {\n // Freeze options to prevent accidental change.\n options = Object.freeze({ ...options });\n\n const BuildContext = createContext<BuildContextType<Request, Props>>(\n Object.freeze({ enhancer: next => request => next(request) })\n );\n\n const RenderContext = createContext<RenderContextType<Props>>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new Proxy({} as any, {\n get() {\n // The following is assertion, there is no way to hit this line.\n /* istanbul ignore next */\n throw new Error(\n 'react-chain-of-responsibility: this hook cannot be used outside of <Proxy> and useBuildRenderCallback()'\n );\n }\n })\n );\n\n function reactComponent<P extends Props>(\n component: ComponentType<P>,\n bindProps?:\n | (Partial<Props> & Omit<P, keyof Props>)\n | ((props: Props) => Partial<Props> & Omit<P, keyof Props>)\n | undefined\n ): ComponentFunctorReturnValue<Props> {\n return Object.freeze({\n [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined,\n render: (overridingProps?: Partial<Props> | undefined) => (\n <ComponentWithProps\n bindProps={bindProps}\n component={component as ComponentType<Props>}\n overridingProps={overridingProps}\n />\n )\n });\n }\n\n const ComponentWithProps = memo(function ComponentWithProps({\n bindProps,\n component: Component,\n overridingProps\n }: {\n readonly bindProps?: Partial<Props> | ((props: Props) => Partial<Props>) | undefined;\n readonly component: ComponentType<Props>;\n readonly overridingProps?: Partial<Props> | undefined;\n }) {\n const { allowOverrideProps } = options;\n const { renderCallbackProps } = useContext(RenderContext);\n\n if (overridingProps && !arePropsEqual(overridingProps, renderCallbackProps) && !allowOverrideProps) {\n console.warn('react-chain-of-responsibility: \"allowOverrideProps\" must be set to true to override props');\n }\n\n const props = Object.freeze(\n allowOverrideProps ? { ...renderCallbackProps, ...overridingProps } : { ...renderCallbackProps }\n );\n\n return <Component {...props} {...(typeof bindProps === 'function' ? bindProps(props) : bindProps)} />;\n });\n\n const useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props> = () => {\n const { enhancer } = useContext(BuildContext);\n\n return useCallback(\n (request, buildOptions = {}) => {\n const result =\n // Put the \"fallbackComponent\" as the last one in the chain.\n enhancer(() => {\n const { fallbackComponent } = buildOptions;\n\n if (!fallbackComponent) {\n console.warn(\n 'react-chain-of-responsibility: the request has fall through all middleware, set \"fallbackComponent\" as a catchall',\n request\n );\n\n // For clarity, we are returning `undefined` instead of `() => undefined`.\n return;\n }\n\n return Object.freeze({\n // Mark fallback render callback as functor return value.\n [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined,\n render: () => (\n // Currently, there are no ways to set `bindProps` to `fallbackComponent`.\n // `fallbackComponent` do not need `overridingProps` because it is the last one in the chain, it would not have the next() function.\n <ComponentWithProps component={fallbackComponent} />\n )\n });\n })(request);\n\n return (\n result &&\n ((props: Props) => {\n const renderCallbackProps = useMemoValueWithEquality<Props>(() => props, arePropsEqual);\n\n const context = useMemo<RenderContextType<Props>>(\n () => Object.freeze({ renderCallbackProps }),\n [renderCallbackProps]\n );\n\n return <RenderContext.Provider value={context}>{result.render()}</RenderContext.Provider>;\n })\n );\n },\n [enhancer]\n );\n };\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n if (!Array.isArray(middleware) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('react-chain-of-responsibility: \"middleware\" prop must be an array of functions');\n }\n\n // Remap the middleware, so all inputs/outputs are validated.\n const fortifiedMiddleware = useMemo(\n () =>\n Object.freeze(\n middleware.map<ComponentMiddleware<Request, Props, Init>>(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return next => originalRequest => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error(\n 'react-chain-of-responsibility: next() cannot be called after the function had returned synchronously'\n );\n }\n\n // We do not allow passing void/undefined to next() because it would be confusing whether to keep the original request or pass an undefined.\n !options.passModifiedRequest &&\n !Object.is(nextRequest, originalRequest) &&\n console.warn(\n 'react-chain-of-responsibility: next() must be called with the original request, otherwise, set \"options.passModifiedRequest\" to true to pass a different request object downstream'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n // Make sure the return value is built using our helper function for forward-compatibility reason.\n return returnValue && parse(componentFunctorReturnValueSchema, returnValue);\n };\n })\n ),\n [middleware]\n );\n\n const { enhancer: parentEnhancer } = useContext(BuildContext);\n\n const enhancer = useMemo<ComponentEnhancer<Request, Props>>(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<[Request], ComponentFunctorReturnValue<Props> | undefined, [Init]>(\n ...[...fortifiedMiddleware, ...[() => parentEnhancer]].reverse()\n )(init as Init),\n [init, fortifiedMiddleware, parentEnhancer]\n );\n\n const contextValue = useMemo<BuildContextType<Request, Props>>(() => Object.freeze({ enhancer }), [enhancer]);\n\n return <BuildContext.Provider value={contextValue}>{children}</BuildContext.Provider>;\n }\n\n function ChainOfResponsibilityProxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const result = useBuildRenderCallback()(request, { fallbackComponent })?.(props as Props);\n\n return result ? <Fragment>{result}</Fragment> : null;\n }\n\n const MemoizedChainOfResponsibilityProvider =\n memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider);\n\n return Object.freeze({\n Provider: MemoizedChainOfResponsibilityProvider as typeof MemoizedChainOfResponsibilityProvider &\n InferenceHelper<Request, Props, Init>,\n Proxy: memo<ProxyProps<Request, Props>>(ChainOfResponsibilityProxy),\n reactComponent,\n useBuildRenderCallback\n\n // TODO: Consider adding back `asMiddleware`.\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type CreateChainOfResponsibilityOptions,\n type InferComponent,\n type InferInit,\n type InferMiddleware,\n type InferProps,\n type InferProxyProps,\n type InferRequest,\n type UseBuildRenderCallback\n};\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function arePropsEqual<T extends Record<string, any>>(x: T, y: T): boolean {\n if (Object.is(x, y)) {\n return true;\n }\n\n const mapOfX = new Map(Object.entries(x));\n const mapOfY = new Map(Object.entries(y));\n\n if (mapOfX.size !== mapOfY.size) {\n return false;\n }\n\n const keys = new Set([...mapOfX.keys(), ...mapOfY.keys()]);\n\n for (const key of keys) {\n if (!Object.is(mapOfX.get(key), mapOfY.get(key))) {\n return false;\n }\n }\n\n return true;\n}\n","import { useEffect, useRef } from 'react';\n\nconst NOT_INITIALIZED = Symbol();\n\nexport default function useMemoValueWithEquality<T>(factory: () => T, equalityFn: (x: T, y: T) => boolean): T {\n const prevRef = useRef<T | typeof NOT_INITIALIZED>(NOT_INITIALIZED);\n const next: T = factory();\n const current: T = prevRef.current !== NOT_INITIALIZED && equalityFn(prevRef.current, next) ? prevRef.current : next;\n\n useEffect(() => {\n prevRef.current = current;\n });\n\n return current;\n}\n"],"mappings":";;;;;AAAA,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,QAAQ,WAAW,QAAQ,OAAO,iBAAiB;;;ACV7C,SAAR,cAA8D,GAAM,GAAe;AACxF,MAAI,OAAO,GAAG,GAAG,CAAC,GAAG;AACnB,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,IAAI,IAAI,OAAO,QAAQ,CAAC,CAAC;AACxC,QAAM,SAAS,IAAI,IAAI,OAAO,QA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EAAE,IAAY;AAAA;AAAA,MAChB,CAAC,MAAM,qBAAqB,cAAc;AAAA,IAC5C;AAEA,UAAM,eAAe,QAA0C,MAAM,OAAO,OAAO,EAAE,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC;AAE5G,WAAO,oCAAC,aAAa,UAAb,EAAsB,OAAO,gBAAe,QAAS;AAAA,EAC/D;AAEA,WAAS,2BAA2B,EAAE,mBAAmB,SAAS,GAAG,MAAM,GAA+B;AACxG,UAAM,SAAS,uBAAuB,EAAE,SAAS,EAAE,kBAAkB,CAAC,IAAI,KAAc;AAExF,WAAO,SAAS,oCAAC,gBAAU,MAAO,IAAc;AAAA,EAClD;AAEA,QAAM,wCACJ,KAA0C,6BAA6B;AAEzE,SAAO,OAAO,OAAO;AAAA,IACnB,UAAU;AAAA,IAEV,OAAO,KAAiC,0BAA0B;AAAA,IAClE;AAAA,IACA;AAAA;AAAA,EAGF,CAAC;AACH;AAEA,IAAO,sDAAQ;","names":["ComponentWithProps","middleware","init","enhancer"]}
|
|
1
|
+
{"version":3,"sources":["../src/preview/createChainOfResponsibilityAsRenderCallback.tsx","../src/preview/private/arePropsEqual.ts","../src/preview/private/useMemoValueWithEquality.ts"],"sourcesContent":["import { applyMiddleware } from 'handler-chain';\nimport React, {\n createContext,\n Fragment,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren,\n type ReactNode\n} from 'react';\nimport { custom, function_, object, parse, safeParse } from 'valibot';\n\nimport arePropsEqual from './private/arePropsEqual.ts';\nimport useMemoValueWithEquality from './private/useMemoValueWithEquality.ts';\n\n// TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n// typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\ndeclare global {\n interface ArrayConstructor {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n isArray(arg: any): arg is readonly any[];\n }\n}\n\ntype BaseProps = object;\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows one component to pass different set of props to its downstream component. Default is false.\n *\n * It is recommended to keep this settings as default to prevent newly added component from unexpectedly changing behavior of downstream components.\n */\n readonly allowOverrideProps?: boolean | undefined;\n\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * It is recommended to keep this settings as default ot prevent newly added middleware from unexpectedly changing behavior of downstream middleware.\n *\n * To prevent upstream middleware from modifying the request, the request object should be set to be immutable through `Object.freeze`.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype ChainOfResponsibility<Request, Props extends BaseProps, Init> = {\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>> & InferenceHelper<Request, Props, Init>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly reactComponent: ReactComponentHandlerResult<Props>;\n readonly useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props>;\n};\n\n// TODO: Maybe this one should be local.\n// Verify that reactComponent() from an instance of CoR should throw error when used in another instance of CoR.\nconst DO_NOT_CREATE_THIS_OBJECT_YOURSELF = Symbol();\n\ntype ComponentRenderer<Props> = (props: Props) => ReactNode;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst componentHandlerResultSchema = custom<ComponentHandlerResult<any>>(\n value =>\n safeParse(object({ render: function_() }), value).success &&\n !!value &&\n typeof value === 'object' &&\n DO_NOT_CREATE_THIS_OBJECT_YOURSELF in value,\n 'react-chain-of-responsibility: middleware must return value constructed by reactComponent()'\n);\n\ninterface ComponentHandlerResult<Props extends BaseProps> {\n readonly [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined;\n readonly render: (overridingProps?: Partial<Props> | undefined) => ReactNode;\n}\n\ntype ComponentHandler<Request, Props extends BaseProps> = (\n request: Request\n) => ComponentHandlerResult<Props> | undefined;\n\ntype ComponentEnhancer<Request, Props extends BaseProps> = (\n next: ComponentHandler<Request, Props>\n) => ComponentHandler<Request, Props>;\n\ntype ComponentMiddleware<Request, Props extends BaseProps, Init = undefined> = (\n init: Init\n) => ComponentEnhancer<Request, Props>;\n\ntype ReactComponentHandlerResult<Props extends object> = <P extends Props>(\n component: ComponentType<P>,\n bindProps?:\n | (Partial<Props> & Omit<P, keyof Props>)\n | ((props: Props) => Partial<Props> & Omit<P, keyof Props>)\n | undefined\n) => ComponentHandlerResult<Props>;\n\ntype UseBuildRenderCallbackOptions<Props> = {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n};\n\ninterface UseBuildRenderCallback<Request, Props extends BaseProps> {\n (request: Request, options?: undefined | UseBuildRenderCallbackOptions<Props>): ComponentRenderer<Props> | undefined;\n}\n\ntype BuildContextType<Request, Props extends BaseProps> = {\n readonly enhancer: ComponentEnhancer<Request, Props>;\n};\n\ntype RenderContextType<Props> = {\n readonly renderCallbackProps: Props;\n};\n\ntype ProviderProps<Request, Props extends BaseProps, Init> = PropsWithChildren<{\n readonly middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends BaseProps> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype InferenceHelper<Request, Props extends BaseProps, Init> = {\n readonly '~types': {\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly providerProps: ProviderProps<Request, Props, Init>;\n readonly request: Request;\n };\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferInit<T extends InferenceHelper<any, any, any>> = T['~types']['init'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferMiddleware<T extends InferenceHelper<any, any, any>> = T['~types']['middleware'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProps<T extends InferenceHelper<any, any, any>> = T['~types']['props'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProxyProps<T extends InferenceHelper<any, any, any>> = T['~types']['proxyProps'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferProviderProps<T extends InferenceHelper<any, any, any>> = T['~types']['providerProps'];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InferRequest<T extends InferenceHelper<any, any, any>> = T['~types']['request'];\n\nfunction createChainOfResponsibility<\n Request = void,\n Props extends BaseProps = { readonly children?: never },\n Init = void\n>(options: CreateChainOfResponsibilityOptions = {}): ChainOfResponsibility<Request, Props, Init> {\n // Freeze options to prevent accidental change.\n options = Object.freeze({ ...options });\n\n const BuildContext = createContext<BuildContextType<Request, Props>>(\n Object.freeze({ enhancer: next => request => next(request) })\n );\n\n const RenderContext = createContext<RenderContextType<Props>>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new Proxy({} as any, {\n get() {\n // The following is assertion, there is no way to hit this line.\n /* istanbul ignore next */\n throw new Error(\n 'react-chain-of-responsibility: this hook cannot be used outside of <Proxy> and useBuildRenderCallback()'\n );\n }\n })\n );\n\n function reactComponent<P extends Props>(\n component: ComponentType<P>,\n bindProps?:\n | (Partial<Props> & Omit<P, keyof Props>)\n | ((props: Props) => Partial<Props> & Omit<P, keyof Props>)\n | undefined\n ): ComponentHandlerResult<Props> {\n return Object.freeze({\n [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined,\n render: (overridingProps?: Partial<Props> | undefined) => (\n <ComponentWithProps\n bindProps={bindProps}\n component={component as ComponentType<Props>}\n overridingProps={overridingProps}\n />\n )\n });\n }\n\n const ComponentWithProps = memo(function ComponentWithProps({\n bindProps,\n component: Component,\n overridingProps\n }: {\n readonly bindProps?: Partial<Props> | ((props: Props) => Partial<Props>) | undefined;\n readonly component: ComponentType<Props>;\n readonly overridingProps?: Partial<Props> | undefined;\n }) {\n const { allowOverrideProps } = options;\n const { renderCallbackProps } = useContext(RenderContext);\n\n if (overridingProps && !arePropsEqual(overridingProps, renderCallbackProps) && !allowOverrideProps) {\n console.warn('react-chain-of-responsibility: \"allowOverrideProps\" must be set to true to override props');\n }\n\n const props = Object.freeze(\n allowOverrideProps ? { ...renderCallbackProps, ...overridingProps } : { ...renderCallbackProps }\n );\n\n return <Component {...props} {...(typeof bindProps === 'function' ? bindProps(props) : bindProps)} />;\n });\n\n const useBuildRenderCallback: () => UseBuildRenderCallback<Request, Props> = () => {\n const { enhancer } = useContext(BuildContext);\n\n return useCallback(\n (request, buildOptions = {}) => {\n const result =\n // Put the \"fallbackComponent\" as the last one in the chain.\n enhancer(() => {\n const { fallbackComponent } = buildOptions;\n\n if (!fallbackComponent) {\n console.warn(\n 'react-chain-of-responsibility: the request has fall through all middleware, set \"fallbackComponent\" as a catchall',\n request\n );\n\n // For clarity, we are returning `undefined` instead of `() => undefined`.\n return;\n }\n\n return Object.freeze({\n // Convert fallback component as renderer.\n [DO_NOT_CREATE_THIS_OBJECT_YOURSELF]: undefined,\n render: () => (\n // Currently, there are no ways to set `bindProps` to `fallbackComponent`.\n // `fallbackComponent` do not need `overridingProps` because it is the last one in the chain, it would not have the next() function.\n <ComponentWithProps component={fallbackComponent} />\n )\n });\n })(request);\n\n return (\n result &&\n ((props: Props) => {\n const renderCallbackProps = useMemoValueWithEquality<Props>(() => props, arePropsEqual);\n\n const context = useMemo<RenderContextType<Props>>(\n () => Object.freeze({ renderCallbackProps }),\n [renderCallbackProps]\n );\n\n return <RenderContext.Provider value={context}>{result.render()}</RenderContext.Provider>;\n })\n );\n },\n [enhancer]\n );\n };\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n if (!Array.isArray(middleware) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('react-chain-of-responsibility: \"middleware\" prop must be an array of functions');\n }\n\n // Remap the middleware, so all inputs/outputs are validated.\n const fortifiedMiddleware = useMemo(\n () =>\n Object.freeze(\n middleware.map<ComponentMiddleware<Request, Props, Init>>(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return next => originalRequest => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error(\n 'react-chain-of-responsibility: next() cannot be called after the function had returned synchronously'\n );\n }\n\n // We do not allow passing void/undefined to next() because it would be confusing whether to keep the original request or pass an undefined.\n !options.passModifiedRequest &&\n !Object.is(nextRequest, originalRequest) &&\n console.warn(\n 'react-chain-of-responsibility: next() must be called with the original request, otherwise, set \"options.passModifiedRequest\" to true to pass a different request object downstream'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n // Make sure the return value is built using our helper function for forward-compatibility reason.\n return returnValue && parse(componentHandlerResultSchema, returnValue);\n };\n })\n ),\n [middleware]\n );\n\n const { enhancer: parentEnhancer } = useContext(BuildContext);\n\n const enhancer = useMemo<ComponentEnhancer<Request, Props>>(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<ComponentHandlerResult<Props> | undefined, Request, Init>(\n ...[...fortifiedMiddleware, ...[() => parentEnhancer]]\n )(init as Init),\n [init, fortifiedMiddleware, parentEnhancer]\n );\n\n const contextValue = useMemo<BuildContextType<Request, Props>>(() => Object.freeze({ enhancer }), [enhancer]);\n\n return <BuildContext.Provider value={contextValue}>{children}</BuildContext.Provider>;\n }\n\n function ChainOfResponsibilityProxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const result = useBuildRenderCallback()(request, { fallbackComponent })?.(props as Props);\n\n return result ? <Fragment>{result}</Fragment> : null;\n }\n\n const MemoizedChainOfResponsibilityProvider =\n memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider);\n\n return Object.freeze({\n Provider: MemoizedChainOfResponsibilityProvider as typeof MemoizedChainOfResponsibilityProvider &\n InferenceHelper<Request, Props, Init>,\n Proxy: memo<ProxyProps<Request, Props>>(ChainOfResponsibilityProxy),\n reactComponent,\n useBuildRenderCallback\n\n // TODO: Consider adding back `asMiddleware`.\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type ComponentEnhancer,\n type ComponentHandler,\n type ComponentHandlerResult,\n type ComponentMiddleware,\n type ComponentRenderer,\n type CreateChainOfResponsibilityOptions,\n type InferenceHelper,\n type InferInit,\n type InferMiddleware,\n type InferProps,\n type InferProviderProps,\n type InferProxyProps,\n type InferRequest,\n type ProviderProps,\n type ProxyProps,\n type ReactComponentHandlerResult,\n type UseBuildRenderCallback,\n type UseBuildRenderCallbackOptions\n};\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function arePropsEqual<T extends Record<string, any>>(x: T, y: T): boolean {\n if (Object.is(x, y)) {\n return true;\n }\n\n const mapOfX = new Map(Object.entries(x));\n const mapOfY = new Map(Object.entries(y));\n\n if (mapOfX.size !== mapOfY.size) {\n return false;\n }\n\n const keys = new Set([...mapOfX.keys(), ...mapOfY.keys()]);\n\n for (const key of keys) {\n if (!Object.is(mapOfX.get(key), mapOfY.get(key))) {\n return false;\n }\n }\n\n return true;\n}\n","import { useEffect, useRef } from 'react';\n\nconst NOT_INITIALIZED = Symbol();\n\nexport default function useMemoValueWithEquality<T>(factory: () => T, equalityFn: (x: T, y: T) => boolean): T {\n const prevRef = useRef<T | typeof NOT_INITIALIZED>(NOT_INITIALIZED);\n const next: T = factory();\n const current: T = prevRef.current !== NOT_INITIALIZED && equalityFn(prevRef.current, next) ? prevRef.current : next;\n\n useEffect(() => {\n prevRef.current = current;\n });\n\n return current;\n}\n"],"mappings":";AAAA,SAAS,uBAAuB;AAChC,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,QAAQ,WAAW,QAAQ,OAAO,iBAAiB;;;ACX7C,SAAR,cAA8D,GAAM,GAAe;AACxF,MAAI,OAAO,GAAG,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;AAAA,MACf;AAAA;AAAA;AAAA;AAAA,QAIE;AAAA,UACE,GAAG,CAAC,GAAG,qBAAqB,GAAG,CAAC,MAAM,cAAc,CAAC;AAAA,QACvD,EAAE,IAAY;AAAA;AAAA,MAChB,CAAC,MAAM,qBAAqB,cAAc;AAAA,IAC5C;AAEA,UAAM,eAAe,QAA0C,MAAM,OAAO,OAAO,EAAE,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC;AAE5G,WAAO,oCAAC,aAAa,UAAb,EAAsB,OAAO,gBAAe,QAAS;AAAA,EAC/D;AAEA,WAAS,2BAA2B,EAAE,mBAAmB,SAAS,GAAG,MAAM,GAA+B;AACxG,UAAM,SAAS,uBAAuB,EAAE,SAAS,EAAE,kBAAkB,CAAC,IAAI,KAAc;AAExF,WAAO,SAAS,oCAAC,gBAAU,MAAO,IAAc;AAAA,EAClD;AAEA,QAAM,wCACJ,KAA0C,6BAA6B;AAEzE,SAAO,OAAO,OAAO;AAAA,IACnB,UAAU;AAAA,IAEV,OAAO,KAAiC,0BAA0B;AAAA,IAClE;AAAA,IACA;AAAA;AAAA,EAGF,CAAC;AACH;AAEA,IAAO,sDAAQ;","names":["ComponentWithProps","middleware","init","enhancer"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-chain-of-responsibility",
|
|
3
|
-
"version": "0.4.0-main.
|
|
3
|
+
"version": "0.4.0-main.d864102",
|
|
4
4
|
"description": "Using chain of responsibility design pattern for compositing and customizing React component.",
|
|
5
5
|
"files": [
|
|
6
6
|
"./dist/"
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
"precommit:typescript:production": "tsc --noEmit --project ./src/tsconfig.precommit.production.json",
|
|
51
51
|
"precommit:typescript:test": "tsc --noEmit --project ./src/tsconfig.precommit.test.json",
|
|
52
52
|
"prepack": "cp ../../CHANGELOG.md . && cp ../../LICENSE . && cp ../../README.md .",
|
|
53
|
+
"start": "npm run build -- --onSuccess \"touch ../pages/package.json\" --watch",
|
|
53
54
|
"switch": "cat package.json | jq --arg SWITCH_NAME $SWITCH_NAME -r '(.[\"switch:\" + $SWITCH_NAME] // {}) as $TEMPLATE | .devDependencies += ($TEMPLATE.devDependencies // {}) | .dependencies += ($TEMPLATE.dependencies // {})' | tee ./package.json.tmp && mv ./package.json.tmp ./package.json",
|
|
54
55
|
"test": "jest"
|
|
55
56
|
},
|
|
@@ -98,9 +99,18 @@
|
|
|
98
99
|
}
|
|
99
100
|
},
|
|
100
101
|
"pinDependencies": {
|
|
102
|
+
"@testduet/given-when-then": [
|
|
103
|
+
"main"
|
|
104
|
+
],
|
|
105
|
+
"@testduet/wait-for": [
|
|
106
|
+
"main"
|
|
107
|
+
],
|
|
101
108
|
"@types/react": [
|
|
102
109
|
"18"
|
|
103
110
|
],
|
|
111
|
+
"escape-string-regexp": [
|
|
112
|
+
"4"
|
|
113
|
+
],
|
|
104
114
|
"react": [
|
|
105
115
|
"18"
|
|
106
116
|
],
|
|
@@ -112,23 +122,24 @@
|
|
|
112
122
|
]
|
|
113
123
|
},
|
|
114
124
|
"devDependencies": {
|
|
115
|
-
"@babel/preset-env": "^7.
|
|
125
|
+
"@babel/preset-env": "^7.28.0",
|
|
116
126
|
"@babel/preset-react": "^7.27.1",
|
|
117
127
|
"@babel/preset-typescript": "^7.27.1",
|
|
118
|
-
"@fluentui/react": "^8.123.
|
|
128
|
+
"@fluentui/react": "^8.123.1",
|
|
119
129
|
"@testduet/given-when-then": "^0.1.0-main.334801c",
|
|
130
|
+
"@testduet/wait-for": "^0.1.1-main.3a4f261",
|
|
120
131
|
"@testing-library/dom": "^10.4.0",
|
|
121
132
|
"@testing-library/react": "^16.3.0",
|
|
122
133
|
"@tsconfig/recommended": "^1.0.10",
|
|
123
134
|
"@tsconfig/strictest": "^2.0.5",
|
|
124
135
|
"@types/jest": "^30.0.0",
|
|
125
|
-
"@types/node": "^24.0.
|
|
136
|
+
"@types/node": "^24.0.15",
|
|
126
137
|
"@types/react": "^18.3.23",
|
|
127
|
-
"esbuild": "^0.25.
|
|
138
|
+
"esbuild": "^0.25.8",
|
|
128
139
|
"escape-string-regexp": "^4.0.0",
|
|
129
|
-
"jest": "^30.0.
|
|
130
|
-
"jest-environment-jsdom": "^30.0.
|
|
131
|
-
"prettier": "^3.
|
|
140
|
+
"jest": "^30.0.4",
|
|
141
|
+
"jest-environment-jsdom": "^30.0.4",
|
|
142
|
+
"prettier": "^3.6.2",
|
|
132
143
|
"publint": "^0.3.12",
|
|
133
144
|
"react": "^18.3.1",
|
|
134
145
|
"react-dom": "^18.3.1",
|
|
@@ -142,7 +153,8 @@
|
|
|
142
153
|
"react": ">=16.8.0"
|
|
143
154
|
},
|
|
144
155
|
"dependencies": {
|
|
145
|
-
"
|
|
156
|
+
"handler-chain": "^0.1.0",
|
|
157
|
+
"react-chain-of-responsibility": "^0.4.0-main.d864102",
|
|
146
158
|
"valibot": "^1.1.0"
|
|
147
159
|
}
|
|
148
160
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createChainOfResponsibility.tsx","../src/isReactComponent.ts"],"sourcesContent":["import React, {\n createContext,\n isValidElement,\n memo,\n useCallback,\n useContext,\n useMemo,\n type ComponentType,\n type PropsWithChildren\n} from 'react';\n\nimport isReactComponent from './isReactComponent.ts';\nimport applyMiddleware, { type Enhancer } from './private/applyMiddleware.ts';\nimport { type ComponentMiddleware } from './types.ts';\n\n// TODO: Simplify to ComponentType<Props> | undefined.\ntype ResultComponent<Props> = ComponentType<Props> | false | null | undefined;\n\ntype UseBuildComponentCallbackOptions<Props> = {\n fallbackComponent?: ResultComponent<Props> | undefined;\n};\n\ninterface UseBuildComponentCallback<Request, Props> {\n (request: Request, options?: undefined | UseBuildComponentCallbackOptions<Props>): ComponentType<Props> | undefined;\n}\n\ntype ProviderContext<Request, Props> = {\n get enhancer(): Enhancer<[Request], ResultComponent<Props>> | undefined;\n useBuildComponentCallback: UseBuildComponentCallback<Request, Props>;\n};\n\ntype ProviderProps<Request, Props, Init> = PropsWithChildren<{\n middleware: readonly ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | void\n ? { readonly init?: undefined }\n : Init extends undefined | void\n ? { readonly init?: Init }\n : { readonly init: Init });\n\ntype ProxyProps<Request, Props extends object> = Props & {\n readonly fallbackComponent?: ComponentType<Props> | undefined;\n readonly request: Request;\n};\n\ntype CreateChainOfResponsibilityOptions = {\n /**\n * Allows a middleware to pass another request object when calling its next middleware. Default is false.\n *\n * However, middleware could modify the request object before calling its next middleware. It is recommended\n * to use Object.freeze() to prevent middleware from modifying the request object.\n */\n readonly passModifiedRequest?: boolean | undefined;\n};\n\ntype AsMiddlewareProps<Request, Props, Init> = {\n readonly init: Init;\n readonly Next: ComponentType<Partial<Props>>;\n readonly request: Request;\n};\n\ntype AsMiddlewareComponentProps<Request, Props, Init> = Props & {\n readonly middleware: AsMiddlewareProps<Request, Props, Init>;\n};\n\ntype ChainOfResponsibility<Request, Props extends object, Init> = {\n readonly asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init>;\n readonly Provider: ComponentType<ProviderProps<Request, Props, Init>>;\n readonly Proxy: ComponentType<ProxyProps<Request, Props>>;\n readonly types: {\n readonly init: Init;\n readonly middleware: ComponentMiddleware<Request, Props, Init>;\n readonly middlewareComponentProps: AsMiddlewareComponentProps<Request, Props, Init>;\n readonly props: Props;\n readonly proxyProps: ProxyProps<Request, Props>;\n readonly request: Request;\n };\n readonly useBuildComponentCallback: () => UseBuildComponentCallback<Request, Props>;\n};\n\nfunction createChainOfResponsibility<Request = void, Props extends object = { readonly children?: never }, Init = void>(\n options: CreateChainOfResponsibilityOptions = {}\n): ChainOfResponsibility<Request, Props, Init> {\n const defaultUseBuildComponentCallback: ProviderContext<Request, Props> = {\n get enhancer() {\n return undefined;\n },\n useBuildComponentCallback(_request, options): ComponentType<Props> {\n if (!options?.fallbackComponent) {\n throw new Error('This component/hook cannot be used outside of its corresponding <Provider>');\n }\n\n return options.fallbackComponent;\n }\n };\n\n const context = createContext<ProviderContext<Request, Props>>(defaultUseBuildComponentCallback);\n\n function ChainOfResponsibilityProvider({ children, init, middleware }: ProviderProps<Request, Props, Init>) {\n // TODO: Related to https://github.com/microsoft/TypeScript/issues/17002.\n // typescript@5.2.2 has a bug, Array.isArray() is a type predicate but only works with mutable array, not readonly array.\n // After removing \"as unknown\", `middleware` on the next line become `any[]`.\n if (!Array.isArray(middleware as unknown) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('middleware prop must be an array of functions');\n }\n\n const patchedMiddleware: readonly ComponentMiddleware<Request, Props, Init>[] = Object.freeze(\n middleware\n ? middleware.map(fn => (init: Init) => {\n const enhancer = fn(init);\n\n return (next: (request: Request) => ComponentType<Props> | false | null | undefined) =>\n (originalRequest: Request) => {\n // False positive: although we did not re-assign the variable from true, it was initialized as undefined.\n // eslint-disable-next-line prefer-const\n let hasReturned: boolean;\n\n const returnValue = enhancer(nextRequest => {\n if (hasReturned) {\n throw new Error('next() cannot be called after the function had returned synchronously');\n }\n\n !options.passModifiedRequest &&\n nextRequest !== originalRequest &&\n console.warn(\n 'react-chain-of-responsibility: \"options.passModifiedRequest\" must be set to true to pass a different request object to next().'\n );\n\n return next(options.passModifiedRequest ? nextRequest : originalRequest);\n })(originalRequest);\n\n hasReturned = true;\n\n if (isValidElement(returnValue)) {\n throw new Error('middleware must not return React element directly');\n } else if (\n returnValue !== false &&\n returnValue !== null &&\n typeof returnValue !== 'undefined' &&\n !isReactComponent(returnValue)\n ) {\n throw new Error(\n 'middleware must return false, null, undefined, function component, or class component'\n );\n }\n\n return returnValue;\n };\n })\n : []\n );\n\n const { enhancer: parentEnhancer } = useContext(context);\n\n const enhancer = useMemo(\n () =>\n // We are reversing because it is easier to read:\n // - With reverse, [a, b, c] will become a(b(c(fn)))\n // - Without reverse, [a, b, c] will become c(b(a(fn)))\n applyMiddleware<[Request], ResultComponent<Props>, [Init]>(\n ...[...patchedMiddleware, ...(parentEnhancer ? [() => parentEnhancer] : [])].reverse()\n )(init as Init),\n [init, middleware, parentEnhancer]\n );\n\n const useBuildComponentCallback = useCallback<UseBuildComponentCallback<Request, Props>>(\n (request, options = {}) => enhancer(() => options.fallbackComponent)(request) || undefined,\n [enhancer]\n );\n\n const contextValue = useMemo<ProviderContext<Request, Props>>(\n () => ({ enhancer, useBuildComponentCallback }),\n [enhancer, useBuildComponentCallback]\n );\n\n return <context.Provider value={contextValue}>{children}</context.Provider>;\n }\n\n const useBuildComponentCallback = () => useContext(context).useBuildComponentCallback;\n\n function Proxy({ fallbackComponent, request, ...props }: ProxyProps<Request, Props>) {\n const enhancer = useBuildComponentCallback();\n\n const Component = enhancer(request as Request, { fallbackComponent });\n\n return Component ? <Component {...(props as Props)} /> : null;\n }\n\n const asMiddleware: (\n middlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ) => ComponentMiddleware<Request, Props, Init> =\n (\n MiddlewareComponent: ComponentType<AsMiddlewareComponentProps<Request, Props, Init>>\n ): ComponentMiddleware<Request, Props, Init> =>\n init =>\n next =>\n request => {\n const RawNextComponent = next(request);\n\n // TODO: Can we pre-build this component during init?\n const MiddlewareOf = (props: Props) => {\n const middleware = useMemo(\n () =>\n Object.freeze({\n init,\n Next: memo<Partial<Props>>(\n RawNextComponent\n ? (overridingProps: Partial<Props>) => <RawNextComponent {...props} {...overridingProps} />\n : () => null\n ),\n request\n }),\n []\n );\n\n return <MiddlewareComponent {...props} middleware={middleware} />;\n };\n\n MiddlewareOf.displayName = `MiddlewareOf<${MiddlewareComponent.displayName || ''}>`;\n\n return memo<Props>(MiddlewareOf);\n };\n\n return Object.freeze({\n asMiddleware,\n Provider: memo<ProviderProps<Request, Props, Init>>(ChainOfResponsibilityProvider),\n Proxy: memo<ProxyProps<Request, Props>>(Proxy),\n types: Object.freeze({\n middlewareComponentProps: undefined as unknown as AsMiddlewareComponentProps<Request, Props, Init>,\n init: undefined as unknown as Init,\n middleware: undefined as unknown as ComponentMiddleware<Request, Props, Init>,\n props: undefined as unknown as Props,\n proxyProps: undefined as unknown as ProxyProps<Request, Props>,\n request: undefined as unknown as Request\n }),\n useBuildComponentCallback\n });\n}\n\nexport default createChainOfResponsibility;\nexport {\n type ChainOfResponsibility,\n type CreateChainOfResponsibilityOptions,\n type ProxyProps,\n type UseBuildComponentCallback\n};\n","import {\n type ComponentClass,\n type ComponentType,\n type Consumer,\n type Fragment,\n type FunctionComponent,\n type Provider\n} from 'react';\nimport { custom } from 'valibot';\n\nfunction isConsumer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Consumer<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.context)';\n}\n\nfunction isProvider(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is Provider<unknown> {\n return component?.$$typeof?.toString() === 'Symbol(react.provider)';\n}\n\nfunction isFragment(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is typeof Fragment {\n return component?.toString() === 'Symbol(react.fragment)';\n}\n\nfunction isFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n if (typeof component === 'function') {\n return true;\n }\n\n return isPureFunctionComponent(component);\n}\n\nfunction isPureFunctionComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is FunctionComponent {\n return component?.$$typeof?.toString() === 'Symbol(react.memo)' && isFunctionComponent(component.type);\n}\n\nfunction isComponentClass(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentClass {\n return typeof component === 'object' && typeof component?.['render'] === 'function';\n}\n\n// There are no definitive ways to check if an object is a React component or not.\n// We are checking if the object has a render function (classic component).\n// Note: \"forwardRef()\" returns plain object, not class instance.\nfunction isReactComponent(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component: any\n): component is ComponentType {\n return (\n isFunctionComponent(component) ||\n isComponentClass(component) ||\n isFragment(component) ||\n isConsumer(component) ||\n isProvider(component)\n );\n}\n\nconst reactComponent = () =>\n custom<ComponentType<unknown>>(value => isReactComponent(value), 'not a valid React component');\n\nexport default isReactComponent;\nexport { reactComponent };\n"],"mappings":";;;;;AAAA,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACDP,SAAS,cAAc;AAEvB,SAAS,WAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAAM;AAC7C;AAEA,SAAS,WAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAAM;AAC7C;AAEA,SAAS,WAEP,WAC8B;AAC9B,SAAO,WAAW,SAAS,MAAM;AACnC;AAEA,SAAS,oBAEP,WACgC;AAChC,MAAI,OAAO,cAAc,YAAY;AACnC,WAAO;AAAA,EACT;AAEA,SAAO,wBAAwB,SAAS;AAC1C;AAEA,SAAS,wBAEP,WACgC;AAChC,SAAO,WAAW,UAAU,SAAS,MAAM,wBAAwB,oBAAoB,UAAU,IAAI;AACvG;AAEA,SAAS,iBAEP,WAC6B;AAC7B,SAAO,OAAO,cAAc,YAAY,OAAO,YAAY,QAAQ,MAAM;AAC3E;AAKA,SAAS,iBAEP,WAC4B;AAC5B,SACE,oBAAoB,SAAS,KAC7B,iBAAiB,SAAS,KAC1B,WAAW,SAAS,KACpB,WAAW,SAAS,KACpB,WAAW,SAAS;AAExB;AAKA,IAAO,2BAAQ;;;ADOf,SAAS,4BACP,UAA8C,CAAC,GACF;AAC7C,QAAM,mCAAoE;AAAA,IACxE,IAAI,WAAW;AACb,aAAO;AAAA,IACT;AAAA,IACA,0BAA0B,UAAUA,UAA+B;AACjE,UAAI,CAACA,UAAS,mBAAmB;AAC/B,cAAM,IAAI,MAAM,4EAA4E;AAAA,MAC9F;AAEA,aAAOA,SAAQ;AAAA,IACjB;AAAA,EACF;AAEA,QAAM,UAAU,cAA+C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P,YAAY;AAAA,MACZ,SAAS;AAAA,IACX,CAAC;AAAA,IACD;AAAA,EACF,CAAC;AACH;AAEA,IAAO,sCAAQ;","names":["options","middleware","init","enhancer","useBuildComponentCallback"]}
|
package/dist/chunk-TNTIZJJ5.mjs
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// src/private/compose.ts
|
|
2
|
-
function compose(...fns) {
|
|
3
|
-
return (fn) => fns.reduce((chain, fn2) => fn2(chain), fn);
|
|
4
|
-
}
|
|
5
|
-
|
|
6
|
-
// src/private/applyMiddleware.ts
|
|
7
|
-
function applyMiddleware(...arrayOfMiddleware) {
|
|
8
|
-
return (...init) => {
|
|
9
|
-
const chain = arrayOfMiddleware.map((middleware) => middleware(...init));
|
|
10
|
-
return compose(...chain);
|
|
11
|
-
};
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export {
|
|
15
|
-
applyMiddleware
|
|
16
|
-
};
|
|
17
|
-
//# sourceMappingURL=chunk-TNTIZJJ5.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/private/compose.ts","../src/private/applyMiddleware.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn<P extends any[], R> = (...args: P) => R;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function compose<P extends any[], R>(...fns: Enhancer<P, R>[]): Enhancer<P, R> {\n return (fn: Fn<P, R>): Fn<P, R> => fns.reduce((chain, fn) => fn(chain), fn);\n}\n","import compose from './compose.ts';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn<P extends any[], R> = (...args: P) => R;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Middleware<P extends any[], R, S extends any[]> = (...init: S) => Enhancer<P, R>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default function applyMiddleware<P extends any[], R, S extends any[]>(\n ...arrayOfMiddleware: Middleware<P, R, S>[]\n) {\n return (...init: S) => {\n const chain = arrayOfMiddleware.map(middleware => middleware(...init));\n\n return compose(...chain);\n };\n}\n"],"mappings":";AAOe,SAAR,WAAgD,KAAuC;AAC5F,SAAO,CAAC,OAA2B,IAAI,OAAO,CAAC,OAAOA,QAAOA,IAAG,KAAK,GAAG,EAAE;AAC5E;;;ACGe,SAAR,mBACF,mBACH;AACA,SAAO,IAAI,SAAY;AACrB,UAAM,QAAQ,kBAAkB,IAAI,gBAAc,WAAW,GAAG,IAAI,CAAC;AAErE,WAAO,QAAQ,GAAG,KAAK;AAAA,EACzB;AACF;","names":["fn"]}
|