@webiny/react-composition 0.0.0-unstable.78f581c1d2 β†’ 0.0.0-unstable.7be00a75a9

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/Compose.d.ts CHANGED
@@ -1,15 +1,9 @@
1
1
  import React from "react";
2
- import { HigherOrderComponent } from "./Context";
3
- export interface ComposableFC<TProps = unknown> extends React.FC<TProps> {
4
- original: React.FC<TProps>;
5
- originalName: string;
6
- }
2
+ import type { DecoratableTypes } from "./Context.js";
3
+ import type { ComposeWith } from "./types.js";
7
4
  export interface ComposeProps {
8
- /**
9
- * Component to compose.
10
- * NOTE: ComposableFC<TProps> use `any` because the type of the component props is irrelevant.
11
- */
12
- component: ComposableFC<any>;
13
- with: HigherOrderComponent | HigherOrderComponent[];
5
+ function?: DecoratableTypes;
6
+ component?: DecoratableTypes;
7
+ with: ComposeWith;
14
8
  }
15
- export declare const Compose: React.FC<ComposeProps>;
9
+ export declare const Compose: (props: ComposeProps) => React.JSX.Element | null;
package/Compose.js CHANGED
@@ -1,28 +1,56 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.Compose = void 0;
7
-
8
- var _react = require("react");
9
-
10
- var _Context = require("./Context");
11
-
12
- var Compose = function Compose(props) {
13
- var _useComposition = (0, _Context.useComposition)(),
14
- composeComponent = _useComposition.composeComponent;
15
-
16
- (0, _react.useEffect)(function () {
17
- if (typeof props.component.original === "undefined") {
18
- console.warn("You must make your component \"<".concat(props.component.displayName, ">\" composable, by using the makeComposable() function!"));
19
- return;
1
+ import react, { useEffect, useRef } from "react";
2
+ import { useCompositionStore } from "./Context.js";
3
+ import { useCompositionScope } from "./CompositionScope.js";
4
+ const Compose = (props)=>{
5
+ const store = useCompositionStore();
6
+ const { scope, inherit } = useCompositionScope();
7
+ const targetFn = props.function ?? props.component;
8
+ if (!targetFn) {
9
+ console.warn("You must provide a function or a component to compose with!", props);
10
+ return null;
20
11
  }
21
-
22
- var hocs = Array.isArray(props.with) ? props.with : [props.with];
23
- return composeComponent(props.component.original, hocs);
24
- }, [props.with]);
25
- return null;
12
+ if (void 0 === targetFn.original) {
13
+ console.warn(`You must make your function "${targetFn.originalName ?? targetFn.name}" composable, by using the makeDecoratable() function!`);
14
+ return null;
15
+ }
16
+ const decorators = Array.isArray(props.with) ? props.with : [
17
+ props.with
18
+ ];
19
+ const currentScope = scope[scope.length - 1] ?? "*";
20
+ store.register(targetFn.original, decorators, currentScope, inherit, true);
21
+ return /*#__PURE__*/ react.createElement(ComposeEffects, {
22
+ store: store,
23
+ target: targetFn.original,
24
+ decorators: decorators,
25
+ scope: currentScope,
26
+ inherit: inherit
27
+ });
26
28
  };
29
+ function ComposeEffects({ store, target, decorators, scope, inherit }) {
30
+ const prevRef = useRef(null);
31
+ const liveRef = useRef(decorators);
32
+ if (liveRef.current !== decorators) {
33
+ store.register(target, decorators, scope, inherit, true, liveRef.current);
34
+ liveRef.current = decorators;
35
+ }
36
+ useEffect(()=>{
37
+ const prev = prevRef.current;
38
+ if (prev && (prev.decorators !== decorators || prev.scope !== scope)) store.notify();
39
+ prevRef.current = {
40
+ decorators,
41
+ scope
42
+ };
43
+ return ()=>{
44
+ store.unregister(target, decorators, scope);
45
+ };
46
+ }, [
47
+ store,
48
+ target,
49
+ decorators,
50
+ scope
51
+ ]);
52
+ return null;
53
+ }
54
+ export { Compose };
27
55
 
28
- exports.Compose = Compose;
56
+ //# sourceMappingURL=Compose.js.map
package/Compose.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["Compose","props","useComposition","composeComponent","useEffect","component","original","console","warn","displayName","hocs","Array","isArray","with"],"sources":["Compose.tsx"],"sourcesContent":["import React, { useEffect } from \"react\";\nimport { HigherOrderComponent, useComposition } from \"./Context\";\n\nexport interface ComposableFC<TProps = unknown> extends React.FC<TProps> {\n original: React.FC<TProps>;\n originalName: string;\n}\n\nexport interface ComposeProps {\n /**\n * Component to compose.\n * NOTE: ComposableFC<TProps> use `any` because the type of the component props is irrelevant.\n */\n component: ComposableFC<any>;\n with: HigherOrderComponent | HigherOrderComponent[];\n}\n\nexport const Compose: React.FC<ComposeProps> = props => {\n const { composeComponent } = useComposition();\n\n useEffect(() => {\n if (typeof props.component.original === \"undefined\") {\n console.warn(\n `You must make your component \"<${props.component.displayName}>\" composable, by using the makeComposable() function!`\n );\n\n return;\n }\n\n const hocs = Array.isArray(props.with) ? props.with : [props.with];\n return composeComponent(props.component.original, hocs);\n }, [props.with]);\n\n return null;\n};\n"],"mappings":";;;;;;;AAAA;;AACA;;AAgBO,IAAMA,OAA+B,GAAG,SAAlCA,OAAkC,CAAAC,KAAK,EAAI;EACpD,sBAA6B,IAAAC,uBAAA,GAA7B;EAAA,IAAQC,gBAAR,mBAAQA,gBAAR;;EAEA,IAAAC,gBAAA,EAAU,YAAM;IACZ,IAAI,OAAOH,KAAK,CAACI,SAAN,CAAgBC,QAAvB,KAAoC,WAAxC,EAAqD;MACjDC,OAAO,CAACC,IAAR,2CACsCP,KAAK,CAACI,SAAN,CAAgBI,WADtD;MAIA;IACH;;IAED,IAAMC,IAAI,GAAGC,KAAK,CAACC,OAAN,CAAcX,KAAK,CAACY,IAApB,IAA4BZ,KAAK,CAACY,IAAlC,GAAyC,CAACZ,KAAK,CAACY,IAAP,CAAtD;IACA,OAAOV,gBAAgB,CAACF,KAAK,CAACI,SAAN,CAAgBC,QAAjB,EAA2BI,IAA3B,CAAvB;EACH,CAXD,EAWG,CAACT,KAAK,CAACY,IAAP,CAXH;EAaA,OAAO,IAAP;AACH,CAjBM"}
1
+ {"version":3,"file":"Compose.js","sources":["../src/Compose.tsx"],"sourcesContent":["import React, { useEffect, useRef } from \"react\";\nimport type { DecoratableTypes } from \"./Context.js\";\nimport { useCompositionStore } from \"./Context.js\";\nimport { useCompositionScope } from \"~/CompositionScope.js\";\nimport type {\n ComposeWith,\n Decoratable,\n Decorator,\n GenericComponent,\n GenericHook\n} from \"./types.js\";\n\nexport interface ComposeProps {\n function?: DecoratableTypes;\n component?: DecoratableTypes;\n with: ComposeWith;\n}\n\nexport const Compose = (props: ComposeProps) => {\n const store = useCompositionStore();\n const { scope, inherit } = useCompositionScope();\n\n const targetFn = (props.function ?? props.component) as Decoratable;\n\n if (!targetFn) {\n console.warn(\"You must provide a function or a component to compose with!\", props);\n return null;\n }\n\n if (typeof targetFn.original === \"undefined\") {\n console.warn(\n `You must make your function \"${\n targetFn.originalName ?? targetFn.name\n }\" composable, by using the makeDecoratable() function!`\n );\n return null;\n }\n\n const decorators = (Array.isArray(props.with) ? props.with : [props.with]) as Decorator<\n GenericComponent | GenericHook\n >[];\n const currentScope = scope[scope.length - 1] ?? \"*\";\n\n // Register synchronously during render so decorators are available immediately.\n // Pass silent=true to avoid notifying listeners mid-render (which would trigger\n // setState in other components and cause React warnings).\n store.register(targetFn.original, decorators, currentScope, inherit, true);\n\n return (\n <ComposeEffects\n store={store}\n target={targetFn.original}\n decorators={decorators}\n scope={currentScope}\n inherit={inherit}\n />\n );\n};\n\n/**\n * Separate component for the effect to avoid re-running the cleanup on every render.\n * This component handles cleanup on unmount and when props change.\n */\nfunction ComposeEffects({\n store,\n target,\n decorators,\n scope,\n inherit\n}: {\n store: ReturnType<typeof useCompositionStore>;\n target: any;\n decorators: Decorator<GenericComponent | GenericHook>[];\n scope: string;\n inherit: boolean;\n}) {\n const prevRef = useRef<{\n decorators: Decorator<GenericComponent | GenericHook>[];\n scope: string;\n } | null>(null);\n\n // Tracks the decorators currently live in the store as of the last render.\n // Updated synchronously during render so it always reflects the most recently\n // registered decorators, allowing the atomic swap below to remove the right ones.\n const liveRef = useRef<Decorator<GenericComponent | GenericHook>[]>(decorators);\n\n // On re-render with new decorators: atomically replace the old ones in the store\n // during render (before React commits). This ensures the store never transiently\n // holds both old and new HOCs β€” which would cause useSyncExternalStore subscribers\n // to render with a doubly-wrapped component and mount inner components twice.\n if (liveRef.current !== decorators) {\n store.register(target, decorators, scope, inherit, true, liveRef.current);\n liveRef.current = decorators;\n }\n\n useEffect(() => {\n const prev = prevRef.current;\n\n // On prop change: the render-phase atomic swap already updated the store.\n // Emit a non-silent notification now that effects have settled so subscribers\n // re-render with the final, clean composition (old HOCs fully gone).\n if (prev && (prev.decorators !== decorators || prev.scope !== scope)) {\n store.notify();\n }\n\n prevRef.current = { decorators, scope };\n\n // Cleanup on unmount.\n return () => {\n store.unregister(target, decorators, scope);\n };\n }, [store, target, decorators, scope]);\n\n return null;\n}\n"],"names":["Compose","props","store","useCompositionStore","scope","inherit","useCompositionScope","targetFn","console","decorators","Array","currentScope","ComposeEffects","target","prevRef","useRef","liveRef","useEffect","prev"],"mappings":";;;AAkBO,MAAMA,UAAU,CAACC;IACpB,MAAMC,QAAQC;IACd,MAAM,EAAEC,KAAK,EAAEC,OAAO,EAAE,GAAGC;IAE3B,MAAMC,WAAYN,MAAM,QAAQ,IAAIA,MAAM,SAAS;IAEnD,IAAI,CAACM,UAAU;QACXC,QAAQ,IAAI,CAAC,+DAA+DP;QAC5E,OAAO;IACX;IAEA,IAAI,AAA6B,WAAtBM,SAAS,QAAQ,EAAkB;QAC1CC,QAAQ,IAAI,CACR,CAAC,6BAA6B,EAC1BD,SAAS,YAAY,IAAIA,SAAS,IAAI,CACzC,sDAAsD,CAAC;QAE5D,OAAO;IACX;IAEA,MAAME,aAAcC,MAAM,OAAO,CAACT,MAAM,IAAI,IAAIA,MAAM,IAAI,GAAG;QAACA,MAAM,IAAI;KAAC;IAGzE,MAAMU,eAAeP,KAAK,CAACA,MAAM,MAAM,GAAG,EAAE,IAAI;IAKhDF,MAAM,QAAQ,CAACK,SAAS,QAAQ,EAAEE,YAAYE,cAAcN,SAAS;IAErE,OAAO,WAAP,GACI,oBAACO,gBAAcA;QACX,OAAOV;QACP,QAAQK,SAAS,QAAQ;QACzB,YAAYE;QACZ,OAAOE;QACP,SAASN;;AAGrB;AAMA,SAASO,eAAe,EACpBV,KAAK,EACLW,MAAM,EACNJ,UAAU,EACVL,KAAK,EACLC,OAAO,EAOV;IACG,MAAMS,UAAUC,OAGN;IAKV,MAAMC,UAAUD,OAAoDN;IAMpE,IAAIO,QAAQ,OAAO,KAAKP,YAAY;QAChCP,MAAM,QAAQ,CAACW,QAAQJ,YAAYL,OAAOC,SAAS,MAAMW,QAAQ,OAAO;QACxEA,QAAQ,OAAO,GAAGP;IACtB;IAEAQ,UAAU;QACN,MAAMC,OAAOJ,QAAQ,OAAO;QAK5B,IAAII,QAASA,CAAAA,KAAK,UAAU,KAAKT,cAAcS,KAAK,KAAK,KAAKd,KAAI,GAC9DF,MAAM,MAAM;QAGhBY,QAAQ,OAAO,GAAG;YAAEL;YAAYL;QAAM;QAGtC,OAAO;YACHF,MAAM,UAAU,CAACW,QAAQJ,YAAYL;QACzC;IACJ,GAAG;QAACF;QAAOW;QAAQJ;QAAYL;KAAM;IAErC,OAAO;AACX"}
@@ -0,0 +1,17 @@
1
+ import React from "react";
2
+ export interface CompositionScopeContext {
3
+ inherit: boolean;
4
+ scope: string[];
5
+ }
6
+ interface CompositionScopeProps {
7
+ name: string;
8
+ /**
9
+ * Use this prop on components that are used to register decorators.
10
+ * Components are inherited at the time of registration, and then cached.
11
+ */
12
+ inherit?: boolean;
13
+ children: React.ReactNode;
14
+ }
15
+ export declare const CompositionScope: ({ name, inherit, children }: CompositionScopeProps) => React.JSX.Element;
16
+ export declare function useCompositionScope(): CompositionScopeContext;
17
+ export {};
@@ -0,0 +1,25 @@
1
+ import react from "react";
2
+ const CompositionScopeContext = /*#__PURE__*/ react.createContext(void 0);
3
+ const CompositionScope = ({ name, inherit = false, children })=>{
4
+ const parentScope = useCompositionScope();
5
+ return /*#__PURE__*/ react.createElement(CompositionScopeContext.Provider, {
6
+ value: {
7
+ scope: [
8
+ ...parentScope.scope,
9
+ name
10
+ ],
11
+ inherit
12
+ }
13
+ }, children);
14
+ };
15
+ function useCompositionScope() {
16
+ const context = react.useContext(CompositionScopeContext);
17
+ if (!context) return {
18
+ scope: [],
19
+ inherit: false
20
+ };
21
+ return context;
22
+ }
23
+ export { CompositionScope, useCompositionScope };
24
+
25
+ //# sourceMappingURL=CompositionScope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CompositionScope.js","sources":["../src/CompositionScope.tsx"],"sourcesContent":["import React from \"react\";\n\nexport interface CompositionScopeContext {\n inherit: boolean;\n scope: string[];\n}\n\nconst CompositionScopeContext = React.createContext<CompositionScopeContext | undefined>(undefined);\n\ninterface CompositionScopeProps {\n name: string;\n /**\n * Use this prop on components that are used to register decorators.\n * Components are inherited at the time of registration, and then cached.\n */\n inherit?: boolean;\n children: React.ReactNode;\n}\n\nexport const CompositionScope = ({ name, inherit = false, children }: CompositionScopeProps) => {\n const parentScope = useCompositionScope();\n\n return (\n <CompositionScopeContext.Provider value={{ scope: [...parentScope.scope, name], inherit }}>\n {children}\n </CompositionScopeContext.Provider>\n );\n};\n\nexport function useCompositionScope() {\n const context = React.useContext(CompositionScopeContext);\n\n if (!context) {\n return { scope: [], inherit: false };\n }\n\n return context;\n}\n"],"names":["CompositionScopeContext","React","undefined","CompositionScope","name","inherit","children","parentScope","useCompositionScope","context"],"mappings":";AAOA,MAAMA,0BAA0B,WAAHA,GAAGC,MAAAA,aAAmB,CAAsCC;AAYlF,MAAMC,mBAAmB,CAAC,EAAEC,IAAI,EAAEC,UAAU,KAAK,EAAEC,QAAQ,EAAyB;IACvF,MAAMC,cAAcC;IAEpB,OAAO,WAAP,GACI,oBAACR,wBAAwB,QAAQ;QAAC,OAAO;YAAE,OAAO;mBAAIO,YAAY,KAAK;gBAAEH;aAAK;YAAEC;QAAQ;OACnFC;AAGb;AAEO,SAASE;IACZ,MAAMC,UAAUR,MAAAA,UAAgB,CAACD;IAEjC,IAAI,CAACS,SACD,OAAO;QAAE,OAAO,EAAE;QAAE,SAAS;IAAM;IAGvC,OAAOA;AACX"}
package/Context.d.ts CHANGED
@@ -1,38 +1,35 @@
1
- import React, { FC, ComponentType } from "react";
2
- export declare function compose(...fns: HigherOrderComponent[]): (Base: FC<unknown>) => FC<unknown>;
3
- interface ComposedComponent {
4
- /**
5
- * Ready to use React component.
6
- */
7
- component: ComponentType<unknown>;
8
- /**
9
- * HOCs used to compose the original component.
10
- */
11
- hocs: HigherOrderComponent[];
12
- }
1
+ import type { ComponentType } from "react";
2
+ import React from "react";
3
+ import { CompositionStore } from "./domain/CompositionStore.js";
4
+ import type { ComposeWith, Decoratable, DecoratableComponent, DecoratableHook, Decorator, Enumerable, GenericComponent, GenericHook } from "./types.js";
5
+ export declare function compose<T>(...fns: Decorator<T>[]): (decoratee: T) => T;
13
6
  /**
14
- * IMPORTANT: TInputProps default type is `any` because this interface is use as a prop type in the `Compose` component.
15
- * You can pass any HigherOrderComponent as a prop, regardless of its TInputProps type. The only way to allow that is
16
- * to let it be `any` in this interface.
7
+ * @deprecated Use `Decorator` instead.
17
8
  */
18
- export interface HigherOrderComponent<TInputProps = any, TOutputProps = TInputProps> {
19
- (Component: FC<TInputProps>): FC<TOutputProps>;
9
+ export interface HigherOrderComponent<TProps = any, TOutput = TProps> {
10
+ (Component: GenericComponent<TProps>): GenericComponent<TOutput>;
11
+ }
12
+ export type DecoratableTypes = DecoratableComponent | DecoratableHook;
13
+ export type DecoratorsTuple = [Decoratable, Decorator<any>[]];
14
+ export type DecoratorsCollection = Array<DecoratorsTuple>;
15
+ interface CompositionProviderProps {
16
+ decorators?: DecoratorsCollection;
17
+ children: React.ReactNode;
20
18
  }
21
- declare type ComposedComponents = Map<ComponentType<unknown>, ComposedComponent>;
22
- interface CompositionContext {
23
- components: ComposedComponents;
24
- getComponent(component: ComponentType<unknown>): ComponentType<unknown> | undefined;
25
- composeComponent(component: ComponentType<unknown>, hocs: HigherOrderComponent[]): void;
19
+ export declare const CompositionProvider: ({ decorators, children }: CompositionProviderProps) => React.JSX.Element;
20
+ export declare function useCompositionStore(): CompositionStore;
21
+ export declare function useOptionalCompositionStore(): CompositionStore | undefined;
22
+ export declare function useComponent<T>(baseFunction: T): T;
23
+ interface CompositionContextValue {
24
+ composeComponent(component: ComponentType<unknown>, hocs: Enumerable<ComposeWith>, scope?: string, inherit?: boolean): () => void;
25
+ getComponent(component: ComponentType<unknown>, scope: string[]): GenericComponent | GenericHook | undefined;
26
26
  }
27
- declare const CompositionContext: React.Context<CompositionContext | undefined>;
28
- export declare const CompositionProvider: React.FC;
29
- export declare function useComponent(Component: ComponentType<any>): React.ComponentClass<unknown, any> | React.FunctionComponent<unknown>;
30
27
  /**
31
28
  * This hook will throw an error if composition context doesn't exist.
32
29
  */
33
- export declare function useComposition(): CompositionContext;
30
+ export declare function useComposition(): CompositionContextValue;
34
31
  /**
35
32
  * This hook will not throw an error if composition context doesn't exist.
36
33
  */
37
- export declare function useOptionalComposition(): CompositionContext | undefined;
34
+ export declare function useOptionalComposition(): CompositionContextValue | undefined;
38
35
  export {};
package/Context.js CHANGED
@@ -1,126 +1,54 @@
1
- "use strict";
2
-
3
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
4
-
5
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
6
-
7
- Object.defineProperty(exports, "__esModule", {
8
- value: true
9
- });
10
- exports.CompositionProvider = void 0;
11
- exports.compose = compose;
12
- exports.useComponent = useComponent;
13
- exports.useComposition = useComposition;
14
- exports.useOptionalComposition = useOptionalComposition;
15
-
16
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
17
-
18
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
19
-
20
- var _react = _interopRequireWildcard(require("react"));
21
-
22
- function compose() {
23
- for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
24
- fns[_key] = arguments[_key];
25
- }
26
-
27
- return function ComposedComponent(Base) {
28
- return fns.reduceRight(function (Component, hoc) {
29
- return hoc(Component);
30
- }, Base);
31
- };
1
+ import react, { createContext, useContext, useRef, useSyncExternalStore } from "react";
2
+ import { useCompositionScope } from "./CompositionScope.js";
3
+ import { CompositionStore } from "./domain/CompositionStore.js";
4
+ function compose(...fns) {
5
+ return (decoratee)=>fns.reduceRight((decoratee, decorator)=>decorator(decoratee), decoratee);
32
6
  }
33
-
34
- var CompositionContext = /*#__PURE__*/(0, _react.createContext)(undefined);
35
-
36
- var CompositionProvider = function CompositionProvider(_ref) {
37
- var children = _ref.children;
38
-
39
- var _useState = (0, _react.useState)(new Map()),
40
- _useState2 = (0, _slicedToArray2.default)(_useState, 2),
41
- components = _useState2[0],
42
- setComponents = _useState2[1];
43
-
44
- var composeComponent = (0, _react.useCallback)(function (component, hocs) {
45
- setComponents(function (prevComponents) {
46
- var components = new Map(prevComponents);
47
- var recipe = components.get(component) || {
48
- component: null,
49
- hocs: []
50
- };
51
- var newHocs = [].concat((0, _toConsumableArray2.default)(recipe.hocs || []), (0, _toConsumableArray2.default)(hocs));
52
- components.set(component, {
53
- component: compose.apply(void 0, (0, _toConsumableArray2.default)((0, _toConsumableArray2.default)(newHocs).reverse()))(component),
54
- hocs: newHocs
55
- });
56
- return components;
57
- }); // Return a function that will remove the added HOCs.
58
-
59
- return function () {
60
- setComponents(function (prevComponents) {
61
- var components = new Map(prevComponents);
62
- var recipe = components.get(component) || {
63
- component: null,
64
- hocs: []
65
- };
66
- var newHOCs = (0, _toConsumableArray2.default)(recipe.hocs).filter(function (hoc) {
67
- return !hocs.includes(hoc);
68
- });
69
- var NewComponent = compose.apply(void 0, (0, _toConsumableArray2.default)((0, _toConsumableArray2.default)(newHOCs).reverse()))(component);
70
- components.set(component, {
71
- component: NewComponent,
72
- hocs: newHOCs
73
- });
74
- return components;
75
- });
76
- };
77
- }, [setComponents]);
78
- var getComponent = (0, _react.useCallback)(function (Component) {
79
- var composedComponent = components.get(Component);
80
- return composedComponent ? composedComponent.component : undefined;
81
- }, [components]);
82
- var context = (0, _react.useMemo)(function () {
83
- return {
84
- getComponent: getComponent,
85
- composeComponent: composeComponent,
86
- components: components
87
- };
88
- }, [components, composeComponent]);
89
- return /*#__PURE__*/_react.default.createElement(CompositionContext.Provider, {
90
- value: context
91
- }, children);
7
+ const CompositionStoreContext = /*#__PURE__*/ createContext(void 0);
8
+ const CompositionProvider = ({ decorators = [], children })=>{
9
+ const storeRef = useRef(null);
10
+ if (null === storeRef.current) {
11
+ const store = new CompositionStore();
12
+ for (const [decoratable, hocs] of decorators)store.register(decoratable.original, hocs);
13
+ storeRef.current = store;
14
+ }
15
+ return /*#__PURE__*/ react.createElement(CompositionStoreContext.Provider, {
16
+ value: storeRef.current
17
+ }, children);
92
18
  };
93
-
94
- exports.CompositionProvider = CompositionProvider;
95
-
96
- function useComponent(Component) {
97
- var context = useOptionalComposition();
98
-
99
- if (!context) {
100
- return Component;
101
- }
102
-
103
- return context.getComponent(Component) || Component;
19
+ function useCompositionStore() {
20
+ const store = useContext(CompositionStoreContext);
21
+ if (!store) throw new Error("You're missing a <CompositionProvider> higher up in your component hierarchy!");
22
+ return store;
104
23
  }
105
- /**
106
- * This hook will throw an error if composition context doesn't exist.
107
- */
108
-
109
-
24
+ function useOptionalCompositionStore() {
25
+ return useContext(CompositionStoreContext);
26
+ }
27
+ function useComponent(baseFunction) {
28
+ const store = useOptionalCompositionStore();
29
+ const scope = useCompositionScope();
30
+ useSyncExternalStore(store ? store.subscribe : noopSubscribe, store ? store.getSnapshot : noopGetSnapshot);
31
+ if (!store) return baseFunction;
32
+ const result = store.getComponent(baseFunction, scope.scope) || baseFunction;
33
+ return result;
34
+ }
35
+ const noopSubscribe = ()=>()=>{};
36
+ const noopGetSnapshot = ()=>0;
110
37
  function useComposition() {
111
- var context = (0, _react.useContext)(CompositionContext);
112
-
113
- if (!context) {
114
- throw new Error("You're missing a <CompositionProvider> higher up in your component hierarchy!");
115
- }
116
-
117
- return context;
38
+ const store = useCompositionStore();
39
+ return {
40
+ composeComponent: (component, hocs, scope = "*", inherit = false)=>store.register(component, hocs, scope, inherit),
41
+ getComponent: (component, scope)=>store.getComponent(component, scope)
42
+ };
118
43
  }
119
- /**
120
- * This hook will not throw an error if composition context doesn't exist.
121
- */
122
-
123
-
124
44
  function useOptionalComposition() {
125
- return (0, _react.useContext)(CompositionContext);
126
- }
45
+ const store = useOptionalCompositionStore();
46
+ if (!store) return;
47
+ return {
48
+ composeComponent: (component, hocs, scope = "*", inherit = false)=>store.register(component, hocs, scope, inherit),
49
+ getComponent: (component, scope)=>store.getComponent(component, scope)
50
+ };
51
+ }
52
+ export { CompositionProvider, compose, useComponent, useComposition, useCompositionStore, useOptionalComposition, useOptionalCompositionStore };
53
+
54
+ //# sourceMappingURL=Context.js.map
package/Context.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["compose","fns","ComposedComponent","Base","reduceRight","Component","hoc","CompositionContext","createContext","undefined","CompositionProvider","children","useState","Map","components","setComponents","composeComponent","useCallback","component","hocs","prevComponents","recipe","get","newHocs","set","reverse","newHOCs","filter","includes","NewComponent","getComponent","composedComponent","context","useMemo","useComponent","useOptionalComposition","useComposition","useContext","Error"],"sources":["Context.tsx"],"sourcesContent":["import React, {\n FC,\n ComponentType,\n useState,\n useCallback,\n createContext,\n useContext,\n useMemo\n} from \"react\";\n\nexport function compose(...fns: HigherOrderComponent[]) {\n return function ComposedComponent(Base: FC<unknown>): FC<unknown> {\n return fns.reduceRight((Component, hoc) => hoc(Component), Base);\n };\n}\n\ninterface ComposedComponent {\n /**\n * Ready to use React component.\n */\n component: ComponentType<unknown>;\n /**\n * HOCs used to compose the original component.\n */\n hocs: HigherOrderComponent[];\n}\n\n/**\n * IMPORTANT: TInputProps default type is `any` because this interface is use as a prop type in the `Compose` component.\n * You can pass any HigherOrderComponent as a prop, regardless of its TInputProps type. The only way to allow that is\n * to let it be `any` in this interface.\n */\nexport interface HigherOrderComponent<TInputProps = any, TOutputProps = TInputProps> {\n (Component: FC<TInputProps>): FC<TOutputProps>;\n}\n\ntype ComposedComponents = Map<ComponentType<unknown>, ComposedComponent>;\n\ninterface CompositionContext {\n components: ComposedComponents;\n getComponent(component: ComponentType<unknown>): ComponentType<unknown> | undefined;\n composeComponent(component: ComponentType<unknown>, hocs: HigherOrderComponent[]): void;\n}\n\nconst CompositionContext = createContext<CompositionContext | undefined>(undefined);\n\nexport const CompositionProvider: React.FC = ({ children }) => {\n const [components, setComponents] = useState<ComposedComponents>(new Map());\n\n const composeComponent = useCallback(\n (component, hocs) => {\n setComponents(prevComponents => {\n const components = new Map(prevComponents);\n const recipe = components.get(component) || { component: null, hocs: [] };\n\n const newHocs = [...(recipe.hocs || []), ...hocs];\n\n components.set(component, {\n component: compose(...[...newHocs].reverse())(component),\n hocs: newHocs\n });\n\n return components;\n });\n\n // Return a function that will remove the added HOCs.\n return () => {\n setComponents(prevComponents => {\n const components = new Map(prevComponents);\n const recipe = components.get(component) || {\n component: null,\n hocs: []\n };\n\n const newHOCs = [...recipe.hocs].filter(hoc => !hocs.includes(hoc));\n const NewComponent = compose(...[...newHOCs].reverse())(component);\n\n components.set(component, {\n component: NewComponent,\n hocs: newHOCs\n });\n\n return components;\n });\n };\n },\n [setComponents]\n );\n\n const getComponent: CompositionContext[\"getComponent\"] = useCallback(\n Component => {\n const composedComponent = components.get(Component);\n return composedComponent ? composedComponent.component : undefined;\n },\n [components]\n );\n\n const context: CompositionContext = useMemo(\n () => ({\n getComponent,\n composeComponent,\n components\n }),\n [components, composeComponent]\n );\n\n return <CompositionContext.Provider value={context}>{children}</CompositionContext.Provider>;\n};\n\nexport function useComponent(Component: ComponentType<any>) {\n const context = useOptionalComposition();\n\n if (!context) {\n return Component;\n }\n\n return context.getComponent(Component) || Component;\n}\n\n/**\n * This hook will throw an error if composition context doesn't exist.\n */\nexport function useComposition() {\n const context = useContext(CompositionContext);\n if (!context) {\n throw new Error(\n `You're missing a <CompositionProvider> higher up in your component hierarchy!`\n );\n }\n\n return context;\n}\n\n/**\n * This hook will not throw an error if composition context doesn't exist.\n */\nexport function useOptionalComposition() {\n return useContext(CompositionContext);\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"Context.js","sources":["../src/Context.tsx"],"sourcesContent":["import type { ComponentType } from \"react\";\nimport React, { createContext, useContext, useRef, useSyncExternalStore } from \"react\";\nimport { useCompositionScope } from \"~/CompositionScope.js\";\nimport { CompositionStore } from \"~/domain/CompositionStore.js\";\n\nimport type {\n ComposeWith,\n Decoratable,\n DecoratableComponent,\n DecoratableHook,\n Decorator,\n Enumerable,\n GenericComponent,\n GenericHook\n} from \"~/types.js\";\n\nexport function compose<T>(...fns: Decorator<T>[]) {\n return (decoratee: T): T => {\n return fns.reduceRight((decoratee, decorator) => decorator(decoratee), decoratee) as T;\n };\n}\n\n/**\n * @deprecated Use `Decorator` instead.\n */\nexport interface HigherOrderComponent<TProps = any, TOutput = TProps> {\n (Component: GenericComponent<TProps>): GenericComponent<TOutput>;\n}\n\nexport type DecoratableTypes = DecoratableComponent | DecoratableHook;\n\nconst CompositionStoreContext = createContext<CompositionStore | undefined>(undefined);\n\nexport type DecoratorsTuple = [Decoratable, Decorator<any>[]];\nexport type DecoratorsCollection = Array<DecoratorsTuple>;\n\ninterface CompositionProviderProps {\n decorators?: DecoratorsCollection;\n children: React.ReactNode;\n}\n\nexport const CompositionProvider = ({ decorators = [], children }: CompositionProviderProps) => {\n const storeRef = useRef<CompositionStore | null>(null);\n if (storeRef.current === null) {\n const store = new CompositionStore();\n // Pre-register decorators from props.\n for (const [decoratable, hocs] of decorators) {\n store.register(decoratable.original as ComponentType<unknown>, hocs);\n }\n storeRef.current = store;\n }\n\n return (\n <CompositionStoreContext.Provider value={storeRef.current}>\n {children}\n </CompositionStoreContext.Provider>\n );\n};\n\nexport function useCompositionStore(): CompositionStore {\n const store = useContext(CompositionStoreContext);\n if (!store) {\n throw new Error(\n `You're missing a <CompositionProvider> higher up in your component hierarchy!`\n );\n }\n return store;\n}\n\nexport function useOptionalCompositionStore(): CompositionStore | undefined {\n return useContext(CompositionStoreContext);\n}\n\nexport function useComponent<T>(baseFunction: T) {\n const store = useOptionalCompositionStore();\n const scope = useCompositionScope();\n\n // Subscribe to store changes so we re-render when compositions change.\n useSyncExternalStore(\n store ? store.subscribe : noopSubscribe,\n store ? store.getSnapshot : noopGetSnapshot\n );\n\n if (!store) {\n return baseFunction;\n }\n\n const result = store.getComponent(baseFunction as any, scope.scope) || baseFunction;\n\n return result as T;\n}\n\nconst noopSubscribe = () => () => {};\nconst noopGetSnapshot = () => 0;\n\n// Legacy compatibility β€” kept for any external consumers.\n\ninterface CompositionContextValue {\n composeComponent(\n component: ComponentType<unknown>,\n hocs: Enumerable<ComposeWith>,\n scope?: string,\n inherit?: boolean\n ): () => void;\n getComponent(\n component: ComponentType<unknown>,\n scope: string[]\n ): GenericComponent | GenericHook | undefined;\n}\n\n/**\n * This hook will throw an error if composition context doesn't exist.\n */\nexport function useComposition(): CompositionContextValue {\n const store = useCompositionStore();\n\n return {\n composeComponent: (component, hocs, scope = \"*\", inherit = false) => {\n return store.register(component, hocs as any[], scope, inherit);\n },\n getComponent: (component, scope) => {\n return store.getComponent(component, scope);\n }\n };\n}\n\n/**\n * This hook will not throw an error if composition context doesn't exist.\n */\nexport function useOptionalComposition(): CompositionContextValue | undefined {\n const store = useOptionalCompositionStore();\n if (!store) {\n return undefined;\n }\n\n return {\n composeComponent: (component, hocs, scope = \"*\", inherit = false) => {\n return store.register(component, hocs as any[], scope, inherit);\n },\n getComponent: (component, scope) => {\n return store.getComponent(component, scope);\n }\n };\n}\n"],"names":["compose","fns","decoratee","decorator","CompositionStoreContext","createContext","undefined","CompositionProvider","decorators","children","storeRef","useRef","store","CompositionStore","decoratable","hocs","useCompositionStore","useContext","Error","useOptionalCompositionStore","useComponent","baseFunction","scope","useCompositionScope","useSyncExternalStore","noopSubscribe","noopGetSnapshot","result","useComposition","component","inherit","useOptionalComposition"],"mappings":";;;AAgBO,SAASA,QAAW,GAAGC,GAAmB;IAC7C,OAAO,CAACC,YACGD,IAAI,WAAW,CAAC,CAACC,WAAWC,YAAcA,UAAUD,YAAYA;AAE/E;AAWA,MAAME,0BAA0B,WAAHA,GAAGC,cAA4CC;AAUrE,MAAMC,sBAAsB,CAAC,EAAEC,aAAa,EAAE,EAAEC,QAAQ,EAA4B;IACvF,MAAMC,WAAWC,OAAgC;IACjD,IAAID,AAAqB,SAArBA,SAAS,OAAO,EAAW;QAC3B,MAAME,QAAQ,IAAIC;QAElB,KAAK,MAAM,CAACC,aAAaC,KAAK,IAAIP,WAC9BI,MAAM,QAAQ,CAACE,YAAY,QAAQ,EAA4BC;QAEnEL,SAAS,OAAO,GAAGE;IACvB;IAEA,OAAO,WAAP,GACI,oBAACR,wBAAwB,QAAQ;QAAC,OAAOM,SAAS,OAAO;OACpDD;AAGb;AAEO,SAASO;IACZ,MAAMJ,QAAQK,WAAWb;IACzB,IAAI,CAACQ,OACD,MAAM,IAAIM,MACN;IAGR,OAAON;AACX;AAEO,SAASO;IACZ,OAAOF,WAAWb;AACtB;AAEO,SAASgB,aAAgBC,YAAe;IAC3C,MAAMT,QAAQO;IACd,MAAMG,QAAQC;IAGdC,qBACIZ,QAAQA,MAAM,SAAS,GAAGa,eAC1Bb,QAAQA,MAAM,WAAW,GAAGc;IAGhC,IAAI,CAACd,OACD,OAAOS;IAGX,MAAMM,SAASf,MAAM,YAAY,CAACS,cAAqBC,MAAM,KAAK,KAAKD;IAEvE,OAAOM;AACX;AAEA,MAAMF,gBAAgB,IAAM,KAAO;AACnC,MAAMC,kBAAkB,IAAM;AAoBvB,SAASE;IACZ,MAAMhB,QAAQI;IAEd,OAAO;QACH,kBAAkB,CAACa,WAAWd,MAAMO,QAAQ,GAAG,EAAEQ,UAAU,KAAK,GACrDlB,MAAM,QAAQ,CAACiB,WAAWd,MAAeO,OAAOQ;QAE3D,cAAc,CAACD,WAAWP,QACfV,MAAM,YAAY,CAACiB,WAAWP;IAE7C;AACJ;AAKO,SAASS;IACZ,MAAMnB,QAAQO;IACd,IAAI,CAACP,OACD;IAGJ,OAAO;QACH,kBAAkB,CAACiB,WAAWd,MAAMO,QAAQ,GAAG,EAAEQ,UAAU,KAAK,GACrDlB,MAAM,QAAQ,CAACiB,WAAWd,MAAeO,OAAOQ;QAE3D,cAAc,CAACD,WAAWP,QACfV,MAAM,YAAY,CAACiB,WAAWP;IAE7C;AACJ"}
package/README.md CHANGED
@@ -1,8 +1,11 @@
1
- # Validation
2
- [![](https://img.shields.io/npm/dw/@webiny/react-composition.svg)](https://www.npmjs.com/package/@webiny/react-composition)
3
- [![](https://img.shields.io/npm/v/@webiny/react-composition.svg)](https://www.npmjs.com/package/@webiny/react-composition)
4
- [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
5
- [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
1
+ # @webiny/react-composition
6
2
 
7
- A tiny composition framework for React components which makes it possible to compose components anywhere in your application.
3
+ > [!NOTE]
4
+ > This package is part of the [Webiny](https://www.webiny.com) monorepo.
5
+ > It’s **included in every Webiny project by default** and is not meant to be used as a standalone package.
8
6
 
7
+ πŸ“˜ **Documentation:** [https://www.webiny.com/docs](https://www.webiny.com/docs)
8
+
9
+ ---
10
+
11
+ _This README file is automatically generated during the publish process._
@@ -0,0 +1,19 @@
1
+ import React from "react";
2
+ import type { CanReturnNullOrElement, Decoratable, DecoratableComponent, DecoratableHook, Decorator } from "./types.js";
3
+ type GetBaseFunction<T> = T extends DecoratableComponent<infer F> ? F : never;
4
+ /**
5
+ * Creates a component which, when mounted, registers a Higher Order Component for the given base component.
6
+ * This is particularly useful for decorating (wrapping) existing composable components.
7
+ * For more information, visit https://www.webiny.com/docs/admin-area/basics/framework.
8
+ */
9
+ export declare function createComponentPlugin<T extends Decoratable>(Base: T, hoc: T extends DecoratableComponent ? Decorator<CanReturnNullOrElement<GetBaseFunction<T>>> : Decorator<GetBaseFunction<T>>): {
10
+ (): React.JSX.Element;
11
+ displayName: string;
12
+ };
13
+ export type GetDecorateeParams<T> = T extends (params?: infer P1) => any ? P1 : T extends (params: infer P2) => any ? P2 : any;
14
+ export type GetDecoratee<T> = T extends DecoratableHook<infer F> ? F : T extends DecoratableComponent<infer F> ? F : never;
15
+ export declare function createDecorator<T extends Decoratable>(Base: T, hoc: T extends DecoratableComponent ? Decorator<CanReturnNullOrElement<GetBaseFunction<T>>> : Decorator<GetBaseFunction<T>>): {
16
+ (): React.JSX.Element;
17
+ displayName: string;
18
+ };
19
+ export {};
@@ -0,0 +1,17 @@
1
+ import react from "react";
2
+ import { Compose } from "./Compose.js";
3
+ function createComponentPlugin(Base, hoc) {
4
+ return createDecorator(Base, hoc);
5
+ }
6
+ const isDecoratableComponent = (decoratable)=>"displayName" in decoratable;
7
+ function createDecorator(Base, hoc) {
8
+ const DecoratorPlugin = ()=>/*#__PURE__*/ react.createElement(Compose, {
9
+ component: Base,
10
+ with: hoc
11
+ });
12
+ if (isDecoratableComponent(Base)) DecoratorPlugin.displayName = Base.displayName;
13
+ return DecoratorPlugin;
14
+ }
15
+ export { createComponentPlugin, createDecorator };
16
+
17
+ //# sourceMappingURL=createDecorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createDecorator.js","sources":["../src/createDecorator.tsx"],"sourcesContent":["import React from \"react\";\nimport type {\n CanReturnNullOrElement,\n Decoratable,\n DecoratableComponent,\n DecoratableHook,\n Decorator\n} from \"~/types.js\";\nimport { Compose } from \"~/Compose.js\";\n\ntype GetBaseFunction<T> = T extends DecoratableComponent<infer F> ? F : never;\n\n/**\n * Creates a component which, when mounted, registers a Higher Order Component for the given base component.\n * This is particularly useful for decorating (wrapping) existing composable components.\n * For more information, visit https://www.webiny.com/docs/admin-area/basics/framework.\n */\nexport function createComponentPlugin<T extends Decoratable>(\n Base: T,\n hoc: T extends DecoratableComponent\n ? Decorator<CanReturnNullOrElement<GetBaseFunction<T>>>\n : Decorator<GetBaseFunction<T>>\n) {\n return createDecorator(Base, hoc);\n}\n\n// Maybe there's a better way to mark params as non-existent, but for now I left it as `any`.\n// TODO: revisit this type; not sure if `?` can be handled in one clause\nexport type GetDecorateeParams<T> = T extends (params?: infer P1) => any\n ? P1\n : T extends (params: infer P2) => any\n ? P2\n : any;\n\nexport type GetDecoratee<T> =\n T extends DecoratableHook<infer F> ? F : T extends DecoratableComponent<infer F> ? F : never;\n\nconst isDecoratableComponent = (\n decoratable: DecoratableComponent | DecoratableHook\n): decoratable is DecoratableComponent => {\n return \"displayName\" in decoratable;\n};\n\nexport function createDecorator<T extends Decoratable>(\n Base: T,\n hoc: T extends DecoratableComponent\n ? Decorator<CanReturnNullOrElement<GetBaseFunction<T>>>\n : Decorator<GetBaseFunction<T>>\n) {\n const DecoratorPlugin = () => <Compose component={Base} with={hoc as any} />;\n if (isDecoratableComponent(Base)) {\n DecoratorPlugin.displayName = Base.displayName;\n }\n return DecoratorPlugin;\n}\n"],"names":["createComponentPlugin","Base","hoc","createDecorator","isDecoratableComponent","decoratable","DecoratorPlugin","Compose"],"mappings":";;AAiBO,SAASA,sBACZC,IAAO,EACPC,GAEmC;IAEnC,OAAOC,gBAAgBF,MAAMC;AACjC;AAaA,MAAME,yBAAyB,CAC3BC,cAEO,iBAAiBA;AAGrB,SAASF,gBACZF,IAAO,EACPC,GAEmC;IAEnC,MAAMI,kBAAkB,kBAAM,oBAACC,SAAOA;YAAC,WAAWN;YAAM,MAAMC;;IAC9D,IAAIE,uBAAuBH,OACvBK,gBAAgB,WAAW,GAAGL,KAAK,WAAW;IAElD,OAAOK;AACX"}
@@ -0,0 +1,15 @@
1
+ import React from "react";
2
+ import type { GetDecoratee, GetDecorateeParams } from "./createDecorator.js";
3
+ import type { DecoratableComponent, GenericComponent, Decorator, GenericHook, DecoratableHook, ComponentDecorator } from "./types.js";
4
+ export interface ShouldDecorate<TDecorator = any, TComponent = any> {
5
+ (decoratorProps: TDecorator, componentProps: TComponent): boolean;
6
+ }
7
+ export declare function createConditionalDecorator<TDecoratee extends GenericComponent>(shouldDecorate: ShouldDecorate, decorator: Decorator<TDecoratee>, decoratorProps: unknown): Decorator<TDecoratee>;
8
+ export declare function createDecoratorFactory<TDecorator>(): <TDecoratable extends DecoratableComponent>(decoratable: TDecoratable, shouldDecorate?: ShouldDecorate<TDecorator, GetDecorateeParams<GetDecoratee<TDecoratable>>>) => (decorator: ComponentDecorator<GetDecoratee<TDecoratable>>) => (props: TDecorator) => React.JSX.Element;
9
+ export declare function createHookDecoratorFactory(): <TDecoratable extends DecoratableHook>(decoratable: TDecoratable) => (decorator: Decorator<GetDecoratee<TDecoratable>>) => () => React.JSX.Element;
10
+ export declare function withDecoratorFactory<TDecorator>(): <TDecoratable extends DecoratableComponent>(Component: TDecoratable, shouldDecorate?: ShouldDecorate<TDecorator, GetDecorateeParams<GetDecoratee<TDecoratable>>>) => TDecoratable & {
11
+ createDecorator: (decorator: ComponentDecorator<GetDecoratee<TDecoratable>>) => (props: TDecorator) => React.JSX.Element;
12
+ };
13
+ export declare function withHookDecoratorFactory(): <TDecoratable extends DecoratableHook>(hook: TDecoratable) => DecoratableHook<GenericHook<GetDecorateeParams<GetDecoratee<TDecoratable>>, ReturnType<GetDecoratee<TDecoratable>>>> & {
14
+ createDecorator: (decorator: Decorator<GetDecoratee<TDecoratable>>) => () => React.JSX.Element;
15
+ };
package/decorators.js ADDED
@@ -0,0 +1,63 @@
1
+ import react from "react";
2
+ import { Compose } from "./Compose.js";
3
+ function createConditionalDecorator(shouldDecorate, decorator, decoratorProps) {
4
+ return (Original)=>{
5
+ const DecoratedComponent = /*#__PURE__*/ react.memo(decorator(Original));
6
+ DecoratedComponent.displayName = Original.displayName;
7
+ return function(props) {
8
+ if (shouldDecorate(decoratorProps, props)) return /*#__PURE__*/ react.createElement(DecoratedComponent, props);
9
+ return /*#__PURE__*/ react.createElement(Original, props);
10
+ };
11
+ };
12
+ }
13
+ const memoizedComponent = (decorator)=>(decoratee)=>/*#__PURE__*/ react.memo(decorator(decoratee));
14
+ function createDecoratorFactory() {
15
+ return function(decoratable, shouldDecorate) {
16
+ return function(decorator) {
17
+ return function(props) {
18
+ if (shouldDecorate) {
19
+ const componentDecorator = createConditionalDecorator(shouldDecorate, decorator, props);
20
+ return /*#__PURE__*/ react.createElement(Compose, {
21
+ function: decoratable,
22
+ with: componentDecorator
23
+ });
24
+ }
25
+ return /*#__PURE__*/ react.createElement(Compose, {
26
+ function: decoratable,
27
+ with: memoizedComponent(decorator)
28
+ });
29
+ };
30
+ };
31
+ };
32
+ }
33
+ function createHookDecoratorFactory() {
34
+ return function(decoratable) {
35
+ return function(decorator) {
36
+ return function() {
37
+ return /*#__PURE__*/ react.createElement(Compose, {
38
+ function: decoratable,
39
+ with: decorator
40
+ });
41
+ };
42
+ };
43
+ };
44
+ }
45
+ function withDecoratorFactory() {
46
+ return function(Component, shouldDecorate) {
47
+ const createDecorator = createDecoratorFactory()(Component, shouldDecorate);
48
+ return Object.assign(Component, {
49
+ createDecorator
50
+ });
51
+ };
52
+ }
53
+ function withHookDecoratorFactory() {
54
+ return function(hook) {
55
+ const createDecorator = createHookDecoratorFactory()(hook);
56
+ return Object.assign(hook, {
57
+ createDecorator
58
+ });
59
+ };
60
+ }
61
+ export { createConditionalDecorator, createDecoratorFactory, createHookDecoratorFactory, withDecoratorFactory, withHookDecoratorFactory };
62
+
63
+ //# sourceMappingURL=decorators.js.map