react-chain-of-responsibility 0.0.1-main.9fc4b7d

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.
Files changed (33) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +339 -0
  3. package/lib/commonjs/createChainOfResponsibility.js +139 -0
  4. package/lib/commonjs/createChainOfResponsibility.js.map +1 -0
  5. package/lib/commonjs/createChainOfResponsibilityForFluentUI.js +35 -0
  6. package/lib/commonjs/createChainOfResponsibilityForFluentUI.js.map +1 -0
  7. package/lib/commonjs/index.js +22 -0
  8. package/lib/commonjs/index.js.map +1 -0
  9. package/lib/commonjs/private/applyMiddleware.js +27 -0
  10. package/lib/commonjs/private/applyMiddleware.js.map +1 -0
  11. package/lib/commonjs/private/compose.js +25 -0
  12. package/lib/commonjs/private/compose.js.map +1 -0
  13. package/lib/commonjs/types.js +1 -0
  14. package/lib/commonjs/types.js.map +1 -0
  15. package/lib/esmodules/createChainOfResponsibility.js +130 -0
  16. package/lib/esmodules/createChainOfResponsibility.js.map +1 -0
  17. package/lib/esmodules/createChainOfResponsibilityForFluentUI.js +26 -0
  18. package/lib/esmodules/createChainOfResponsibilityForFluentUI.js.map +1 -0
  19. package/lib/esmodules/index.js +4 -0
  20. package/lib/esmodules/index.js.map +1 -0
  21. package/lib/esmodules/private/applyMiddleware.js +22 -0
  22. package/lib/esmodules/private/applyMiddleware.js.map +1 -0
  23. package/lib/esmodules/private/compose.js +17 -0
  24. package/lib/esmodules/private/compose.js.map +1 -0
  25. package/lib/esmodules/types.js +1 -0
  26. package/lib/esmodules/types.js.map +1 -0
  27. package/lib/types/createChainOfResponsibility.d.ts +44 -0
  28. package/lib/types/createChainOfResponsibilityForFluentUI.d.ts +11 -0
  29. package/lib/types/index.d.ts +5 -0
  30. package/lib/types/private/applyMiddleware.d.ts +5 -0
  31. package/lib/types/private/compose.d.ts +4 -0
  32. package/lib/types/types.d.ts +9 -0
  33. package/package.json +118 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 William Wong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,339 @@
