@webiny/react-composition 6.0.0-beta.0 → 6.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Compose.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { DecoratableTypes } from "./Context";
2
- import { ComposeWith } from "./types";
1
+ import React from "react";
2
+ import type { DecoratableTypes } from "./Context.js";
3
+ import type { ComposeWith } from "./types.js";
3
4
  export interface ComposeProps {
4
5
  function?: DecoratableTypes;
5
6
  component?: DecoratableTypes;
6
7
  with: ComposeWith;
7
8
  }
8
- export declare const Compose: (props: ComposeProps) => null;
9
+ export declare const Compose: (props: ComposeProps) => React.JSX.Element | null;
package/Compose.js CHANGED
@@ -1,26 +1,68 @@
1
- "use strict";
1
+ import React, { useEffect, useRef } from "react";
2
+ import { useCompositionStore } from "./Context.js";
3
+ import { useCompositionScope } from "./CompositionScope.js";
4
+ export const Compose = props => {
5
+ const store = useCompositionStore();
6
+ const {
7
+ scope,
8
+ inherit
9
+ } = useCompositionScope();
10
+ const targetFn = props.function ?? props.component;
11
+ if (!targetFn) {
12
+ console.warn("You must provide a function or a component to compose with!", props);
13
+ return null;
14
+ }
15
+ if (typeof targetFn.original === "undefined") {
16
+ console.warn(`You must make your function "${targetFn.originalName ?? targetFn.name}" composable, by using the makeDecoratable() function!`);
17
+ return null;
18
+ }
19
+ const decorators = Array.isArray(props.with) ? props.with : [props.with];
20
+ const currentScope = scope[scope.length - 1] ?? "*";
2
21
 
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.Compose = void 0;
7
- var _react = require("react");
8
- var _Context = require("./Context");
9
- var _CompositionScope = require("./CompositionScope");
10
- var Compose = exports.Compose = function Compose(props) {
11
- var _useComposition = (0, _Context.useComposition)(),
12
- composeComponent = _useComposition.composeComponent;
13
- var scope = (0, _CompositionScope.useCompositionScope)();
14
- var targetFn = props.function ?? props.component;
15
- (0, _react.useEffect)(function () {
16
- if (typeof targetFn.original === "undefined") {
17
- console.warn("You must make your function \"".concat(targetFn.originalName ?? targetFn.name, "\" composable, by using the makeDecoratable() function!"));
18
- return;
22
+ // Register synchronously during render so decorators are available immediately.
23
+ // Pass silent=true to avoid notifying listeners mid-render (which would trigger
24
+ // setState in other components and cause React warnings).
25
+ store.register(targetFn.original, decorators, currentScope, inherit, true);
26
+ return /*#__PURE__*/React.createElement(ComposeEffects, {
27
+ store: store,
28
+ target: targetFn.original,
29
+ decorators: decorators,
30
+ scope: currentScope
31
+ });
32
+ };
33
+
34
+ /**
35
+ * Separate component for the effect to avoid re-running the cleanup on every render.
36
+ * This component handles cleanup on unmount and when props change.
37
+ */
38
+ function ComposeEffects({
39
+ store,
40
+ target,
41
+ decorators,
42
+ scope
43
+ }) {
44
+ const prevRef = useRef(null);
45
+ useEffect(() => {
46
+ const prev = prevRef.current;
47
+
48
+ // On prop change: unregister old decorators.
49
+ if (prev && (prev.decorators !== decorators || prev.scope !== scope)) {
50
+ store.unregister(target, prev.decorators, prev.scope);
51
+ // Re-register new ones (they were already registered during render,
52
+ // but the idempotency check handles this).
53
+ store.register(target, decorators, scope);
19
54
  }
20
- var decorators = Array.isArray(props.with) ? props.with : [props.with];
21
- return composeComponent(targetFn.original, decorators, scope);
22
- }, [props.with]);
55
+ prevRef.current = {
56
+ decorators,
57
+ scope
58
+ };
59
+
60
+ // Cleanup on unmount.
61
+ return () => {
62
+ store.unregister(target, decorators, scope);
63
+ };
64
+ }, [store, target, decorators, scope]);
23
65
  return null;
24
- };
66
+ }
25
67
 
26
68
  //# sourceMappingURL=Compose.js.map
package/Compose.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["_react","require","_Context","_CompositionScope","Compose","exports","props","_useComposition","useComposition","composeComponent","scope","useCompositionScope","targetFn","function","component","useEffect","original","console","warn","concat","originalName","name","decorators","Array","isArray","with"],"sources":["Compose.tsx"],"sourcesContent":["import { useEffect } from \"react\";\nimport { DecoratableTypes, useComposition } from \"./Context\";\nimport { useCompositionScope } from \"~/CompositionScope\";\nimport { ComposeWith, Decoratable, Enumerable } from \"./types\";\n\nexport interface ComposeProps {\n function?: DecoratableTypes;\n component?: DecoratableTypes;\n with: ComposeWith;\n}\n\nexport const Compose = (props: ComposeProps) => {\n const { composeComponent } = useComposition();\n const scope = useCompositionScope();\n\n const targetFn = (props.function ?? props.component) as Decoratable;\n\n useEffect(() => {\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\n return;\n }\n\n const decorators = Array.isArray(props.with) ? props.with : [props.with];\n return composeComponent(targetFn.original, decorators as Enumerable<ComposeWith>, scope);\n }, [props.with]);\n\n return null;\n};\n"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,QAAA,GAAAD,OAAA;AACA,IAAAE,iBAAA,GAAAF,OAAA;AASO,IAAMG,OAAO,GAAAC,OAAA,CAAAD,OAAA,GAAG,SAAVA,OAAOA,CAAIE,KAAmB,EAAK;EAC5C,IAAAC,eAAA,GAA6B,IAAAC,uBAAc,EAAC,CAAC;IAArCC,gBAAgB,GAAAF,eAAA,CAAhBE,gBAAgB;EACxB,IAAMC,KAAK,GAAG,IAAAC,qCAAmB,EAAC,CAAC;EAEnC,IAAMC,QAAQ,GAAIN,KAAK,CAACO,QAAQ,IAAIP,KAAK,CAACQ,SAAyB;EAEnE,IAAAC,gBAAS,EAAC,YAAM;IACZ,IAAI,OAAOH,QAAQ,CAACI,QAAQ,KAAK,WAAW,EAAE;MAC1CC,OAAO,CAACC,IAAI,kCAAAC,MAAA,CAEJP,QAAQ,CAACQ,YAAY,IAAIR,QAAQ,CAACS,IAAI,4DAE9C,CAAC;MAED;IACJ;IAEA,IAAMC,UAAU,GAAGC,KAAK,CAACC,OAAO,CAAClB,KAAK,CAACmB,IAAI,CAAC,GAAGnB,KAAK,CAACmB,IAAI,GAAG,CAACnB,KAAK,CAACmB,IAAI,CAAC;IACxE,OAAOhB,gBAAgB,CAACG,QAAQ,CAACI,QAAQ,EAAEM,UAAU,EAA6BZ,KAAK,CAAC;EAC5F,CAAC,EAAE,CAACJ,KAAK,CAACmB,IAAI,CAAC,CAAC;EAEhB,OAAO,IAAI;AACf,CAAC","ignoreList":[]}
1
+ {"version":3,"names":["React","useEffect","useRef","useCompositionStore","useCompositionScope","Compose","props","store","scope","inherit","targetFn","function","component","console","warn","original","originalName","name","decorators","Array","isArray","with","currentScope","length","register","createElement","ComposeEffects","target","prevRef","prev","current","unregister"],"sources":["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 />\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}: {\n store: ReturnType<typeof useCompositionStore>;\n target: any;\n decorators: Decorator<GenericComponent | GenericHook>[];\n scope: string;\n}) {\n const prevRef = useRef<{\n decorators: Decorator<GenericComponent | GenericHook>[];\n scope: string;\n } | null>(null);\n\n useEffect(() => {\n const prev = prevRef.current;\n\n // On prop change: unregister old decorators.\n if (prev && (prev.decorators !== decorators || prev.scope !== scope)) {\n store.unregister(target, prev.decorators, prev.scope);\n // Re-register new ones (they were already registered during render,\n // but the idempotency check handles this).\n store.register(target, decorators, scope);\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"],"mappings":"AAAA,OAAOA,KAAK,IAAIC,SAAS,EAAEC,MAAM,QAAQ,OAAO;AAEhD,SAASC,mBAAmB;AAC5B,SAASC,mBAAmB;AAe5B,OAAO,MAAMC,OAAO,GAAIC,KAAmB,IAAK;EAC5C,MAAMC,KAAK,GAAGJ,mBAAmB,CAAC,CAAC;EACnC,MAAM;IAAEK,KAAK;IAAEC;EAAQ,CAAC,GAAGL,mBAAmB,CAAC,CAAC;EAEhD,MAAMM,QAAQ,GAAIJ,KAAK,CAACK,QAAQ,IAAIL,KAAK,CAACM,SAAyB;EAEnE,IAAI,CAACF,QAAQ,EAAE;IACXG,OAAO,CAACC,IAAI,CAAC,6DAA6D,EAAER,KAAK,CAAC;IAClF,OAAO,IAAI;EACf;EAEA,IAAI,OAAOI,QAAQ,CAACK,QAAQ,KAAK,WAAW,EAAE;IAC1CF,OAAO,CAACC,IAAI,CACR,gCACIJ,QAAQ,CAACM,YAAY,IAAIN,QAAQ,CAACO,IAAI,wDAE9C,CAAC;IACD,OAAO,IAAI;EACf;EAEA,MAAMC,UAAU,GAAIC,KAAK,CAACC,OAAO,CAACd,KAAK,CAACe,IAAI,CAA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,EAAEV,KAAK,CAAC,CAAC;EAEtC,OAAO,IAAI;AACf","ignoreList":[]}
@@ -1,11 +1,17 @@
1
1
  import React from "react";
2
2
  export interface CompositionScopeContext {
3
- name: string;
3
+ inherit: boolean;
4
+ scope: string[];
4
5
  }
5
6
  interface CompositionScopeProps {
6
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;
7
13
  children: React.ReactNode;
8
14
  }
9
- export declare const CompositionScope: ({ name, children }: CompositionScopeProps) => React.JSX.Element;
10
- export declare function useCompositionScope(): string | undefined;
15
+ export declare const CompositionScope: ({ name, inherit, children }: CompositionScopeProps) => React.JSX.Element;
16
+ export declare function useCompositionScope(): CompositionScopeContext;
11
17
  export {};
@@ -1,28 +1,27 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.CompositionScope = void 0;
8
- exports.useCompositionScope = useCompositionScope;
9
- var _react = _interopRequireDefault(require("react"));
10
- var CompositionScopeContext = /*#__PURE__*/_react.default.createContext(undefined);
11
- var CompositionScope = exports.CompositionScope = function CompositionScope(_ref) {
12
- var name = _ref.name,
13
- children = _ref.children;
14
- return /*#__PURE__*/_react.default.createElement(CompositionScopeContext.Provider, {
1
+ import React from "react";
2
+ const CompositionScopeContext = /*#__PURE__*/React.createContext(undefined);
3
+ export const CompositionScope = ({
4
+ name,
5
+ inherit = false,
6
+ children
7
+ }) => {
8
+ const parentScope = useCompositionScope();
9
+ return /*#__PURE__*/React.createElement(CompositionScopeContext.Provider, {
15
10
  value: {
16
- name: name
11
+ scope: [...parentScope.scope, name],
12
+ inherit
17
13
  }
18
14
  }, children);
19
15
  };
20
- function useCompositionScope() {
21
- var context = _react.default.useContext(CompositionScopeContext);
16
+ export function useCompositionScope() {
17
+ const context = React.useContext(CompositionScopeContext);
22
18
  if (!context) {
23
- return undefined;
19
+ return {
20
+ scope: [],
21
+ inherit: false
22
+ };
24
23
  }
25
- return context.name;
24
+ return context;
26
25
  }
27
26
 
28
27
  //# sourceMappingURL=CompositionScope.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["_react","_interopRequireDefault","require","CompositionScopeContext","React","createContext","undefined","CompositionScope","exports","_ref","name","children","default","createElement","Provider","value","useCompositionScope","context","useContext"],"sources":["CompositionScope.tsx"],"sourcesContent":["import React from \"react\";\n\nexport interface CompositionScopeContext {\n name: string;\n}\n\nconst CompositionScopeContext = React.createContext<CompositionScopeContext | undefined>(undefined);\n\ninterface CompositionScopeProps {\n name: string;\n children: React.ReactNode;\n}\n\nexport const CompositionScope = ({ name, children }: CompositionScopeProps) => {\n return (\n <CompositionScopeContext.Provider value={{ name }}>\n {children}\n </CompositionScopeContext.Provider>\n );\n};\n\nexport function useCompositionScope() {\n const context = React.useContext(CompositionScopeContext);\n if (!context) {\n return undefined;\n }\n return context.name;\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AAMA,IAAMC,uBAAuB,gBAAGC,cAAK,CAACC,aAAa,CAAsCC,SAAS,CAAC;AAO5F,IAAMC,gBAAgB,GAAAC,OAAA,CAAAD,gBAAA,GAAG,SAAnBA,gBAAgBA,CAAAE,IAAA,EAAkD;EAAA,IAA5CC,IAAI,GAAAD,IAAA,CAAJC,IAAI;IAAEC,QAAQ,GAAAF,IAAA,CAARE,QAAQ;EAC7C,oBACIX,MAAA,CAAAY,OAAA,CAAAC,aAAA,CAACV,uBAAuB,CAACW,QAAQ;IAACC,KAAK,EAAE;MAAEL,IAAI,EAAJA;IAAK;EAAE,GAC7CC,QAC6B,CAAC;AAE3C,CAAC;AAEM,SAASK,mBAAmBA,CAAA,EAAG;EAClC,IAAMC,OAAO,GAAGb,cAAK,CAACc,UAAU,CAACf,uBAAuB,CAAC;EACzD,IAAI,CAACc,OAAO,EAAE;IACV,OAAOX,SAAS;EACpB;EACA,OAAOW,OAAO,CAACP,IAAI;AACvB","ignoreList":[]}
1
+ {"version":3,"names":["React","CompositionScopeContext","createContext","undefined","CompositionScope","name","inherit","children","parentScope","useCompositionScope","createElement","Provider","value","scope","context","useContext"],"sources":["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"],"mappings":"AAAA,OAAOA,KAAK,MAAM,OAAO;AAOzB,MAAMC,uBAAuB,gBAAGD,KAAK,CAACE,aAAa,CAAsCC,SAAS,CAAC;AAYnG,OAAO,MAAMC,gBAAgB,GAAGA,CAAC;EAAEC,IAAI;EAAEC,OAAO,GAAG,KAAK;EAAEC;AAAgC,CAAC,KAAK;EAC5F,MAAMC,WAAW,GAAGC,mBAAmB,CAAC,CAAC;EAEzC,oBACIT,KAAA,CAAAU,aAAA,CAACT,uBAAuB,CAACU,QAAQ;IAACC,KAAK,EAAE;MAAEC,KAAK,EAAE,CAAC,GAAGL,WAAW,CAACK,KAAK,EAAER,IAAI,CAAC;MAAEC;IAAQ;EAAE,GACrFC,QAC6B,CAAC;AAE3C,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAAG;EAClC,MAAMK,OAAO,GAAGd,KAAK,CAACe,UAAU,CAACd,uBAAuB,CAAC;EAEzD,IAAI,CAACa,OAAO,EAAE;IACV,OAAO;MAAED,KAAK,EAAE,EAAE;MAAEP,OAAO,EAAE;IAAM,CAAC;EACxC;EAEA,OAAOQ,OAAO;AAClB","ignoreList":[]}
package/Context.d.ts CHANGED
@@ -1,49 +1,35 @@
1
- import React, { ComponentType } from "react";
2
- import { ComposedFunction, ComposeWith, DecoratableComponent, DecoratableHook, Decorator, Enumerable, GenericComponent, GenericHook } from "./types";
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";
3
5
  export declare function compose<T>(...fns: Decorator<T>[]): (decoratee: T) => T;
4
- interface ComposedComponent {
5
- /**
6
- * Ready to use React component.
7
- */
8
- component: GenericHook | GenericComponent;
9
- /**
10
- * HOCs used to compose the original component.
11
- */
12
- hocs: Decorator<GenericComponent | GenericHook>[];
13
- /**
14
- * Component composition can be scoped.
15
- */
16
- scope?: string;
17
- }
18
6
  /**
19
7
  * @deprecated Use `Decorator` instead.
20
8
  */
21
9
  export interface HigherOrderComponent<TProps = any, TOutput = TProps> {
22
10
  (Component: GenericComponent<TProps>): GenericComponent<TOutput>;
23
11
  }
24
- declare type ComposedComponents = Map<ComponentType<unknown>, ComposedComponent>;
25
- declare type ComponentScopes = Map<string, ComposedComponents>;
26
- export declare type DecoratableTypes = DecoratableComponent | DecoratableHook;
27
- interface CompositionContextGetComponentCallable {
28
- (component: ComponentType<unknown>, scope?: string): ComposedFunction | GenericComponent | undefined;
29
- }
30
- interface CompositionContext {
31
- components: ComponentScopes;
32
- getComponent: CompositionContextGetComponentCallable;
33
- composeComponent(component: ComponentType<unknown>, hocs: Enumerable<ComposeWith>, scope?: string): void;
34
- }
35
- declare const CompositionContext: React.Context<CompositionContext | undefined>;
12
+ export type DecoratableTypes = DecoratableComponent | DecoratableHook;
13
+ export type DecoratorsTuple = [Decoratable, Decorator<any>[]];
14
+ export type DecoratorsCollection = Array<DecoratorsTuple>;
36
15
  interface CompositionProviderProps {
16
+ decorators?: DecoratorsCollection;
37
17
  children: React.ReactNode;
38
18
  }
39
- export declare const CompositionProvider: ({ children }: CompositionProviderProps) => React.JSX.Element;
19
+ export declare const CompositionProvider: ({ decorators, children }: CompositionProviderProps) => React.JSX.Element;
20
+ export declare function useCompositionStore(): CompositionStore;
21
+ export declare function useOptionalCompositionStore(): CompositionStore | undefined;
40
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
+ }
41
27
  /**
42
28
  * This hook will throw an error if composition context doesn't exist.
43
29
  */
44
- export declare function useComposition(): CompositionContext;
30
+ export declare function useComposition(): CompositionContextValue;
45
31
  /**
46
32
  * This hook will not throw an error if composition context doesn't exist.
47
33
  */
48
- export declare function useOptionalComposition(): CompositionContext | undefined;
34
+ export declare function useOptionalComposition(): CompositionContextValue | undefined;
49
35
  export {};
package/Context.js CHANGED
@@ -1,27 +1,9 @@
1
- "use strict";
2
-
3
- var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
4
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports.CompositionProvider = void 0;
9
- exports.compose = compose;
10
- exports.useComponent = useComponent;
11
- exports.useComposition = useComposition;
12
- exports.useOptionalComposition = useOptionalComposition;
13
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
14
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
15
- var _react = _interopRequireWildcard(require("react"));
16
- var _CompositionScope = require("./CompositionScope");
17
- function compose() {
18
- for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
19
- fns[_key] = arguments[_key];
20
- }
21
- return function (decoratee) {
22
- return fns.reduceRight(function (decoratee, decorator) {
23
- return decorator(decoratee);
24
- }, decoratee);
1
+ import React, { createContext, useContext, useRef, useSyncExternalStore } from "react";
2
+ import { useCompositionScope } from "./CompositionScope.js";
3
+ import { CompositionStore } from "./domain/CompositionStore.js";
4
+ export function compose(...fns) {
5
+ return decoratee => {
6
+ return fns.reduceRight((decoratee, decorator) => decorator(decoratee), decoratee);
25
7
  };
26
8
  }
27
9
 
@@ -29,101 +11,81 @@ function compose() {
29
11
  * @deprecated Use `Decorator` instead.
30
12
  */
31
13
 
32
- var CompositionContext = /*#__PURE__*/(0, _react.createContext)(undefined);
33
- var CompositionProvider = exports.CompositionProvider = function CompositionProvider(_ref) {
34
- var children = _ref.children;
35
- var _useState = (0, _react.useState)(new Map()),
36
- _useState2 = (0, _slicedToArray2.default)(_useState, 2),
37
- components = _useState2[0],
38
- setComponents = _useState2[1];
39
- var composeComponent = (0, _react.useCallback)(function (component, hocs) {
40
- var scope = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "*";
41
- setComponents(function (prevComponents) {
42
- var components = new Map(prevComponents);
43
- var scopeMap = components.get(scope) || new Map();
44
- var recipe = scopeMap.get(component) || {
45
- component: null,
46
- hocs: []
47
- };
48
- var newHocs = [].concat((0, _toConsumableArray2.default)(recipe.hocs || []), (0, _toConsumableArray2.default)(hocs));
49
- scopeMap.set(component, {
50
- component: compose.apply(void 0, (0, _toConsumableArray2.default)((0, _toConsumableArray2.default)(newHocs).reverse()))(component),
51
- hocs: newHocs
52
- });
53
- components.set(scope, scopeMap);
54
- return components;
55
- });
56
-
57
- // Return a function that will remove the added HOCs.
58
- return function () {
59
- setComponents(function (prevComponents) {
60
- var components = new Map(prevComponents);
61
- var scopeMap = components.get(scope) || new Map();
62
- var recipe = scopeMap.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
- scopeMap.set(component, {
71
- component: NewComponent,
72
- hocs: newHOCs
73
- });
74
- components.set(scope, scopeMap);
75
- return components;
76
- });
77
- };
78
- }, [setComponents]);
79
- var getComponent = (0, _react.useCallback)(function (Component) {
80
- var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "*";
81
- var scopeMap = components.get(scope) || new Map();
82
- var composedComponent = scopeMap.get(Component);
83
- if (!composedComponent && scope !== "*") {
84
- // Check if a default scope component exists
85
- var defaultScopeMap = components.get("*") || new Map();
86
- var defaultComponent = defaultScopeMap.get(Component);
87
- return defaultComponent ? defaultComponent.component : undefined;
14
+ const CompositionStoreContext = /*#__PURE__*/createContext(undefined);
15
+ export const CompositionProvider = ({
16
+ decorators = [],
17
+ children
18
+ }) => {
19
+ const storeRef = useRef(null);
20
+ if (storeRef.current === null) {
21
+ const store = new CompositionStore();
22
+ // Pre-register decorators from props.
23
+ for (const [decoratable, hocs] of decorators) {
24
+ store.register(decoratable.original, hocs);
88
25
  }
89
- return composedComponent ? composedComponent.component : undefined;
90
- }, [components]);
91
- var context = (0, _react.useMemo)(function () {
92
- return {
93
- getComponent: getComponent,
94
- composeComponent: composeComponent,
95
- components: components
96
- };
97
- }, [components, composeComponent]);
98
- return /*#__PURE__*/_react.default.createElement(CompositionContext.Provider, {
99
- value: context
26
+ storeRef.current = store;
27
+ }
28
+ return /*#__PURE__*/React.createElement(CompositionStoreContext.Provider, {
29
+ value: storeRef.current
100
30
  }, children);
101
31
  };
102
- function useComponent(baseFunction) {
103
- var context = useOptionalComposition();
104
- var scope = (0, _CompositionScope.useCompositionScope)();
105
- if (!context) {
32
+ export function useCompositionStore() {
33
+ const store = useContext(CompositionStoreContext);
34
+ if (!store) {
35
+ throw new Error(`You're missing a <CompositionProvider> higher up in your component hierarchy!`);
36
+ }
37
+ return store;
38
+ }
39
+ export function useOptionalCompositionStore() {
40
+ return useContext(CompositionStoreContext);
41
+ }
42
+ export function useComponent(baseFunction) {
43
+ const store = useOptionalCompositionStore();
44
+ const scope = useCompositionScope();
45
+
46
+ // Subscribe to store changes so we re-render when compositions change.
47
+ useSyncExternalStore(store ? store.subscribe : noopSubscribe, store ? store.getSnapshot : noopGetSnapshot);
48
+ if (!store) {
106
49
  return baseFunction;
107
50
  }
108
- return context.getComponent(baseFunction, scope) || baseFunction;
51
+ return store.getComponent(baseFunction, scope.scope) || baseFunction;
109
52
  }
53
+ const noopSubscribe = () => () => {};
54
+ const noopGetSnapshot = () => 0;
55
+
56
+ // Legacy compatibility — kept for any external consumers.
110
57
 
111
58
  /**
112
59
  * This hook will throw an error if composition context doesn't exist.
113
60
  */
114
- function useComposition() {
115
- var context = (0, _react.useContext)(CompositionContext);
116
- if (!context) {
117
- throw new Error("You're missing a <CompositionProvider> higher up in your component hierarchy!");
118
- }
119
- return context;
61
+ export function useComposition() {
62
+ const store = useCompositionStore();
63
+ return {
64
+ composeComponent: (component, hocs, scope = "*", inherit = false) => {
65
+ return store.register(component, hocs, scope, inherit);
66
+ },
67
+ getComponent: (component, scope) => {
68
+ return store.getComponent(component, scope);
69
+ }
70
+ };
120
71
  }
121
72
 
122
73
  /**
123
74
  * This hook will not throw an error if composition context doesn't exist.
124
75
  */
125
- function useOptionalComposition() {
126
- return (0, _react.useContext)(CompositionContext);
76
+ export function useOptionalComposition() {
77
+ const store = useOptionalCompositionStore();
78
+ if (!store) {
79
+ return undefined;
80
+ }
81
+ return {
82
+ composeComponent: (component, hocs, scope = "*", inherit = false) => {
83
+ return store.register(component, hocs, scope, inherit);
84
+ },
85
+ getComponent: (component, scope) => {
86
+ return store.getComponent(component, scope);
87
+ }
88
+ };
127
89
  }
128
90
 
129
91
  //# sourceMappingURL=Context.js.map
package/Context.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["_react","_interopRequireWildcard","require","_CompositionScope","compose","_len","arguments","length","fns","Array","_key","decoratee","reduceRight","decorator","CompositionContext","createContext","undefined","CompositionProvider","exports","_ref","children","_useState","useState","Map","_useState2","_slicedToArray2","default","components","setComponents","composeComponent","useCallback","component","hocs","scope","prevComponents","scopeMap","get","recipe","newHocs","concat","_toConsumableArray2","set","apply","reverse","newHOCs","filter","hoc","includes","NewComponent","getComponent","Component","composedComponent","defaultScopeMap","defaultComponent","context","useMemo","createElement","Provider","value","useComponent","baseFunction","useOptionalComposition","useCompositionScope","useComposition","useContext","Error"],"sources":["Context.tsx"],"sourcesContent":["import React, {\n ComponentType,\n createContext,\n useCallback,\n useContext,\n useMemo,\n useState\n} from \"react\";\nimport { useCompositionScope } from \"~/CompositionScope\";\nimport {\n ComposedFunction,\n ComposeWith,\n DecoratableComponent,\n DecoratableHook,\n Decorator,\n Enumerable,\n GenericComponent,\n GenericHook\n} from \"~/types\";\n\nexport function compose<T>(...fns: Decorator<T>[]) {\n return (decoratee: T): T => {\n return fns.reduceRight((decoratee, decorator) => decorator(decoratee), decoratee);\n };\n}\n\ninterface ComposedComponent {\n /**\n * Ready to use React component.\n */\n component: GenericHook | GenericComponent;\n /**\n * HOCs used to compose the original component.\n */\n hocs: Decorator<GenericComponent | GenericHook>[];\n /**\n * Component composition can be scoped.\n */\n scope?: string;\n}\n\n/**\n * @deprecated Use `Decorator` instead.\n */\nexport interface HigherOrderComponent<TProps = any, TOutput = TProps> {\n (Component: GenericComponent<TProps>): GenericComponent<TOutput>;\n}\n\ntype ComposedComponents = Map<ComponentType<unknown>, ComposedComponent>;\ntype ComponentScopes = Map<string, ComposedComponents>;\n\nexport type DecoratableTypes = DecoratableComponent | DecoratableHook;\n\ninterface CompositionContextGetComponentCallable {\n (component: ComponentType<unknown>, scope?: string):\n | ComposedFunction\n | GenericComponent\n | undefined;\n}\n\ninterface CompositionContext {\n components: ComponentScopes;\n getComponent: CompositionContextGetComponentCallable;\n composeComponent(\n component: ComponentType<unknown>,\n hocs: Enumerable<ComposeWith>,\n scope?: string\n ): void;\n}\n\nconst CompositionContext = createContext<CompositionContext | undefined>(undefined);\n\ninterface CompositionProviderProps {\n children: React.ReactNode;\n}\n\nexport const CompositionProvider = ({ children }: CompositionProviderProps) => {\n const [components, setComponents] = useState<ComponentScopes>(new Map());\n\n const composeComponent = useCallback(\n (\n component: GenericHook | GenericComponent,\n hocs: HigherOrderComponent<any, any>[],\n scope: string | undefined = \"*\"\n ) => {\n setComponents(prevComponents => {\n const components = new Map(prevComponents);\n const scopeMap: ComposedComponents = components.get(scope) || new Map();\n const recipe = scopeMap.get(component) || { component: null, hocs: [] };\n\n const newHocs = [...(recipe.hocs || []), ...hocs] as Decorator<\n GenericHook | GenericComponent\n >[];\n\n scopeMap.set(component, {\n component: compose(...[...newHocs].reverse())(component),\n hocs: newHocs\n });\n\n components.set(scope, scopeMap);\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 scopeMap: ComposedComponents = components.get(scope) || new Map();\n const recipe = scopeMap.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 scopeMap.set(component, {\n component: NewComponent,\n hocs: newHOCs\n });\n\n components.set(scope, scopeMap);\n return components;\n });\n };\n },\n [setComponents]\n );\n\n const getComponent = useCallback<CompositionContextGetComponentCallable>(\n (Component, scope = \"*\") => {\n const scopeMap: ComposedComponents = components.get(scope) || new Map();\n const composedComponent = scopeMap.get(Component);\n if (!composedComponent && scope !== \"*\") {\n // Check if a default scope component exists\n const defaultScopeMap: ComposedComponents = components.get(\"*\") || new Map();\n const defaultComponent = defaultScopeMap.get(Component);\n return defaultComponent ? defaultComponent.component : undefined;\n }\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<T>(baseFunction: T) {\n const context = useOptionalComposition();\n const scope = useCompositionScope();\n\n if (!context) {\n return baseFunction;\n }\n\n return (context.getComponent(baseFunction as any, scope) || baseFunction) as T;\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":";;;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,uBAAA,CAAAC,OAAA;AAQA,IAAAC,iBAAA,GAAAD,OAAA;AAYO,SAASE,OAAOA,CAAA,EAA4B;EAAA,SAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,EAArBC,GAAG,OAAAC,KAAA,CAAAJ,IAAA,GAAAK,IAAA,MAAAA,IAAA,GAAAL,IAAA,EAAAK,IAAA;IAAHF,GAAG,CAAAE,IAAA,IAAAJ,SAAA,CAAAI,IAAA;EAAA;EAC7B,OAAO,UAACC,SAAY,EAAQ;IACxB,OAAOH,GAAG,CAACI,WAAW,CAAC,UAACD,SAAS,EAAEE,SAAS;MAAA,OAAKA,SAAS,CAACF,SAAS,CAAC;IAAA,GAAEA,SAAS,CAAC;EACrF,CAAC;AACL;;AAiBA;AACA;AACA;;AA2BA,IAAMG,kBAAkB,gBAAG,IAAAC,oBAAa,EAAiCC,SAAS,CAAC;AAM5E,IAAMC,mBAAmB,GAAAC,OAAA,CAAAD,mBAAA,GAAG,SAAtBA,mBAAmBA,CAAAE,IAAA,EAA+C;EAAA,IAAzCC,QAAQ,GAAAD,IAAA,CAARC,QAAQ;EAC1C,IAAAC,SAAA,GAAoC,IAAAC,eAAQ,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O,sBAAsBA,CAAA,EAAG;EACrC,OAAO,IAAAG,iBAAU,EAAClD,kBAAkB,CAAC;AACzC","ignoreList":[]}
1
+ {"version":3,"names":["React","createContext","useContext","useRef","useSyncExternalStore","useCompositionScope","CompositionStore","compose","fns","decoratee","reduceRight","decorator","CompositionStoreContext","undefined","CompositionProvider","decorators","children","storeRef","current","store","decoratable","hocs","register","original","createElement","Provider","value","useCompositionStore","Error","useOptionalCompositionStore","useComponent","baseFunction","scope","subscribe","noopSubscribe","getSnapshot","noopGetSnapshot","getComponent","useComposition","composeComponent","component","inherit","useOptionalComposition"],"sources":["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\";\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 return (store.getComponent(baseFunction as any, scope.scope) || baseFunction) 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"],"mappings":"AACA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,EAAEA,CAACC,SAAS,EAAEnB,IAAI,EAAEW,KAAK,GAAG,GAAG,EAAES,OAAO,GAAG,KAAK,KAAK;MACjE,OAAOtB,KAAK,CAACG,QAAQ,CAACkB,SAAS,EAAEnB,IAAI,EAAWW,KAAK,EAAES,OAAO,CAAC;IACnE,CAAC;IACDJ,YAAY,EAAEA,CAACG,SAAS,EAAER,KAAK,KAAK;MAChC,OAAOb,KAAK,CAACkB,YAAY,CAACG,SAAS,EAAER,KAAK,CAAC;IAC/C;EACJ,CAAC;AACL","ignoreList":[]}
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._
@@ -1,18 +1,18 @@
1
1
  import React from "react";
2
- import { CanReturnNull, Decoratable, DecoratableComponent, DecoratableHook, Decorator } from "./types";
3
- declare type GetBaseFunction<T> = T extends DecoratableComponent<infer F> ? F : never;
2
+ import type { CanReturnNullOrElement, Decoratable, DecoratableComponent, DecoratableHook, Decorator } from "./types.js";
3
+ type GetBaseFunction<T> = T extends DecoratableComponent<infer F> ? F : never;
4
4
  /**
5
5
  * Creates a component which, when mounted, registers a Higher Order Component for the given base component.
6
6
  * This is particularly useful for decorating (wrapping) existing composable components.
7
7
  * For more information, visit https://www.webiny.com/docs/admin-area/basics/framework.
8
8
  */
9
- export declare function createComponentPlugin<T extends Decoratable>(Base: T, hoc: T extends DecoratableComponent ? Decorator<CanReturnNull<GetBaseFunction<T>>> : Decorator<GetBaseFunction<T>>): {
9
+ export declare function createComponentPlugin<T extends Decoratable>(Base: T, hoc: T extends DecoratableComponent ? Decorator<CanReturnNullOrElement<GetBaseFunction<T>>> : Decorator<GetBaseFunction<T>>): {
10
10
  (): React.JSX.Element;
11
11
  displayName: string;
12
12
  };
13
- export declare type GetDecorateeParams<T> = T extends (params?: infer P1) => any ? P1 : T extends (params: infer P2) => any ? P2 : any;
14
- export declare 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<CanReturnNull<GetBaseFunction<T>>> : Decorator<GetBaseFunction<T>>): {
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
16
  (): React.JSX.Element;
17
17
  displayName: string;
18
18
  };
@@ -1,35 +1,25 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.createComponentPlugin = createComponentPlugin;
8
- exports.createDecorator = createDecorator;
9
- var _react = _interopRequireDefault(require("react"));
10
- var _Compose = require("./Compose");
1
+ import React from "react";
2
+ import { Compose } from "./Compose.js";
11
3
  /**
12
4
  * Creates a component which, when mounted, registers a Higher Order Component for the given base component.
13
5
  * This is particularly useful for decorating (wrapping) existing composable components.
14
6
  * For more information, visit https://www.webiny.com/docs/admin-area/basics/framework.
15
7
  */
16
- function createComponentPlugin(Base, hoc) {
8
+ export function createComponentPlugin(Base, hoc) {
17
9
  return createDecorator(Base, hoc);
18
10
  }
19
11
 
20
12
  // Maybe there's a better way to mark params as non-existent, but for now I left it as `any`.
21
13
  // TODO: revisit this type; not sure if `?` can be handled in one clause
22
14
 
23
- var isDecoratableComponent = function isDecoratableComponent(decoratable) {
15
+ const isDecoratableComponent = decoratable => {
24
16
  return "displayName" in decoratable;
25
17
  };
26
- function createDecorator(Base, hoc) {
27
- var DecoratorPlugin = function DecoratorPlugin() {
28
- return /*#__PURE__*/_react.default.createElement(_Compose.Compose, {
29
- component: Base,
30
- with: hoc
31
- });
32
- };
18
+ export function createDecorator(Base, hoc) {
19
+ const DecoratorPlugin = () => /*#__PURE__*/React.createElement(Compose, {
20
+ component: Base,
21
+ with: hoc
22
+ });
33
23
  if (isDecoratableComponent(Base)) {
34
24
  DecoratorPlugin.displayName = Base.displayName;
35
25
  }