1
+ # `react-chain-of-responsibility`
2
+
3
+ [Chain of responsibility design pattern](https://refactoring.guru/design-patterns/chain-of-responsibility) for React component customization.
4
+
5
+ ## Background
6
+
7
+ This package is designed for React component developers to enable component customization via composition using the [chain of responsibility design pattern](https://refactoring.guru/design-patterns/chain-of-responsibility).
8
+
9
+ Additional entrypoint and hook are provided to use with [Fluent UI as `IRenderFunction`](https://github.com/microsoft/fluentui/blob/master/packages/utilities/src/IRenderFunction.ts).
10
+
11
+ By composing customizations, they can be decoupled and published separately. App developers could import these published customizations and orchestrate them to their needs. This pattern encourages [separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns) and enables economy of customizability.
12
+
13
+ ## Demo
14
+
15
+ Click here for [our live demo](https://compulim.github.io/react-chain-of-responsibility/).
16
+
17
+ ## How to use
18
+
19
+ ### Using `<Proxy>` component
20
+
21
+ ```jsx
22
+ import { createChainOfResponsibility } from 'react-chain-of-responsibility';
23
+
24
+ // Creates a <Provider> providing the chain of responsibility service.
25
+ const { Provider, Proxy } = createChainOfResponsibility();
26
+
27
+ // List of subcomponents.
28
+ const Bold = ({ children }) => <strong>{children}</strong>;
29
+ const Italic = ({ children }) => <i>{children}</i>;
30
+ const Plain = ({ children }) => <>{children}</>;
31
+
32
+ // Constructs an array of middleware to handle the request and return corresponding subcomponents.
33
+ const middleware = [
34
+ () => next => request => request === 'bold' ? Bold : next(request),
35
+ () => next => request => request === 'italic' ? Italic : next(request),
36
+ () => () => () => Plain
37
+ ];
38
+
39
+ render(
40
+ <Provider middleware={middleware}>
41
+ <Proxy request="bold">This is bold.</Proxy>
42
+ <Proxy request="italic">This is italic.</Proxy>
43
+ <Proxy>This is plain.</Proxy>
44
+ </Provider>
45
+ );
46
+ ```
47
+
48
+ This sample will render:
49
+
50
+ > **This is bold.** _This is italic._ This is plain.
51
+
52
+ ### Using with Fluent UI as `IRenderFunction`
53
+
54
+ The chain of responsibility design pattern can be used in Fluent UI.
55
+
56
+ After calling `createChainOfResponsibilityForFluentUI`, it will return `useBuildRenderFunction` hook. This hook, when called, will return a function to use as [`IRenderFunction`](https://github.com/microsoft/fluentui/blob/master/packages/utilities/src/IRenderFunction.ts) in Fluent UI components.
57
+
58
+ #### Sample code
59
+
60
+ ```jsx
61
+ import { createChainOfResponsibilityForFluentUI } from 'react-chain-of-responsibility';
62
+
63
+ // Creates a <Provider> providing the chain of responsibility service.
64
+ const { Provider, Proxy } = createChainOfResponsibilityForFluentUI();
65
+
66
+ // List of subcomponents.
67
+ const Banana = () => <>🍌</>;
68
+ const Orange = () => <>🍊</>;
69
+
70
+ // Constructs an array of middleware to handle the request and return corresponding subcomponents.
71
+ const middleware = [
72
+ () => next => props => props?.iconProps?.iconName === 'Banana' ? Banana : next(props),
73
+ () => next => props => props?.iconProps?.iconName === 'Orange' ? Orange : next(props)
74
+ // Fallback to `defaultRender` of `IRenderFunction` is automatically injected.
75
+ ];
76
+
77
+ const Inner = () => {
78
+ const renderIconFunction = useBuildRenderFunction();
79
+
80
+ return (
81
+ <Fragment>
82
+ <DefaultButton iconProps={{ iconName: 'Banana' }} onRenderIcon={renderIconFunction} />
83
+ <DefaultButton iconProps={{ iconName: 'Orange' }} onRenderIcon={renderIconFunction} />
84
+ <DefaultButton iconProps={{ iconName: 'OpenInNewTab' }} onRenderIcon={renderIconFunction} />
85
+ </Fragment>
86
+ );
87
+ };
88
+
89
+ render(
90
+ <Provider middleware={middleware}>
91
+ <Inner />
92
+ </Provider>
93
+ );
94
+ ```
95
+
96
+ There are subtle differences between the standard version and the Fluent UI version:
97
+
98
+ - Entrypoint is `createChainOfResponsibilityForFluentUI()`
99
+ - Request and props are always of same type
100
+ - They are optional too, as defined in [`IRenderFunction`](https://github.com/microsoft/fluentui/blob/master/packages/utilities/src/IRenderFunction.ts)
101
+ - Automatic fallback to `defaultRender`
102
+
103
+ ### Decorating UI components
104
+
105
+ One core feature of chain of responsibility design pattern is allowing middleware to control the execution flow. In other words, middleware can decorate the result of their `next()` middleware. The code snippet below shows how the wrapping could be done.
106
+
107
+ The bold middleware uses traditional approach to wrap the `next()` result, which is a component named `<Next>`. The italic middleware uses [`react-wrap-with`](https://npmjs.com/package/react-wrap-with/) to simplify the wrapping code.
108
+
109
+ ```jsx
110
+ const middleware = [
111
+ () => next => request => {
112
+ const Next = next(request);
113
+
114
+ if (request?.has('bold')) {
115
+ return props => <Bold>{Next && <Next {...props} />}</Bold>;
116
+ }
117
+
118
+ return Next;
119
+ },
120
+ () => next => request => wrapWith(request?.has('italic') && Italic)(next(request)),
121
+ () => () => () => Plain
122
+ ];
123
+
124
+ const App = () => (
125
+ <Provider middleware={middleware}>
126
+ <Proxy request={new Set(['bold'])}>This is bold.</Proxy>
127
+ <Proxy request={new Set(['italic'])}>This is italic.</Proxy>
128
+ <Proxy request={new Set(['bold', 'italic'])}>This is bold and italic.</Proxy>
129
+ <Proxy>This is plain.</Proxy>
130
+ </Provider>
131
+ );
132
+ ```
133
+
134
+ This sample will render:
135
+
136
+ > **This is bold.** _This is italic._ **_This is bold and italic._** This is plain.
137
+
138
+ ## API
139
+
140
+ ```ts
141
+ function createChainOfResponsibility<Request = undefined, Props = { children?: never }, Init = undefined>(
142
+ options?: Options
143
+ ): {
144
+ Provider: ComponentType<ProviderProps<Request, Props, Init>>;
145
+ Proxy: ComponentType<ProxyProps<Request, Props>>;
146
+ types: {
147
+ init: Init;
148
+ middleware: ComponentMiddleware<Request, Props, Init>;
149
+ props: Props;
150
+ request: Request;
151
+ };
152
+ useBuildComponentCallback: () => UseBuildComponent<Request, Props>;
153
+ };
154
+ ```
155
+
156
+ ### Return value
157
+
158
+ | Name | Type | Description |
159
+ | --------------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------- |
160
+ | `Provider` | `React.ComponentType` | Entrypoint component, must wraps all usage of customizations |
161
+ | `Proxy` | `React.ComponentType` | Proxy component, process the `request` from props and morph into the result component |
162
+ | `types` | `{ init, middleware, props, request }` | TypeScript: shorthand types, all objects are `undefined` intentionally |
163
+ | `useBuildComponentCallback` | `() => (request, options) => React.ComponentType` | Callback hook which return a function to build the component for rendering the result |
164
+
165
+ ### Options
166
+
167
+ ```ts
168
+ type Options = {
169
+ /** Allows a middleware to pass another request object to its next middleware. Default is false. */
170
+ passModifiedRequest?: boolean;
171
+ };
172
+ ```
173
+
174
+ If `passModifiedRequest` is default or `false`, middleware will not be allowed to pass another reference of `request` object to their `next()` middleware. Instead, the `request` object passed to `next()` will be ignored and the next middleware always receive the original `request` object. This behavior is similar to [ExpressJS](https://expressjs.com/) middleware.
175
+
176
+ Setting to `true` will enable advanced scenarios and allow a middleware to influence their downstreamers.
177
+
178
+ When the option is default or `false`, middleware could still modify the `request` object and influence their downstreamers. It is recommended to follow immutable pattern when handling the `request` object, or use deep [`Object.freeze()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) to guarantee immutability.
179
+
180
+ ### API of `useBuildComponentCallback`
181
+
182
+ ```ts
183
+ type UseBuildComponentCallbackOptions<Props> = { fallbackComponent?: ComponentType<Props> | false | null | undefined };
184
+
185
+ type UseBuildComponentCallback<Request, Props> = (
186
+ request: Request,
187
+ options?: UseBuildComponentCallbackOptions<Props>
188
+ ) => ComponentType<Props> | false | null | undefined;
189
+ ```
190
+
191
+ The `fallbackComponent` is a component which all unhandled requests will sink into.
192
+
193
+ ### API for Fluent UI
194
+
195
+ ```ts
196
+ export default function createChainOfResponsibilityForFluentUI<Props extends {}, Init = undefined>(
197
+ options?: Options
198
+ ): ReturnType<typeof createChainOfResponsibility<Props | undefined, Props, Init>> & {
199
+ useBuildRenderFunction: useBuildRenderFunction<Props>;
200
+ };
201
+ ```
202
+
203
+ #### Return value
204
+
205
+ | Name | Type | Description |
206
+ | ------------------------ | ---------------------------------------- | ---------------------------------------------------------------- |
207
+ | `useBuildRenderFunction` | `({ getKey }) => IRenderFunction<Props>` | Callback hook to build the `IRenderFunction` to use in Fluent UI |
208
+
209
+ #### API of `useBuildRenderFunction`
210
+
211
+ ```ts
212
+ type UseBuildRenderFunctionOptions<Props> = { getKey?: (props: Props | undefined) => Key };
213
+
214
+ type UseBuildRenderFunction<Props> = (options?: UseBuildRenderFunctionOptions<Props>) => IRenderFunction<Props>;
215
+ ```
216
+
217
+ When rendering the element, `getKey` is called to compute the `key` attribute. This is required for some `onRenderXXX` props. These props are usually used to render more than one elements, such as [`DetailsList.onRenderField`](https://developer.microsoft.com/en-us/fluentui#/controls/web/detailslist#implementation), which renders every field (a.k.a. cell) in the [`<DetailsList>`](https://developer.microsoft.com/en-us/fluentui#/controls/web/detailslist).
218
+
219
+ ## Designs
220
+
221
+ ### Why the type of request and props can be different?
222
+
223
+ This approach may seem overkill at first.
224
+
225
+ This is to support advanced scenarios where props are not ready until all rendering components are built.
226
+
227
+ For example, in a chat UI, the middleware is used to influence how the message bubble is rendered, say, a text message vs. an image vs. a hidden message.
228
+
229
+ The message bubble is responsible to render its timestamp. However, if timestamp grouping is enabled, timestamps in some bubbles will not be rendered if its neighboring bubble render the timestamp. This is also true for avatar grouping.
230
+
231
+ At component build-time (with the request object), it is not known if a message bubble should render its timestamp or not. This is because we do not know their neighbors yet. At render-time (with props), because all components are prepared, we can start telling each message bubble if they should render their timestamp.
232
+
233
+ We need to put some logics between build-time and render-time to support grouping. This needs to be a "two-pass" operation because avatar grouping and timestamp grouping look up neighbors in a different direction:
234
+
235
+ - Avatar grouping look at _predecessors_
236
+ - If an earlier message already rendered the avatar, it should not render again
237
+ - Timestamp grouping look at _successors_
238
+ - If a latter message is going to render the timestamp, it should not render it now
239
+
240
+ ### Why the middleware should return component instead of element?
241
+
242
+ Despite its complexity, there are several advantages when returning component:
243
+
244
+ - We know if a request would render or not render a request
245
+ - If it would render, middleware will return a component
246
+ - If it would not render, middleware will return `false`/`null`/`undefined`
247
+ - Components works with hooks in a more natural way
248
+ - Build-time and render-time are separated to support advanced scenarios
249
+
250
+ ### Why we call the handler "middleware"?
251
+
252
+ "Handler" is often seen in articles explaining the chain of responsibility design pattern. They are typically written in a language-agnostic format, such as pseudo code.
253
+
254
+ However, "middleware" is a more popular word in JavaScript community. Thus, we chose "middleware".
255
+
256
+ ### Why we need to call `createChainOfResponsibility()` to create `<Provider>`?
257
+
258
+ This is for supporting multiple providers/proxies under a single app/tree.
259
+
260
+ ### Why we disable `passModifiedRequest` by default?
261
+
262
+ To reduce learning curve and likelihood of bugs, we disabled this feature until developers are more proficient with this package.
263
+
264
+ If the `request` object passed to `next()` differs from the original `request` object, a reminder will be logged in the console.
265
+
266
+ ## Behaviors
267
+
268
+ ### `<Proxy>` vs. `useBuildComponentCallback`
269
+
270
+ Most of the time, use `<Proxy>`.
271
+
272
+ Behind the scene, `<Proxy>` call `useBuildComponentCallback()` to build the component it would morph into.
273
+
274
+ You can use the following decision tree to know when to use `<Proxy>` vs. `useBuildComponentCallback`
275
+
276
+ - If you want to know what component will render before actual render happen, use `useBuildComponentCallback()`
277
+ - For example, using `useBuildComponentCallback()` allow you to know if the middleware will skip rendering the request
278
+ - If your component use `request` prop which is conflict with `<Proxy>`, use `useBuildComponentCallback()`
279
+ - Otherwise, use `<Proxy>`
280
+
281
+ ### Calling `next()` multiple times
282
+
283
+ It is possible to call `next()` multiple times to render multiple copies of UI. Middleware should be written as a stateless function.
284
+
285
+ This is best used with options `passModifiedRequest` set to `true`. This combination allow a middleware to render the UI multiple times with some variations, such as rendering content and minimap at the same time.
286
+
287
+ ### Calling `next()` later
288
+
289
+ This is not supported.
290
+
291
+ This is because React does not allow asynchronous render. An exception will be thrown if the `next()` is called after return.
292
+
293
+ ### Good middleware is stateless
294
+
295
+ When writing middleware, keep them as stateless as possible and do not relies on data outside of the `request` object. The way it is writing should be similar to React function components.
296
+
297
+ ### Good middleware returns false to skip rendering
298
+
299
+ If the middleware wants to skip rendering a request, return `false`/`null`/`undefined` directly. Do not return `() => false`, `<Fragment />`, or any other invisible components.
300
+
301
+ This helps the component which send the request to the chain of responsibility to determine whether the request could be rendered or not.
302
+
303
+ ### Typing a component which expect no props to be passed
304
+
305
+ To type a component which expects no props to be passed, use `ComponentType<{ children?: undefined }>`.
306
+
307
+ In TypeScript, `{}` literally means any objects. Components of type `ComponentType<{}>` means [anything can be passed as props](https://www.typescriptlang.org/play?#code/C4TwDgpgBACgTgezAZygXigbwL4G4BQ+AxggHbLBRiIoBcsNqGmUyCAthMABYCWpAc3oByCABtkEYVDz4gA).
308
+
309
+ Although `Record<any, never>` means empty object, it is not extensible. Thus, [`Record<any, never> & { className: string }` means `Record<any, never>`](https://www.typescriptlang.org/play?#code/C4TwDgpgBACgTgezAZygXigJQgYwXAEwB4BDAOxABooyIA3COAPgG4AoUSKAZQFcAjeElQYhKKADIoAbyg4ANiWTIAciQC2EAFxRkwOAEsyAcygBfdmzxk9UMIhQ6+ghyJlzFytZp0BydSRGvubsQA).
310
+
311
+ We believe the best way to type a component which does not allow any props, is `ComponentType<{ children?: undefined }>`.
312
+
313
+ ## Inspirations
314
+
315
+ This package is heavily inspired by [Redux](https://redux.js.org/) middleware, especially [`applyMiddleware()`](https://github.com/reduxjs/redux/blob/master/docs/api/applyMiddleware.md) and [`compose()`](https://github.com/reduxjs/redux/blob/master/docs/api/compose.md). We read [this article](https://medium.com/@jacobp100/you-arent-using-redux-middleware-enough-94ffe991e6) to understand the concept, followed by some more readings on functional programming topics.
316
+
317
+ Over multiple years, the chain of responsibility design pattern is proven to be very flexible and extensible in [Bot Framework Web Chat](https://github.co/microsoft/BotFramework-WebChat/). Internal parts of Web Chat is written as middleware consumed by itself. Multiple bundles with various sizes can be offered by removing some middleware and treeshaking them off.
318
+
319
+ Middleware and router in [ExpressJS](https://expressjs.com/) also inspired us to learn more about this pattern. Their fallback middleware always returns 404 is an innovative approach.
320
+
321
+ [Bing chat](https://bing.com/chat/) helped us understand and experiment with different naming.
322
+
323
+ ### Differences from Redux and ExpressJS
324
+
325
+ The chain of responsibility design pattern implemented in [Redux](https://redux.js.org/) and [ExpressJS](https://expressjs.com/) prefers fire-and-forget execution (a.k.a. unidirectional): the result from the last middleware will not bubble up back to the first middleware. Instead, the caller may only collect the result from the last middleware. Sometimes, middleware may interrupt the execution and never return any results.
326
+
327
+ However, the chain of responsibility design pattern implemented in this package prefers call-and-return execution: the result from the last middleware will propagate back to the first middleware before returning to the caller. This gives every middleware a chance to manipulate the result from downstreamers before sending it back.
328
+
329
+ ## Plain English
330
+
331
+ This package implements the _chain of responsibility_ design pattern. Based on _request_, the chain of responsibility will be asked to _build a React component_. The middleware will _form a chain_ and request is _passed to the first one in the chain_. If the chain decided to render it, a component will be returned, otherwise, `false`/`null`/`undefined`.
332
+
333
+ ## Contributions
334
+
335
+ Like us? [Star](https://github.com/compulim/react-chain-of-responsibility/stargazers) us.
336
+
337
+ Want to make it better? [File](https://github.com/compulim/react-chain-of-responsibility/issues) us an issue.
338
+
339
+ Don't like something you see? [Submit](https://github.com/compulim/react-chain-of-responsibility/pulls) a pull request.
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+
3
+ var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
4
+ var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
5
+ var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default;
6
+ _Object$defineProperty(exports, "__esModule", {
7
+ value: true
8
+ });
9
+ exports.default = createChainOfResponsibility;
10
+ var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/objectWithoutProperties"));
11
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray"));
12
+ var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof"));
13
+ var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array"));
14
+ var _some = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/some"));
15
+ var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));
16
+ var _reverse = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/reverse"));
17
+ var _propTypes = _interopRequireDefault(require("prop-types"));
18
+ var _react = _interopRequireWildcard(require("react"));
19
+ var _applyMiddleware = _interopRequireDefault(require("./private/applyMiddleware"));
20
+ var _excluded = ["children", "fallbackComponent", "request"];
21
+ function createChainOfResponsibility() {
22
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
23
+ var context = /*#__PURE__*/(0, _react.createContext)({
24
+ get useBuildComponentCallback() {
25
+ throw new Error('useBuildComponentCallback() hook cannot be used outside of its corresponding <Provider>');
26
+ }
27
+ });
28
+ var Provider = function Provider(_ref) {
29
+ var _context;
30
+ var children = _ref.children,
31
+ init = _ref.init,
32
+ middleware = _ref.middleware;
33
+ if (!(0, _isArray.default)(middleware) || (0, _some.default)(middleware).call(middleware, function (middleware) {
34
+ return typeof middleware !== 'function';
35
+ })) {
36
+ throw new Error('middleware prop must be an array of functions');
37
+ }
38
+ var patchedMiddleware = (0, _map.default)(_context = middleware || []).call(_context, function (fn) {
39
+ return function (init) {
40
+ var enhancer = fn(init);
41
+ return function (next) {
42
+ return function (originalRequest) {
43
+ // False positive: although we did not re-assign the variable from true, it was initialized as undefined.
44
+ // eslint-disable-next-line prefer-const
45
+ var hasReturned;
46
+ var returnValue = enhancer(function (nextRequest) {
47
+ if (hasReturned) {
48
+ throw new Error('next() cannot be called after the function had returned synchronously');
49
+ }
50
+ !options.passModifiedRequest && nextRequest !== originalRequest && console.warn('react-chain-of-responsibility: "options.passModifiedRequest" must be set to true to pass a different request object to next().');
51
+ return next(options.passModifiedRequest ? nextRequest : originalRequest);
52
+ })(originalRequest);
53
+ hasReturned = true;
54
+ if ( /*#__PURE__*/(0, _react.isValidElement)(returnValue)) {
55
+ throw new Error('middleware must not return React element directly');
56
+ } else if (returnValue !== false && returnValue !== null && typeof returnValue !== 'function' && typeof returnValue !== 'undefined' &&
57
+ // There are no definitive ways to check if an object is a React component or not.
58
+ // We are checking if the object has a render function (classic component).
59
+ // Note: "forwardRef()" returns plain object, not class instance.
60
+ !((0, _typeof2.default)(returnValue) === 'object' && typeof returnValue['render'] === 'function')) {
61
+ throw new Error('middleware must return false, null, undefined, function component, or class component');
62
+ }
63
+ return returnValue;
64
+ };
65
+ };
66
+ };
67
+ });
68
+ var enhancer = (0, _react.useMemo)(function () {
69
+ var _context2;
70
+ return (
71
+ // We are reversing because it is easier to read:
72
+ // - With reverse, [a, b, c] will become a(b(c(fn)))
73
+ // - Without reverse, [a, b, c] will become c(b(a(fn)))
74
+ _applyMiddleware.default.apply(void 0, (0, _toConsumableArray2.default)((0, _reverse.default)(_context2 = (0, _toConsumableArray2.default)(patchedMiddleware || [])).call(_context2)))(init)
75
+ );
76
+ }, [init, middleware]);
77
+ var useBuildComponentCallback = (0, _react.useCallback)(function (request) {
78
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
79
+ return enhancer(function () {
80
+ return options.fallbackComponent;
81
+ })(request);
82
+ }, [enhancer]);
83
+ var contextValue = (0, _react.useMemo)(function () {
84
+ return {
85
+ useBuildComponentCallback: useBuildComponentCallback
86
+ };
87
+ }, [useBuildComponentCallback]);
88
+ return /*#__PURE__*/_react.default.createElement(context.Provider, {
89
+ value: contextValue
90
+ }, children);
91
+ };
92
+ Provider.defaultProps = {};
93
+ Provider.displayName = 'ChainOfResponsibilityProvider';
94
+ Provider.propTypes = {
95
+ children: _propTypes.default.any,
96
+ init: _propTypes.default.any,
97
+ middleware: _propTypes.default.any
98
+ };
99
+ var useBuildComponentCallback = function useBuildComponentCallback() {
100
+ return (0, _react.useContext)(context).useBuildComponentCallback;
101
+ };
102
+ var Proxy = /*#__PURE__*/(0, _react.memo)(
103
+ // False positive: "children" is not a prop.
104
+ // eslint-disable-next-line react/prop-types
105
+ function (_ref2) {
106
+ var children = _ref2.children,
107
+ fallbackComponent = _ref2.fallbackComponent,
108
+ request = _ref2.request,
109
+ props = (0, _objectWithoutProperties2.default)(_ref2, _excluded);
110
+ var enhancer;
111
+ try {
112
+ enhancer = useBuildComponentCallback();
113
+ } catch (_unused) {
114
+ throw new Error('<Proxy> cannot be used outside of its corresponding <Provider>');
115
+ }
116
+ var Component = enhancer(request, {
117
+ fallbackComponent: fallbackComponent
118
+ });
119
+ return Component ? /*#__PURE__*/_react.default.createElement(Component, props, children) : null;
120
+ });
121
+ Proxy.defaultProps = {};
122
+ Proxy.displayName = 'Proxy';
123
+ Proxy.propTypes = {
124
+ fallbackComponent: _propTypes.default.any,
125
+ request: _propTypes.default.any
126
+ };
127
+ return {
128
+ Provider: Provider,
129
+ Proxy: Proxy,
130
+ types: {
131
+ init: undefined,
132
+ middleware: undefined,
133
+ props: undefined,
134
+ request: undefined
135
+ },
136
+ useBuildComponentCallback: useBuildComponentCallback
137
+ };
138
+ }
139
+ //# sourceMappingURL=createChainOfResponsibility.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createChainOfResponsibility.js","names":["_propTypes","_interopRequireDefault","require","_react","_interopRequireWildcard","_applyMiddleware","_excluded","createChainOfResponsibility","options","arguments","length","undefined","context","createContext","useBuildComponentCallback","Error","Provider","_ref","_context","children","init","middleware","_isArray","default","_some","call","patchedMiddleware","_map","fn","enhancer","next","originalRequest","hasReturned","returnValue","nextRequest","passModifiedRequest","console","warn","isValidElement","_typeof2","useMemo","_context2","applyMiddleware","apply","_toConsumableArray2","_reverse","useCallback","request","fallbackComponent","contextValue","createElement","value","defaultProps","displayName","propTypes","PropTypes","any","useContext","Proxy","memo","_ref2","props","_objectWithoutProperties2","_unused","Component","types"],"sources":["../../src/createChainOfResponsibility.tsx"],"sourcesContent":["import PropTypes from 'prop-types';\nimport React, { ComponentType, createContext, isValidElement, memo, useCallback, useContext, useMemo } from 'react';\n\nimport applyMiddleware from './private/applyMiddleware';\n\nimport type { ComponentMiddleware } from './types';\nimport type { PropsWithChildren } from 'react';\n\ntype UseBuildComponentCallbackOptions<Props> = { fallbackComponent?: ComponentType<Props> | false | null | undefined };\n\ntype UseBuildComponentCallback<Request, Props> = (\n request: Request,\n options?: UseBuildComponentCallbackOptions<Props>\n) => ComponentType<Props> | false | null | undefined;\n\ntype ProviderContext<Request, Props> = {\n useBuildComponentCallback: UseBuildComponentCallback<Request, Props>;\n};\n\ntype ProviderProps<Request, Props, Init> = PropsWithChildren<{\n middleware: ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | undefined ? { init?: Init } : { init: Init });\n\ntype ProxyProps<Request, Props> = Request extends never | undefined\n ? Props & { fallbackComponent?: ComponentType<Props>; request?: Request }\n : Props & { fallbackComponent?: ComponentType<Props>; request: Request };\n\ntype Options = {\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 passModifiedRequest?: boolean;\n};\n\nexport default function createChainOfResponsibility<\n Request = undefined,\n Props = { children?: never },\n Init = undefined\n>(\n options: Options = {}\n): {\n Provider: ComponentType<ProviderProps<Request, Props, Init>>;\n Proxy: ComponentType<ProxyProps<Request, Props>>;\n types: {\n init: Init;\n middleware: ComponentMiddleware<Request, Props, Init>;\n props: Props;\n request: Request;\n };\n useBuildComponentCallback: () => UseBuildComponentCallback<Request, Props>;\n} {\n const context = createContext<ProviderContext<Request, Props>>({\n get useBuildComponentCallback(): ProviderContext<Request, Props>['useBuildComponentCallback'] {\n throw new Error('useBuildComponentCallback() hook cannot be used outside of its corresponding <Provider>');\n }\n });\n\n const Provider: ComponentType<ProviderProps<Request, Props, Init>> = ({ children, init, middleware }) => {\n if (!Array.isArray(middleware) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('middleware prop must be an array of functions');\n }\n\n const patchedMiddleware: ComponentMiddleware<Request, Props, Init>[] = (middleware || []).map(fn => {\n return 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('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 !== 'function' &&\n typeof returnValue !== 'undefined' &&\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.\n !(typeof returnValue === 'object' && typeof returnValue['render'] === 'function')\n ) {\n throw new Error('middleware must return false, null, undefined, function component, or class component');\n }\n\n return returnValue;\n };\n };\n });\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], ComponentType<Props> | false | null | undefined, [Init]>(\n ...[...(patchedMiddleware || [])].reverse()\n )(init as Init),\n [init, middleware]\n );\n\n const useBuildComponentCallback = useCallback<UseBuildComponentCallback<Request, Props>>(\n (request, options = {}) => enhancer(() => options.fallbackComponent)(request),\n [enhancer]\n );\n\n const contextValue = useMemo<ProviderContext<Request, Props>>(\n () => ({ useBuildComponentCallback }),\n [useBuildComponentCallback]\n );\n\n return <context.Provider value={contextValue}>{children}</context.Provider>;\n };\n\n Provider.defaultProps = {};\n Provider.displayName = 'ChainOfResponsibilityProvider';\n Provider.propTypes = {\n children: PropTypes.any,\n init: PropTypes.any,\n middleware: PropTypes.any\n };\n\n const useBuildComponentCallback = () => useContext(context).useBuildComponentCallback;\n\n const Proxy: ComponentType<ProxyProps<Request, Props>> = memo(\n // False positive: \"children\" is not a prop.\n // eslint-disable-next-line react/prop-types\n ({ children, fallbackComponent, request, ...props }) => {\n let enhancer: ReturnType<typeof useBuildComponentCallback>;\n\n try {\n enhancer = useBuildComponentCallback();\n } catch {\n throw new Error('<Proxy> cannot be used outside of its corresponding <Provider>');\n }\n\n const Component = enhancer(request as Request, { fallbackComponent });\n\n return Component ? <Component {...(props as Props)}>{children}</Component> : null;\n }\n );\n\n Proxy.defaultProps = {};\n Proxy.displayName = 'Proxy';\n Proxy.propTypes = {\n fallbackComponent: PropTypes.any,\n request: PropTypes.any\n };\n\n return {\n Provider,\n Proxy,\n types: {\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 request: undefined as unknown as Request\n },\n useBuildComponentCallback\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,IAAAA,UAAA,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C,KAAA,EAAAtD,SAAA;IAC/C,IAAIuB,QAAsD;IAE1D,IAAI;MACFA,QAAQ,GAAGf,yBAAyB,EAAE;IACxC,CAAC,CAAC,OAAAiD,OAAA,EAAM;MACN,MAAM,IAAIhD,KAAK,CAAC,gEAAgE,CAAC;IACnF;IAEA,IAAMiD,SAAS,GAAGnC,QAAQ,CAACkB,OAAO,EAAa;MAAEC,iBAAiB,EAAjBA;IAAkB,CAAC,CAAC;IAErE,OAAOgB,SAAS,gBAAG7D,MAAA,CAAAoB,OAAA,CAAA2B,aAAA,CAACc,SAAS,EAAMH,KAAK,EAAa1C,QAAQ,CAAa,GAAG,IAAI;EACnF,CAAC,CACF;EAEDuC,KAAK,CAACN,YAAY,GAAG,CAAC,CAAC;EACvBM,KAAK,CAACL,WAAW,GAAG,OAAO;EAC3BK,KAAK,CAACJ,SAAS,GAAG;IAChBN,iBAAiB,EAAEO,kBAAS,CAACC,GAAG;IAChCT,OAAO,EAAEQ,kBAAS,CAACC;EACrB,CAAC;EAED,OAAO;IACLxC,QAAQ,EAARA,QAAQ;IACR0C,KAAK,EAALA,KAAK;IACLO,KAAK,EAAE;MACL7C,IAAI,EAAET,SAA4B;MAClCU,UAAU,EAAEV,SAAiE;MAC7EkD,KAAK,EAAElD,SAA6B;MACpCoC,OAAO,EAAEpC;IACX,CAAC;IACDG,yBAAyB,EAAzBA;EACF,CAAC;AACH"}
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+
3
+ var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
4
+ var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default;
5
+ var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
6
+ _Object$defineProperty(exports, "__esModule", {
7
+ value: true
8
+ });
9
+ exports.default = createChainOfResponsibilityForFluentUI;
10
+ var _objectSpread2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/objectSpread2"));
11
+ var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));
12
+ var _react = _interopRequireWildcard(require("react"));
13
+ var _createChainOfResponsibility = _interopRequireDefault(require("./createChainOfResponsibility"));
14
+ // We are using the props as both "Request" and "Props".
15
+ // This should eases migration from `onRender` to chain of responsibility.
16
+ // Downside is, web developers could accidentally pass request as props and not honoring props modified by upstreamers.
17
+ function createChainOfResponsibilityForFluentUI(options) {
18
+ var returnValue = (0, _createChainOfResponsibility.default)(options);
19
+ var Proxy = returnValue.Proxy;
20
+ var useBuildRenderFunction = function useBuildRenderFunction() {
21
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
22
+ var getKey = options.getKey;
23
+ return (0, _react.useCallback)(function (props, defaultRender) {
24
+ return /*#__PURE__*/_react.default.createElement(Proxy, (0, _extends2.default)({}, props, {
25
+ fallbackComponent: defaultRender,
26
+ key: getKey === null || getKey === void 0 ? void 0 : getKey(props),
27
+ request: props
28
+ }));
29
+ }, [getKey]);
30
+ };
31
+ return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, returnValue), {}, {
32
+ useBuildRenderFunction: useBuildRenderFunction
33
+ });
34
+ }
35
+ //# sourceMappingURL=createChainOfResponsibilityForFluentUI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createChainOfResponsibilityForFluentUI.js","names":["_react","_interopRequireWildcard","require","_createChainOfResponsibility","_interopRequireDefault","createChainOfResponsibilityForFluentUI","options","returnValue","createChainOfResponsibility","Proxy","useBuildRenderFunction","arguments","length","undefined","getKey","useCallback","props","defaultRender","default","createElement","_extends2","fallbackComponent","key","request","_objectSpread2"],"sources":["../../src/createChainOfResponsibilityForFluentUI.tsx"],"sourcesContent":["import React, { useCallback } from 'react';\n\nimport createChainOfResponsibility from './createChainOfResponsibility';\n\nimport type { IRenderFunction } from '@fluentui/react';\nimport type { Key } from 'react';\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.\nexport default function createChainOfResponsibilityForFluentUI<Props extends object, Init = undefined>(\n options?: Parameters<typeof createChainOfResponsibility>[0]\n): ReturnType<typeof createChainOfResponsibility<Props | undefined, Props, Init>> & {\n useBuildRenderFunction: UseBuildRenderFunction<Props>;\n} {\n const returnValue = createChainOfResponsibility<Props | undefined, Props, Init>(options);\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 <Proxy {...(props as Props)} fallbackComponent={defaultRender} key={getKey?.(props)} request={props} />\n ),\n [getKey]\n );\n };\n\n return { ...returnValue, useBuildRenderFunction };\n}\n"],"mappings":";;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,uBAAA,CAAAC,OAAA;AAEA,IAAAC,4BAAA,GAAAC,sBAAA,CAAAF,OAAA;AASA;AACA;AACA;AACe,SAASG,sCAAsCA,CAC5DC,OAA2D,EAG3D;EACA,IAAMC,WAAW,GAAG,IAAAC,oCAA2B,EAAiCF,OAAO,CAAC;EAExF,IAAQG,KAAK,GAAKF,WAAW,CAArBE,KAAK;EAEb,IAAMC,sBAAqD,GAAG,SAAxDA,sBAAqDA,CAAA,EAAqB;IAAA,IAAjBJ,OAAO,GAAAK,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;IACzE,IAAQG,MAAM,GAAKR,OAAO,CAAlBQ,MAAM;IAEd,OAAO,IAAAC,kBAAW,EAChB,UAACC,KAAK,EAAEC,aAAa;MAAA,oBACnBjB,MAAA,CAAAkB,OAAA,CAAAC,aAAA,CAACV,KAAK,MAAAW,SAAA,CAAAF,OAAA,MAAMF,KAAK;QAAYK,iBAAiB,EAAEJ,aAAc;QAACK,GAAG,EAAER,MAAM,aAANA,MAAM,uBAANA,MAAM,CAAGE,KAAK,CAAE;QAACO,OAAO,EAAEP;MAAM,GAAG;IAAA,CACxG,EACD,CAACF,MAAM,CAAC,CACT;EACH,CAAC;EAED,WAAAU,cAAA,CAAAN,OAAA,MAAAM,cAAA,CAAAN,OAAA,MAAYX,WAAW;IAAEG,sBAAsB,EAAtBA;EAAsB;AACjD"}
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+
3
+ var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
4
+ var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
5
+ _Object$defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ _Object$defineProperty(exports, "createChainOfResponsibility", {
9
+ enumerable: true,
10
+ get: function get() {
11
+ return _createChainOfResponsibility.default;
12
+ }
13
+ });
14
+ _Object$defineProperty(exports, "createChainOfResponsibilityForFluentUI", {
15
+ enumerable: true,
16
+ get: function get() {
17
+ return _createChainOfResponsibilityForFluentUI.default;
18
+ }
19
+ });
20
+ var _createChainOfResponsibility = _interopRequireDefault(require("./createChainOfResponsibility"));
21
+ var _createChainOfResponsibilityForFluentUI = _interopRequireDefault(require("./createChainOfResponsibilityForFluentUI"));
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["_createChainOfResponsibility","_interopRequireDefault","require","_createChainOfResponsibilityForFluentUI"],"sources":["../../src/index.ts"],"sourcesContent":["import createChainOfResponsibility from './createChainOfResponsibility';\nimport createChainOfResponsibilityForFluentUI from './createChainOfResponsibilityForFluentUI';\n\nimport type { ComponentMiddleware } from './types';\n\nexport { createChainOfResponsibility, createChainOfResponsibilityForFluentUI };\n\nexport type { ComponentMiddleware };\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,IAAAA,4BAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,uCAAA,GAAAF,sBAAA,CAAAC,OAAA"}
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+
3
+ var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
4
+ var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
5
+ _Object$defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.default = applyMiddleware;
9
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray"));
10
+ var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));
11
+ var _compose = _interopRequireDefault(require("./compose"));
12
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
13
+ function applyMiddleware() {
14
+ for (var _len = arguments.length, arrayOfMiddleware = new Array(_len), _key = 0; _key < _len; _key++) {
15
+ arrayOfMiddleware[_key] = arguments[_key];
16
+ }
17
+ return function () {
18
+ for (var _len2 = arguments.length, init = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
19
+ init[_key2] = arguments[_key2];
20
+ }
21
+ var chain = (0, _map.default)(arrayOfMiddleware).call(arrayOfMiddleware, function (middleware) {
22
+ return middleware.apply(void 0, init);
23
+ });
24
+ return _compose.default.apply(void 0, (0, _toConsumableArray2.default)(chain));
25
+ };
26
+ }
27
+ //# sourceMappingURL=applyMiddleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"applyMiddleware.js","names":["_compose","_interopRequireDefault","require","applyMiddleware","_len","arguments","length","arrayOfMiddleware","Array","_key","_len2","init","_key2","chain","_map","default","call","middleware","apply","compose","_toConsumableArray2"],"sources":["../../../src/private/applyMiddleware.ts"],"sourcesContent":["import compose from './compose';\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,IAAAA,QAAA,GAAAC,sBAAA,CAAAC,OAAA;AAWA;AACe,SAASC,eAAeA,CAAA,EAErC;EAAA,SAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EADGC,iBAAiB,OAAAC,KAAA,CAAAJ,IAAA,GAAAK,IAAA,MAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA;IAAjBF,iBAAiB,CAAAE,IAAA,IAAAJ,SAAA,CAAAI,IAAA;EAAA;EAEpB,OAAO,YAAgB;IAAA,SAAAC,KAAA,GAAAL,SAAA,CAAAC,MAAA,EAAZK,IAAI,OAAAH,KAAA,CAAAE,KAAA,GAAAE,KAAA,MAAAA,KAAA,GAAAF,KAAA,EAAAE,KAAA;MAAJD,IAAI,CAAAC,KAAA,IAAAP,SAAA,CAAAO,KAAA;IAAA;IACb,IAAMC,KAAK,GAAG,IAAAC,IAAA,CAAAC,OAAA,EAAAR,iBAAiB,EAAAS,IAAA,CAAjBT,iBAAiB,EAAK,UAAAU,UAAU;MAAA,OAAIA,UAAU,CAAAC,KAAA,SAAIP,IAAI,CAAC;IAAA,EAAC;IAEtE,OAAOQ,gBAAO,CAAAD,KAAA,aAAAE,mBAAA,CAAAL,OAAA,EAAIF,KAAK,EAAC;EAC1B,CAAC;AACH"}
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+
3
+ var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
4
+ var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
5
+ _Object$defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.default = compose;
9
+ var _reduce = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/reduce"));
10
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
11
+
12
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
13
+
14
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
+ function compose() {
16
+ for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
17
+ fns[_key] = arguments[_key];
18
+ }
19
+ return function (fn) {
20
+ return (0, _reduce.default)(fns).call(fns, function (chain, fn) {
21
+ return fn(chain);
22
+ }, fn);
23
+ };
24
+ }
25
+ //# sourceMappingURL=compose.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.js","names":["compose","_len","arguments","length","fns","Array","_key","fn","_reduce","default","call","chain"],"sources":["../../../src/private/compose.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"],"mappings":";;;;;;;;;AAAA;;AAGA;;AAGA;AACe,SAASA,OAAOA,CAAA,EAA+D;EAAA,SAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAAvCC,GAAG,OAAAC,KAAA,CAAAJ,IAAA,GAAAK,IAAA,MAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA;IAAHF,GAAG,CAAAE,IAAA,IAAAJ,SAAA,CAAAI,IAAA;EAAA;EACxD,OAAO,UAACC,EAAY;IAAA,OAAe,IAAAC,OAAA,CAAAC,OAAA,EAAAL,GAAG,EAAAM,IAAA,CAAHN,GAAG,EAAQ,UAACO,KAAK,EAAEJ,EAAE;MAAA,OAAKA,EAAE,CAACI,KAAK,CAAC;IAAA,GAAEJ,EAAE,CAAC;EAAA;AAC7E"}
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/types.ts"],"sourcesContent":["import type { ComponentType } from 'react';\nimport type { Middleware } from './private/applyMiddleware';\n\nexport type ComponentMiddleware<Request, Props = { children?: never }, Init = undefined> = Middleware<\n [Request],\n ComponentType<Props> | false | null | undefined,\n [Init]\n>;\n"],"mappings":""}
@@ -0,0 +1,130 @@
1
+ import _objectWithoutProperties from "@babel/runtime-corejs3/helpers/objectWithoutProperties";
2
+ import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
3
+ import _typeof from "@babel/runtime-corejs3/helpers/typeof";
4
+ var _excluded = ["children", "fallbackComponent", "request"];
5
+ import _Array$isArray from "@babel/runtime-corejs3/core-js-stable/array/is-array";
6
+ import _someInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/some";
7
+ import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
8
+ import _reverseInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/reverse";
9
+ import PropTypes from 'prop-types';
10
+ import React, { createContext, isValidElement, memo, useCallback, useContext, useMemo } from 'react';
11
+ import applyMiddleware from './private/applyMiddleware';
12
+ export default function createChainOfResponsibility() {
13
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
14
+ var context = /*#__PURE__*/createContext({
15
+ get useBuildComponentCallback() {
16
+ throw new Error('useBuildComponentCallback() hook cannot be used outside of its corresponding <Provider>');
17
+ }
18
+ });
19
+ var Provider = function Provider(_ref) {
20
+ var _context;
21
+ var children = _ref.children,
22
+ init = _ref.init,
23
+ middleware = _ref.middleware;
24
+ if (!_Array$isArray(middleware) || _someInstanceProperty(middleware).call(middleware, function (middleware) {
25
+ return typeof middleware !== 'function';
26
+ })) {
27
+ throw new Error('middleware prop must be an array of functions');
28
+ }
29
+ var patchedMiddleware = _mapInstanceProperty(_context = middleware || []).call(_context, function (fn) {
30
+ return function (init) {
31
+ var enhancer = fn(init);
32
+ return function (next) {
33
+ return function (originalRequest) {
34
+ // False positive: although we did not re-assign the variable from true, it was initialized as undefined.
35
+ // eslint-disable-next-line prefer-const
36
+ var hasReturned;
37
+ var returnValue = enhancer(function (nextRequest) {
38
+ if (hasReturned) {
39
+ throw new Error('next() cannot be called after the function had returned synchronously');
40
+ }
41
+ !options.passModifiedRequest && nextRequest !== originalRequest && console.warn('react-chain-of-responsibility: "options.passModifiedRequest" must be set to true to pass a different request object to next().');
42
+ return next(options.passModifiedRequest ? nextRequest : originalRequest);
43
+ })(originalRequest);
44
+ hasReturned = true;
45
+ if ( /*#__PURE__*/isValidElement(returnValue)) {
46
+ throw new Error('middleware must not return React element directly');
47
+ } else if (returnValue !== false && returnValue !== null && typeof returnValue !== 'function' && typeof returnValue !== 'undefined' &&
48
+ // There are no definitive ways to check if an object is a React component or not.
49
+ // We are checking if the object has a render function (classic component).
50
+ // Note: "forwardRef()" returns plain object, not class instance.
51
+ !(_typeof(returnValue) === 'object' && typeof returnValue['render'] === 'function')) {
52
+ throw new Error('middleware must return false, null, undefined, function component, or class component');
53
+ }
54
+ return returnValue;
55
+ };
56
+ };
57
+ };
58
+ });
59
+ var enhancer = useMemo(function () {
60
+ var _context2;
61
+ return (
62
+ // We are reversing because it is easier to read:
63
+ // - With reverse, [a, b, c] will become a(b(c(fn)))
64
+ // - Without reverse, [a, b, c] will become c(b(a(fn)))
65
+ applyMiddleware.apply(void 0, _toConsumableArray(_reverseInstanceProperty(_context2 = _toConsumableArray(patchedMiddleware || [])).call(_context2)))(init)
66
+ );
67
+ }, [init, middleware]);
68
+ var useBuildComponentCallback = useCallback(function (request) {
69
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
70
+ return enhancer(function () {
71
+ return options.fallbackComponent;
72
+ })(request);
73
+ }, [enhancer]);
74
+ var contextValue = useMemo(function () {
75
+ return {
76
+ useBuildComponentCallback: useBuildComponentCallback
77
+ };
78
+ }, [useBuildComponentCallback]);
79
+ return /*#__PURE__*/React.createElement(context.Provider, {
80
+ value: contextValue
81
+ }, children);
82
+ };
83
+ Provider.defaultProps = {};
84
+ Provider.displayName = 'ChainOfResponsibilityProvider';
85
+ Provider.propTypes = {
86
+ children: PropTypes.any,
87
+ init: PropTypes.any,
88
+ middleware: PropTypes.any
89
+ };
90
+ var useBuildComponentCallback = function useBuildComponentCallback() {
91
+ return useContext(context).useBuildComponentCallback;
92
+ };
93
+ var Proxy = /*#__PURE__*/memo(
94
+ // False positive: "children" is not a prop.
95
+ // eslint-disable-next-line react/prop-types
96
+ function (_ref2) {
97
+ var children = _ref2.children,
98
+ fallbackComponent = _ref2.fallbackComponent,
99
+ request = _ref2.request,
100
+ props = _objectWithoutProperties(_ref2, _excluded);
101
+ var enhancer;
102
+ try {
103
+ enhancer = useBuildComponentCallback();
104
+ } catch (_unused) {
105
+ throw new Error('<Proxy> cannot be used outside of its corresponding <Provider>');
106
+ }
107
+ var Component = enhancer(request, {
108
+ fallbackComponent: fallbackComponent
109
+ });
110
+ return Component ? /*#__PURE__*/React.createElement(Component, props, children) : null;
111
+ });
112
+ Proxy.defaultProps = {};
113
+ Proxy.displayName = 'Proxy';
114
+ Proxy.propTypes = {
115
+ fallbackComponent: PropTypes.any,
116
+ request: PropTypes.any
117
+ };
118
+ return {
119
+ Provider: Provider,
120
+ Proxy: Proxy,
121
+ types: {
122
+ init: undefined,
123
+ middleware: undefined,
124
+ props: undefined,
125
+ request: undefined
126
+ },
127
+ useBuildComponentCallback: useBuildComponentCallback
128
+ };
129
+ }
130
+ //# sourceMappingURL=createChainOfResponsibility.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createChainOfResponsibility.js","names":["PropTypes","React","createContext","isValidElement","memo","useCallback","useContext","useMemo","applyMiddleware","createChainOfResponsibility","options","arguments","length","undefined","context","useBuildComponentCallback","Error","Provider","_ref","_context","children","init","middleware","_Array$isArray","_someInstanceProperty","call","patchedMiddleware","_mapInstanceProperty","fn","enhancer","next","originalRequest","hasReturned","returnValue","nextRequest","passModifiedRequest","console","warn","_typeof","_context2","apply","_toConsumableArray","_reverseInstanceProperty","request","fallbackComponent","contextValue","createElement","value","defaultProps","displayName","propTypes","any","Proxy","_ref2","props","_objectWithoutProperties","_excluded","_unused","Component","types"],"sources":["../../src/createChainOfResponsibility.tsx"],"sourcesContent":["import PropTypes from 'prop-types';\nimport React, { ComponentType, createContext, isValidElement, memo, useCallback, useContext, useMemo } from 'react';\n\nimport applyMiddleware from './private/applyMiddleware';\n\nimport type { ComponentMiddleware } from './types';\nimport type { PropsWithChildren } from 'react';\n\ntype UseBuildComponentCallbackOptions<Props> = { fallbackComponent?: ComponentType<Props> | false | null | undefined };\n\ntype UseBuildComponentCallback<Request, Props> = (\n request: Request,\n options?: UseBuildComponentCallbackOptions<Props>\n) => ComponentType<Props> | false | null | undefined;\n\ntype ProviderContext<Request, Props> = {\n useBuildComponentCallback: UseBuildComponentCallback<Request, Props>;\n};\n\ntype ProviderProps<Request, Props, Init> = PropsWithChildren<{\n middleware: ComponentMiddleware<Request, Props, Init>[];\n}> &\n (Init extends never | undefined ? { init?: Init } : { init: Init });\n\ntype ProxyProps<Request, Props> = Request extends never | undefined\n ? Props & { fallbackComponent?: ComponentType<Props>; request?: Request }\n : Props & { fallbackComponent?: ComponentType<Props>; request: Request };\n\ntype Options = {\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 passModifiedRequest?: boolean;\n};\n\nexport default function createChainOfResponsibility<\n Request = undefined,\n Props = { children?: never },\n Init = undefined\n>(\n options: Options = {}\n): {\n Provider: ComponentType<ProviderProps<Request, Props, Init>>;\n Proxy: ComponentType<ProxyProps<Request, Props>>;\n types: {\n init: Init;\n middleware: ComponentMiddleware<Request, Props, Init>;\n props: Props;\n request: Request;\n };\n useBuildComponentCallback: () => UseBuildComponentCallback<Request, Props>;\n} {\n const context = createContext<ProviderContext<Request, Props>>({\n get useBuildComponentCallback(): ProviderContext<Request, Props>['useBuildComponentCallback'] {\n throw new Error('useBuildComponentCallback() hook cannot be used outside of its corresponding <Provider>');\n }\n });\n\n const Provider: ComponentType<ProviderProps<Request, Props, Init>> = ({ children, init, middleware }) => {\n if (!Array.isArray(middleware) || middleware.some(middleware => typeof middleware !== 'function')) {\n throw new Error('middleware prop must be an array of functions');\n }\n\n const patchedMiddleware: ComponentMiddleware<Request, Props, Init>[] = (middleware || []).map(fn => {\n return 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('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 !== 'function' &&\n typeof returnValue !== 'undefined' &&\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.\n !(typeof returnValue === 'object' && typeof returnValue['render'] === 'function')\n ) {\n throw new Error('middleware must return false, null, undefined, function component, or class component');\n }\n\n return returnValue;\n };\n };\n });\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], ComponentType<Props> | false | null | undefined, [Init]>(\n ...[...(patchedMiddleware || [])].reverse()\n )(init as Init),\n [init, middleware]\n );\n\n const useBuildComponentCallback = useCallback<UseBuildComponentCallback<Request, Props>>(\n (request, options = {}) => enhancer(() => options.fallbackComponent)(request),\n [enhancer]\n );\n\n const contextValue = useMemo<ProviderContext<Request, Props>>(\n () => ({ useBuildComponentCallback }),\n [useBuildComponentCallback]\n );\n\n return <context.Provider value={contextValue}>{children}</context.Provider>;\n };\n\n Provider.defaultProps = {};\n Provider.displayName = 'ChainOfResponsibilityProvider';\n Provider.propTypes = {\n children: PropTypes.any,\n init: PropTypes.any,\n middleware: PropTypes.any\n };\n\n const useBuildComponentCallback = () => useContext(context).useBuildComponentCallback;\n\n const Proxy: ComponentType<ProxyProps<Request, Props>> = memo(\n // False positive: \"children\" is not a prop.\n // eslint-disable-next-line react/prop-types\n ({ children, fallbackComponent, request, ...props }) => {\n let enhancer: ReturnType<typeof useBuildComponentCallback>;\n\n try {\n enhancer = useBuildComponentCallback();\n } catch {\n throw new Error('<Proxy> cannot be used outside of its corresponding <Provider>');\n }\n\n const Component = enhancer(request as Request, { fallbackComponent });\n\n return Component ? <Component {...(props as Props)}>{children}</Component> : null;\n }\n );\n\n Proxy.defaultProps = {};\n Proxy.displayName = 'Proxy';\n Proxy.propTypes = {\n fallbackComponent: PropTypes.any,\n request: PropTypes.any\n };\n\n return {\n Provider,\n Proxy,\n types: {\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 request: undefined as unknown as Request\n },\n useBuildComponentCallback\n };\n}\n"],"mappings":";;;;;;;;AAAA,OAAOA,SAAS,MAAM,YAAY;AAClC,OAAOC,KAAK,IAAmBC,aAAa,EAAEC,cAAc,EAAEC,IAAI,EAAEC,WAAW,EAAEC,UAAU,EAAEC,OAAO,QAAQ,OAAO;AAEnH,OAAOC,eAAe,M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aAAA,CAACY,SAAS,EAAMJ,KAAK,EAAalC,QAAQ,CAAa,GAAG,IAAI;EACnF,CAAC,CACF;EAEDgC,KAAK,CAACJ,YAAY,GAAG,CAAC,CAAC;EACvBI,KAAK,CAACH,WAAW,GAAG,OAAO;EAC3BG,KAAK,CAACF,SAAS,GAAG;IAChBN,iBAAiB,EAAE5C,SAAS,CAACmD,GAAG;IAChCR,OAAO,EAAE3C,SAAS,CAACmD;EACrB,CAAC;EAED,OAAO;IACLlC,QAAQ,EAARA,QAAQ;IACRmC,KAAK,EAALA,KAAK;IACLO,KAAK,EAAE;MACLtC,IAAI,EAAER,SAA4B;MAClCS,UAAU,EAAET,SAAiE;MAC7EyC,KAAK,EAAEzC,SAA6B;MACpC8B,OAAO,EAAE9B;IACX,CAAC;IACDE,yBAAyB,EAAzBA;EACF,CAAC;AACH"}
@@ -0,0 +1,26 @@
1
+ import _objectSpread from "@babel/runtime-corejs3/helpers/objectSpread2";
2
+ import _extends from "@babel/runtime-corejs3/helpers/extends";
3
+ import React, { useCallback } from 'react';
4
+ import createChainOfResponsibility from './createChainOfResponsibility';
5
+ // We are using the props as both "Request" and "Props".
6
+ // This should eases migration from `onRender` to chain of responsibility.
7
+ // Downside is, web developers could accidentally pass request as props and not honoring props modified by upstreamers.
8
+ export default function createChainOfResponsibilityForFluentUI(options) {
9
+ var returnValue = createChainOfResponsibility(options);
10
+ var Proxy = returnValue.Proxy;
11
+ var useBuildRenderFunction = function useBuildRenderFunction() {
12
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
13
+ var getKey = options.getKey;
14
+ return useCallback(function (props, defaultRender) {
15
+ return /*#__PURE__*/React.createElement(Proxy, _extends({}, props, {
16
+ fallbackComponent: defaultRender,
17
+ key: getKey === null || getKey === void 0 ? void 0 : getKey(props),
18
+ request: props
19
+ }));
20
+ }, [getKey]);
21
+ };
22
+ return _objectSpread(_objectSpread({}, returnValue), {}, {
23
+ useBuildRenderFunction: useBuildRenderFunction
24
+ });
25
+ }
26
+ //# sourceMappingURL=createChainOfResponsibilityForFluentUI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createChainOfResponsibilityForFluentUI.js","names":["React","useCallback","createChainOfResponsibility","createChainOfResponsibilityForFluentUI","options","returnValue","Proxy","useBuildRenderFunction","arguments","length","undefined","getKey","props","defaultRender","createElement","_extends","fallbackComponent","key","request","_objectSpread"],"sources":["../../src/createChainOfResponsibilityForFluentUI.tsx"],"sourcesContent":["import React, { useCallback } from 'react';\n\nimport createChainOfResponsibility from './createChainOfResponsibility';\n\nimport type { IRenderFunction } from '@fluentui/react';\nimport type { Key } from 'react';\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.\nexport default function createChainOfResponsibilityForFluentUI<Props extends object, Init = undefined>(\n options?: Parameters<typeof createChainOfResponsibility>[0]\n): ReturnType<typeof createChainOfResponsibility<Props | undefined, Props, Init>> & {\n useBuildRenderFunction: UseBuildRenderFunction<Props>;\n} {\n const returnValue = createChainOfResponsibility<Props | undefined, Props, Init>(options);\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 <Proxy {...(props as Props)} fallbackComponent={defaultRender} key={getKey?.(props)} request={props} />\n ),\n [getKey]\n );\n };\n\n return { ...returnValue, useBuildRenderFunction };\n}\n"],"mappings":";;AAAA,OAAOA,KAAK,IAAIC,WAAW,QAAQ,OAAO;AAE1C,OAAOC,2BAA2B,MAAM,+BAA+B;AASvE;AACA;AACA;AACA,eAAe,SAASC,sCAAsCA,CAC5DC,OAA2D,EAG3D;EACA,IAAMC,WAAW,GAAGH,2BAA2B,CAAiCE,OAAO,CAAC;EAExF,IAAQE,KAAK,GAAKD,WAAW,CAArBC,KAAK;EAEb,IAAMC,sBAAqD,GAAG,SAAxDA,sBAAqDA,CAAA,EAAqB;IAAA,IAAjBH,OAAO,GAAAI,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;IACzE,IAAQG,MAAM,GAAKP,OAAO,CAAlBO,MAAM;IAEd,OAAOV,WAAW,CAChB,UAACW,KAAK,EAAEC,aAAa;MAAA,oBACnBb,KAAA,CAAAc,aAAA,CAACR,KAAK,EAAAS,QAAA,KAAMH,KAAK;QAAYI,iBAAiB,EAAEH,aAAc;QAACI,GAAG,EAAEN,MAAM,aAANA,MAAM,uBAANA,MAAM,CAAGC,KAAK,CAAE;QAACM,OAAO,EAAEN;MAAM,GAAG;IAAA,CACxG,EACD,CAACD,MAAM,CAAC,CACT;EACH,CAAC;EAED,OAAAQ,aAAA,CAAAA,aAAA,KAAYd,WAAW;IAAEE,sBAAsB,EAAtBA;EAAsB;AACjD"}
@@ -0,0 +1,4 @@
1
+ import createChainOfResponsibility from './createChainOfResponsibility';
2
+ import createChainOfResponsibilityForFluentUI from './createChainOfResponsibilityForFluentUI';
3
+ export { createChainOfResponsibility, createChainOfResponsibilityForFluentUI };
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["createChainOfResponsibility","createChainOfResponsibilityForFluentUI"],"sources":["../../src/index.ts"],"sourcesContent":["import createChainOfResponsibility from './createChainOfResponsibility';\nimport createChainOfResponsibilityForFluentUI from './createChainOfResponsibilityForFluentUI';\n\nimport type { ComponentMiddleware } from './types';\n\nexport { createChainOfResponsibility, createChainOfResponsibilityForFluentUI };\n\nexport type { ComponentMiddleware };\n"],"mappings":"AAAA,OAAOA,2BAA2B,MAAM,+BAA+B;AACvE,OAAOC,sCAAsC,MAAM,0CAA0C;AAI7F,SAASD,2BAA2B,EAAEC,sCAAsC"}
@@ -0,0 +1,22 @@
1
+ import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
2
+ import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
3
+ import compose from './compose';
4
+
5
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
+
7
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
8
+ export default function applyMiddleware() {
9
+ for (var _len = arguments.length, arrayOfMiddleware = new Array(_len), _key = 0; _key < _len; _key++) {
10
+ arrayOfMiddleware[_key] = arguments[_key];
11
+ }
12
+ return function () {
13
+ for (var _len2 = arguments.length, init = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
14
+ init[_key2] = arguments[_key2];
15
+ }
16
+ var chain = _mapInstanceProperty(arrayOfMiddleware).call(arrayOfMiddleware, function (middleware) {
17
+ return middleware.apply(void 0, init);
18
+ });
19
+ return compose.apply(void 0, _toConsumableArray(chain));
20
+ };
21
+ }
22
+ //# sourceMappingURL=applyMiddleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"applyMiddleware.js","names":["compose","applyMiddleware","_len","arguments","length","arrayOfMiddleware","Array","_key","_len2","init","_key2","chain","_mapInstanceProperty","call","middleware","apply","_toConsumableArray"],"sources":["../../../src/private/applyMiddleware.ts"],"sourcesContent":["import compose from './compose';\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,OAAOA,OAAO,MAAM,WAAW;;AAE/B;;AASA;AACA,eAAe,SAASC,eAAeA,CAAA,EAErC;EAAA,SAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EADGC,iBAAiB,OAAAC,KAAA,CAAAJ,IAAA,GAAAK,IAAA,MAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA;IAAjBF,iBAAiB,CAAAE,IAAA,IAAAJ,SAAA,CAAAI,IAAA;EAAA;EAEpB,OAAO,YAAgB;IAAA,SAAAC,KAAA,GAAAL,SAAA,CAAAC,MAAA,EAAZK,IAAI,OAAAH,KAAA,CAAAE,KAAA,GAAAE,KAAA,MAAAA,KAAA,GAAAF,KAAA,EAAAE,KAAA;MAAJD,IAAI,CAAAC,KAAA,IAAAP,SAAA,CAAAO,KAAA;IAAA;IACb,IAAMC,KAAK,GAAGC,oBAAA,CAAAP,iBAAiB,EAAAQ,IAAA,CAAjBR,iBAAiB,EAAK,UAAAS,UAAU;MAAA,OAAIA,UAAU,CAAAC,KAAA,SAAIN,IAAI,CAAC;IAAA,EAAC;IAEtE,OAAOT,OAAO,CAAAe,KAAA,SAAAC,kBAAA,CAAIL,KAAK,EAAC;EAC1B,CAAC;AACH"}
@@ -0,0 +1,17 @@
1
+ import _reduceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/reduce";
2
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3
+
4
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
5
+
6
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
+ export default function compose() {
8
+ for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
9
+ fns[_key] = arguments[_key];
10
+ }
11
+ return function (fn) {
12
+ return _reduceInstanceProperty(fns).call(fns, function (chain, fn) {
13
+ return fn(chain);
14
+ }, fn);
15
+ };
16
+ }
17
+ //# sourceMappingURL=compose.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.js","names":["compose","_len","arguments","length","fns","Array","_key","fn","_reduceInstanceProperty","call","chain"],"sources":["../../../src/private/compose.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"],"mappings":";AAAA;;AAGA;;AAGA;AACA,eAAe,SAASA,OAAOA,CAAA,EAA+D;EAAA,SAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAAvCC,GAAG,OAAAC,KAAA,CAAAJ,IAAA,GAAAK,IAAA,MAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA;IAAHF,GAAG,CAAAE,IAAA,IAAAJ,SAAA,CAAAI,IAAA;EAAA;EACxD,OAAO,UAACC,EAAY;IAAA,OAAeC,uBAAA,CAAAJ,GAAG,EAAAK,IAAA,CAAHL,GAAG,EAAQ,UAACM,KAAK,EAAEH,EAAE;MAAA,OAAKA,EAAE,CAACG,KAAK,CAAC;IAAA,GAAEH,EAAE,CAAC;EAAA;AAC7E"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/types.ts"],"sourcesContent":["import type { ComponentType } from 'react';\nimport type { Middleware } from './private/applyMiddleware';\n\nexport type ComponentMiddleware<Request, Props = { children?: never }, Init = undefined> = Middleware<\n [Request],\n ComponentType<Props> | false | null | undefined,\n [Init]\n>;\n"],"mappings":""}
@@ -0,0 +1,44 @@
1
+ import { ComponentType } from 'react';
2
+ import type { ComponentMiddleware } from './types';
3
+ import type { PropsWithChildren } from 'react';
4
+ type UseBuildComponentCallbackOptions<Props> = {
5
+ fallbackComponent?: ComponentType<Props> | false | null | undefined;
6
+ };
7
+ type UseBuildComponentCallback<Request, Props> = (request: Request, options?: UseBuildComponentCallbackOptions<Props>) => ComponentType<Props> | false | null | undefined;
8
+ type ProviderProps<Request, Props, Init> = PropsWithChildren<{
9
+ middleware: ComponentMiddleware<Request, Props, Init>[];
10
+ }> & (Init extends never | undefined ? {
11
+ init?: Init;
12
+ } : {
13
+ init: Init;
14
+ });
15
+ type ProxyProps<Request, Props> = Request extends never | undefined ? Props & {
16
+ fallbackComponent?: ComponentType<Props>;
17
+ request?: Request;
18
+ } : Props & {
19
+ fallbackComponent?: ComponentType<Props>;
20
+ request: Request;
21
+ };
22
+ type Options = {
23
+ /**
24
+ * Allows a middleware to pass another request object when calling its next middleware. Default is false.
25
+ *
26
+ * However, middleware could modify the request object before calling its next middleware. It is recommended
27
+ * to use Object.freeze() to prevent middleware from modifying the request object.
28
+ */
29
+ passModifiedRequest?: boolean;
30
+ };
31
+ export default function createChainOfResponsibility<Request = undefined, Props = {
32
+ children?: never;
33
+ }, Init = undefined>(options?: Options): {
34
+ Provider: ComponentType<ProviderProps<Request, Props, Init>>;
35
+ Proxy: ComponentType<ProxyProps<Request, Props>>;
36
+ types: {
37
+ init: Init;
38
+ middleware: ComponentMiddleware<Request, Props, Init>;
39
+ props: Props;
40
+ request: Request;
41
+ };
42
+ useBuildComponentCallback: () => UseBuildComponentCallback<Request, Props>;
43
+ };
44
+ export {};
@@ -0,0 +1,11 @@
1
+ import createChainOfResponsibility from './createChainOfResponsibility';
2
+ import type { IRenderFunction } from '@fluentui/react';
3
+ import type { Key } from 'react';
4
+ type UseBuildRenderFunctionOptions<Props> = {
5
+ getKey?: (props: Props | undefined) => Key;
6
+ };
7
+ type UseBuildRenderFunction<Props> = (options?: UseBuildRenderFunctionOptions<Props>) => IRenderFunction<Props>;
8
+ export default function createChainOfResponsibilityForFluentUI<Props extends object, Init = undefined>(options?: Parameters<typeof createChainOfResponsibility>[0]): ReturnType<typeof createChainOfResponsibility<Props | undefined, Props, Init>> & {
9
+ useBuildRenderFunction: UseBuildRenderFunction<Props>;
10
+ };
11
+ export {};
@@ -0,0 +1,5 @@
1
+ import createChainOfResponsibility from './createChainOfResponsibility';
2
+ import createChainOfResponsibilityForFluentUI from './createChainOfResponsibilityForFluentUI';
3
+ import type { ComponentMiddleware } from './types';
4
+ export { createChainOfResponsibility, createChainOfResponsibilityForFluentUI };
5
+ export type { ComponentMiddleware };
@@ -0,0 +1,5 @@
1
+ type Fn<P extends any[], R> = (...args: P) => R;
2
+ export type Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;
3
+ export type Middleware<P extends any[], R, S extends any[]> = (...init: S) => Enhancer<P, R>;
4
+ export default function applyMiddleware<P extends any[], R, S extends any[]>(...arrayOfMiddleware: Middleware<P, R, S>[]): (...init: S) => (next: (...args: P) => R) => (...args: P) => R;
5
+ export {};
@@ -0,0 +1,4 @@
1
+ type Fn<P extends any[], R> = (...args: P) => R;
2
+ type Enhancer<P extends any[], R> = (next: Fn<P, R>) => Fn<P, R>;
3
+ export default function compose<P extends any[], R>(...fns: Enhancer<P, R>[]): Enhancer<P, R>;
4
+ export {};
@@ -0,0 +1,9 @@
1
+ import type { ComponentType } from 'react';
2
+ import type { Middleware } from './private/applyMiddleware';
3
+ export type ComponentMiddleware<Request, Props = {
4
+ children?: never;
5
+ }, Init = undefined> = Middleware<[
6
+ Request
7
+ ], ComponentType<Props> | false | null | undefined, [
8
+ Init
9
+ ]>;
package/package.json ADDED
@@ -0,0 +1,118 @@
1
+ {
2
+ "name": "react-chain-of-responsibility",
3
+ "version": "0.0.1-main.9fc4b7d",
4
+ "description": "Using chain of responsibility design pattern for React component customization.",
5
+ "files": [
6
+ "./lib/*"
7
+ ],
8
+ "exports": {
9
+ ".": {
10
+ "import": "./lib/esmodules/index.js",
11
+ "require": "./lib/commonjs/index.js",
12
+ "types": "./lib/types/index.d.ts"
13
+ },
14
+ "./createChainOfResponsibility": {
15
+ "import": "./lib/esmodules/createChainOfResponsibility.js",
16
+ "require": "./lib/commonjs/createChainOfResponsibility.js",
17
+ "types": "./lib/types/createChainOfResponsibility.d.ts"
18
+ },
19
+ "./createChainOfResponsibilityForFluentUI": {
20
+ "import": "./lib/esmodules/createChainOfResponsibilityForFluentUI.js",
21
+ "require": "./lib/commonjs/createChainOfResponsibilityForFluentUI.js",
22
+ "types": "./lib/types/createChainOfResponsibilityForFluentUI.d.ts"
23
+ }
24
+ },
25
+ "main": "./lib/commonjs/index.js",
26
+ "typings": "./lib/types/index.d.ts",
27
+ "scripts": {
28
+ "build": "npm run build:babel && npm run build:typescript",
29
+ "build:babel": "npm run build:babel:commonjs && npm run build:babel:esmodules",
30
+ "build:babel:commonjs": "babel src --config-file ./babel.commonjs.config.json --extensions .ts,.tsx --out-dir ./lib/commonjs/",
31
+ "build:babel:esmodules": "babel src --config-file ./babel.esmodules.config.json --extensions .ts,.tsx --out-dir ./lib/esmodules/",
32
+ "build:typescript": "tsc --project ./src/tsconfig.declaration.json",
33
+ "bump": "npm run bump:prod && npm run bump:dev && npm run bump:auditfix && npm run bump:babel",
34
+ "bump:auditfix": "npm audit fix || exit 0",
35
+ "bump:babel": "npm run bump:babel:commonjs && npm run bump:babel:esmodules",
36
+ "bump:babel:commonjs": "cat babel.commonjs.config.json | jq --arg CORE_JS_VERSION `cat node_modules/@babel/runtime-corejs3/package.json | jq -r .version` '(.plugins[] | select(.[0] == \"@babel/plugin-transform-runtime\"))[1].version = $CORE_JS_VERSION' | prettier --parser json > babel.commonjs.config.json.tmp && mv babel.commonjs.config.json.tmp babel.commonjs.config.json",
37
+ "bump:babel:esmodules": "cat babel.esmodules.config.json | jq --arg CORE_JS_VERSION `cat node_modules/@babel/runtime-corejs3/package.json | jq -r .version` '(.plugins[] | select(.[0] == \"@babel/plugin-transform-runtime\"))[1].version = $CORE_JS_VERSION' | prettier --parser json > babel.esmodules.config.json.tmp && mv babel.esmodules.config.json.tmp babel.esmodules.config.json",
38
+ "bump:babel:jest": "cat babel.jest.config.json | jq --arg CORE_JS_VERSION `cat node_modules/@babel/runtime-corejs3/package.json | jq -r .version` '(.plugins[] | select(.[0] == \"@babel/plugin-transform-runtime\"))[1].version = $CORE_JS_VERSION' | prettier --parser json > babel.jest.config.json.tmp && mv babel.jest.config.json.tmp babel.jest.config.json",
39
+ "bump:dev": "if [ `cat package.json | jq -r '(.devDependencies // {}) | length'` -ne 0 ]; then npm install $(cat package.json | jq -r '(.pinDependencies // {}) as $p | ((.devDependencies // {}) | keys) | map(. + \"@\" + ($p[.] // [\"latest\"])[0]) | .[]'); fi",
40
+ "bump:prod": "if [ `cat package.json | jq -r '(.dependencies // {}) | length'` -ne 0 ]; then npm install --save-exact $(cat package.json | jq -r '(.pinDependencies // {}) as $p | ((.dependencies // {}) | keys) | map(. + \"@\" + ($p[.] // [\"latest\"])[0]) | .[]'); fi",
41
+ "postbump": "cat package.json | jq '. + (.dependencies = (((.dependencies // {}) + (.localPeerDependencies // {})) | to_entries | sort_by(.key) | from_entries)) | (.devDependencies = (((.devDependencies // {}) + (.localPeerDevDependencies // {})) | to_entries | sort_by(.key) | from_entries))' > package-temp.json && mv package-temp.json package.json",
42
+ "prebump": "cat package.json | jq '(((.localPeerDependencies // {}) | keys | map([\"dependencies\", .])) + ((.localPeerDevDependencies // {}) | keys | map([\"devDependencies\", .]))) as $localPeerPaths | delpaths($localPeerPaths)' > package-temp.json && mv package-temp.json package.json",
43
+ "precommit": "eslint ./src/",
44
+ "prepack": "cp ../../CHANGELOG.md . && cp ../../LICENSE . && cp ../../README.md .",
45
+ "start": "esbuild --bundle --outfile=./public/main.js --servedir=./public --sourcemap ./scenarios/index.jsx",
46
+ "jest": "jest",
47
+ "test": "npm run test:jest && npm run test:typescript",
48
+ "test:jest": "npm run jest",
49
+ "test:typescript": "tsc --project ./src/tsconfig.test.json"
50
+ },
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/compulim/react-chain-of-responsibility.git"
54
+ },
55
+ "keywords": [
56
+ "react",
57
+ "react-hook",
58
+ "react-hooks"
59
+ ],
60
+ "author": "William Wong (https://github.com/compulim)",
61
+ "license": "MIT",
62
+ "bugs": {
63
+ "url": "https://github.com/compulim/react-chain-of-responsibility/issues"
64
+ },
65
+ "homepage": "https://github.com/compulim/react-chain-of-responsibility#readme",
66
+ "pinDependencies": {
67
+ "@testing-library/react": [
68
+ "12",
69
+ "@testing-library/react-hooks@8.0.1 does not support react@>=18"
70
+ ],
71
+ "@types/react": [
72
+ "17",
73
+ "@testing-library/react-hooks@8.0.1 does not support react@>=18"
74
+ ],
75
+ "react": [
76
+ "17",
77
+ "@testing-library/react-hooks@8.0.1 does not support react@>=18"
78
+ ],
79
+ "react-dom": [
80
+ "17",
81
+ "@testing-library/react-hooks@8.0.1 does not support react@>=18"
82
+ ],
83
+ "react-test-renderer": [
84
+ "17",
85
+ "@testing-library/react-hooks@8.0.1 does not support react@>=18"
86
+ ]
87
+ },
88
+ "devDependencies": {
89
+ "@babel/cli": "^7.21.0",
90
+ "@babel/core": "^7.21.0",
91
+ "@babel/plugin-transform-runtime": "^7.21.0",
92
+ "@babel/preset-env": "^7.20.2",
93
+ "@babel/preset-react": "^7.18.6",
94
+ "@babel/preset-typescript": "^7.21.0",
95
+ "@fluentui/react": "^8.106.7",
96
+ "@testing-library/react": "^12.1.5",
97
+ "@testing-library/react-hooks": "^8.0.1",
98
+ "@types/jest": "^29.4.0",
99
+ "@types/node": "^18.14.0",
100
+ "@types/react": "^17.0.53",
101
+ "esbuild": "^0.17.10",
102
+ "jest": "^29.4.3",
103
+ "jest-environment-jsdom": "^29.4.3",
104
+ "prettier": "^2.8.4",
105
+ "react": "^17.0.2",
106
+ "react-dom": "^17.0.2",
107
+ "react-test-renderer": "^17.0.2",
108
+ "react-wrap-with": "0.0.2-main.fa6cc79",
109
+ "typescript": "^4.9.5"
110
+ },
111
+ "peerDependencies": {
112
+ "react": ">=16.9.0"
113
+ },
114
+ "dependencies": {
115
+ "@babel/runtime-corejs3": "7.21.0",
116
+ "prop-types": "^15.8.1"
117
+ }
118
+ }