@webiny/react-composition 0.0.0-unstable.e53eceafb5 → 0.0.0-unstable.e6f0dc8ca7

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 type { DecoratableTypes } from "./Context";
2
- import type { 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,27 +1,83 @@
1
- import { useEffect } from "react";
2
- import { useComposition } from "./Context";
3
- import { useCompositionScope } from "./CompositionScope";
1
+ import React, { useEffect, useRef } from "react";
2
+ import { useCompositionStore } from "./Context.js";
3
+ import { useCompositionScope } from "./CompositionScope.js";
4
4
  export const Compose = props => {
5
- const {
6
- composeComponent
7
- } = useComposition();
5
+ const store = useCompositionStore();
8
6
  const {
9
7
  scope,
10
8
  inherit
11
9
  } = useCompositionScope();
12
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] ?? "*";
21
+
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
+ inherit: inherit
32
+ });
33
+ };
34
+
35
+ /**
36
+ * Separate component for the effect to avoid re-running the cleanup on every render.
37
+ * This component handles cleanup on unmount and when props change.
38
+ */
39
+ function ComposeEffects({
40
+ store,
41
+ target,
42
+ decorators,
43
+ scope,
44
+ inherit
45
+ }) {
46
+ const prevRef = useRef(null);
47
+
48
+ // Tracks the decorators currently live in the store as of the last render.
49
+ // Updated synchronously during render so it always reflects the most recently
50
+ // registered decorators, allowing the atomic swap below to remove the right ones.
51
+ const liveRef = useRef(decorators);
52
+
53
+ // On re-render with new decorators: atomically replace the old ones in the store
54
+ // during render (before React commits). This ensures the store never transiently
55
+ // holds both old and new HOCs — which would cause useSyncExternalStore subscribers
56
+ // to render with a doubly-wrapped component and mount inner components twice.
57
+ if (liveRef.current !== decorators) {
58
+ store.register(target, decorators, scope, inherit, true, liveRef.current);
59
+ liveRef.current = decorators;
60
+ }
13
61
  useEffect(() => {
14
- if (!targetFn) {
15
- console.warn("You must provide a function or a component to compose with!", props);
16
- }
17
- if (typeof targetFn.original === "undefined") {
18
- console.warn(`You must make your function "${targetFn.originalName ?? targetFn.name}" composable, by using the makeDecoratable() function!`);
19
- return;
62
+ const prev = prevRef.current;
63
+
64
+ // On prop change: the render-phase atomic swap already updated the store.
65
+ // Emit a non-silent notification now that effects have settled so subscribers
66
+ // re-render with the final, clean composition (old HOCs fully gone).
67
+ if (prev && (prev.decorators !== decorators || prev.scope !== scope)) {
68
+ store.notify();
20
69
  }
21
- const decorators = Array.isArray(props.with) ? props.with : [props.with];
22
- return composeComponent(targetFn.original, decorators, scope[scope.length - 1], inherit);
23
- }, [props.with]);
70
+ prevRef.current = {
71
+ decorators,
72
+ scope
73
+ };
74
+
75
+ // Cleanup on unmount.
76
+ return () => {
77
+ store.unregister(target, decorators, scope);
78
+ };
79
+ }, [store, target, decorators, scope]);
24
80
  return null;
25
- };
81
+ }
26
82
 
27
83
  //# sourceMappingURL=Compose.js.map
package/Compose.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["useEffect","useComposition","useCompositionScope","Compose","props","composeComponent","scope","inherit","targetFn","function","component","console","warn","original","originalName","name","decorators","Array","isArray","with","length"],"sources":["Compose.tsx"],"sourcesContent":["import { useEffect } from \"react\";\nimport type { DecoratableTypes } from \"./Context\";\nimport { useComposition } from \"./Context\";\nimport { useCompositionScope } from \"~/CompositionScope\";\nimport type { 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, inherit } = useCompositionScope();\n\n const targetFn = (props.function ?? props.component) as Decoratable;\n\n useEffect(() => {\n if (!targetFn) {\n console.warn(\"You must provide a function or a component to compose with!\", props);\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\n return;\n }\n\n const decorators = Array.isArray(props.with) ? props.with : [props.with];\n return composeComponent(\n targetFn.original,\n decorators as Enumerable<ComposeWith>,\n scope[scope.length - 1],\n inherit\n );\n }, [props.with]);\n\n return null;\n};\n"],"mappings":"AAAA,SAASA,SAAS,QAAQ,OAAO;AAEjC,SAASC,cAAc;AACvB,SAASC,mBAAmB;AAS5B,OAAO,MAAMC,OAAO,GAAIC,KAAmB,IAAK;EAC5C,MAAM;IAAEC;EAAiB,CAAC,GAAGJ,cAAc,CAAC,CAAC;EAC7C,MAAM;IAAEK,KAAK;IAAEC;EAAQ,CAAC,GAAGL,mBAAmB,CAAC,CAAC;EAEhD,MAAMM,QAAQ,GAAIJ,KAAK,CAACK,QAAQ,IAAIL,KAAK,CAACM,SAAyB;EAEnEV,SAAS,CAAC,MAAM;IACZ,IAAI,CAACQ,QAAQ,EAAE;MACXG,OAAO,CAACC,IAAI,CAAC,6DAA6D,EAAER,KAAK,CAAC;IACtF;IACA,IAAI,OAAOI,QAAQ,CAACK,QAAQ,KAAK,WAAW,EAAE;MAC1CF,OAAO,CAACC,IAAI,CACR,gCACIJ,QAAQ,CAACM,YAAY,IAAIN,QAAQ,CAACO,IAAI,wDAE9C,CAAC;MAED;IACJ;IAEA,MAAMC,UAAU,GAAGC,KAAK,CAACC,OAAO,CAACd,KAAK,CAACe,IAAI,CAAC,GAAGf,KAAK,CAACe,IAAI,GAAG,CAACf,KAAK,CAACe,IAAI,CAAC;IACxE,OAAOd,gBAAgB,CACnBG,QAAQ,CAACK,QAAQ,EACjBG,UAAU,EACVV,KAAK,CAACA,KAAK,CAACc,MAAM,GAAG,CAAC,CAAC,EACvBb,OACJ,CAAC;EACL,CAAC,EAAE,CAACH,KAAK,CAACe,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","liveRef","current","prev","notify","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 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\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AED;AACA;AACA;AACA;AACA,SAASiB,cAAcA,CAAC;EACpBnB,KAAK;EACLoB,MAAM;EACNT,UAAU;EACVV,KAAK;EACLC;AAOJ,CAAC,EAAE;EACC,MAAMmB,OAAO,GAAG1B,MAAM,CAGZ,IAAI,CAAC;;EAEf;EACA;EACA;EACA,MAAM2B,OAAO,GAAG3B,MAAM,CAA8CgB,UAAU,CAAC;;EAE/E;EACA;EACA;EACA;EACA,IAAIW,OAAO,CAACC,OAAO,KAAKZ,UAAU,EAAE;IAChCX,KAAK,CAACiB,QAAQ,CAACG,MAAM,EAAET,UAAU,EAAEV,KAAK,EAAEC,OAAO,EAAE,IAAI,EAAEoB,OAAO,CAACC,OAAO,CAAC;IACzED,OAAO,CAACC,OAAO,GAAGZ,UAAU;EAChC;EAEAjB,SAAS,CAAC,MAAM;IACZ,MAAM8B,IAAI,GAAGH,OAAO,CAACE,OAAO;;IAE5B;IACA;IACA;IACA,IAAIC,IAAI,KAAKA,IAAI,CAACb,UAAU,KAAKA,UAAU,IAAIa,IAAI,CAACvB,KAAK,KAAKA,KAAK,CAAC,EAAE;MAClED,KAAK,CAACyB,MAAM,CAAC,CAAC;IAClB;IAEAJ,OAAO,CAACE,OAAO,GAAG;MAAEZ,UAAU;MAAEV;IAAM,CAAC;;IAEvC;IACA,OAAO,MAAM;MACTD,KAAK,CAAC0B,UAAU,CAACN,MAAM,EAAET,UAAU,EAAEV,KAAK,CAAC;IAC/C,CAAC;EACL,CAAC,EAAE,CAACD,KAAK,EAAEoB,MAAM,EAAET,UAAU,EAAEV,KAAK,CAAC,CAAC;EAEtC,OAAO,IAAI;AACf","ignoreList":[]}
package/Context.d.ts CHANGED
@@ -1,39 +1,15 @@
1
1
  import type { ComponentType } from "react";
2
2
  import React from "react";
3
- import type { ComposedFunction, ComposeWith, Decoratable, DecoratableComponent, DecoratableHook, Decorator, Enumerable, GenericComponent, GenericHook } from "./types";
3
+ import { CompositionStore } from "./domain/CompositionStore.js";
4
+ import type { ComposeWith, Decoratable, DecoratableComponent, DecoratableHook, Decorator, Enumerable, GenericComponent, GenericHook } from "./types.js";
4
5
  export declare function compose<T>(...fns: Decorator<T>[]): (decoratee: T) => T;
5
- interface ComposedComponent {
6
- /**
7
- * Ready to use React component.
8
- */
9
- component: GenericHook | GenericComponent;
10
- /**
11
- * HOCs used to compose the original component.
12
- */
13
- hocs: Decorator<GenericComponent | GenericHook>[];
14
- /**
15
- * Component composition can be scoped.
16
- */
17
- scope?: string;
18
- }
19
6
  /**
20
7
  * @deprecated Use `Decorator` instead.
21
8
  */
22
9
  export interface HigherOrderComponent<TProps = any, TOutput = TProps> {
23
10
  (Component: GenericComponent<TProps>): GenericComponent<TOutput>;
24
11
  }
25
- type ComposedComponents = Map<ComponentType<unknown>, ComposedComponent>;
26
- type ComponentScopes = Map<string, ComposedComponents>;
27
12
  export type DecoratableTypes = DecoratableComponent | DecoratableHook;
28
- interface CompositionContextGetComponentCallable {
29
- (component: ComponentType<unknown>, scope: string[]): ComposedFunction | GenericComponent | undefined;
30
- }
31
- interface CompositionContext {
32
- components: ComponentScopes;
33
- getComponent: CompositionContextGetComponentCallable;
34
- composeComponent(component: ComponentType<unknown>, hocs: Enumerable<ComposeWith>, scope?: string, inherit?: boolean): void;
35
- }
36
- declare const CompositionContext: React.Context<CompositionContext | undefined>;
37
13
  export type DecoratorsTuple = [Decoratable, Decorator<any>[]];
38
14
  export type DecoratorsCollection = Array<DecoratorsTuple>;
39
15
  interface CompositionProviderProps {
@@ -41,13 +17,19 @@ interface CompositionProviderProps {
41
17
  children: React.ReactNode;
42
18
  }
43
19
  export declare const CompositionProvider: ({ decorators, children }: CompositionProviderProps) => React.JSX.Element;
20
+ export declare function useCompositionStore(): CompositionStore;
21
+ export declare function useOptionalCompositionStore(): CompositionStore | undefined;
44
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
+ }
45
27
  /**
46
28
  * This hook will throw an error if composition context doesn't exist.
47
29
  */
48
- export declare function useComposition(): CompositionContext;
30
+ export declare function useComposition(): CompositionContextValue;
49
31
  /**
50
32
  * This hook will not throw an error if composition context doesn't exist.
51
33
  */
52
- export declare function useOptionalComposition(): CompositionContext | undefined;
34
+ export declare function useOptionalComposition(): CompositionContextValue | undefined;
53
35
  export {};
package/Context.js CHANGED
@@ -1,5 +1,6 @@
1
- import React, { createContext, useCallback, useContext, useMemo, useState } from "react";
2
- import { useCompositionScope } from "./CompositionScope";
1
+ import React, { createContext, useContext, useRef, useSyncExternalStore } from "react";
2
+ import { useCompositionScope } from "./CompositionScope.js";
3
+ import { CompositionStore } from "./domain/CompositionStore.js";
3
4
  export function compose(...fns) {
4
5
  return decoratee => {
5
6
  return fns.reduceRight((decoratee, decorator) => decorator(decoratee), decoratee);
@@ -10,111 +11,82 @@ export function compose(...fns) {
10
11
  * @deprecated Use `Decorator` instead.
11
12
  */
12
13
 
13
- const CompositionContext = /*#__PURE__*/createContext(undefined);
14
- const composeComponents = (components, decorators, scope = "*", inherit = false) => {
15
- const scopeMap = components.get(scope) || new Map();
16
- for (const [component, newHocs] of decorators) {
17
- const recipe = scopeMap.get(component) || {
18
- component: null,
19
- hocs: []
20
- };
21
- const existingHocs = [...(recipe.hocs || [])];
22
- if (inherit && scope !== "*") {
23
- const globalScope = components.get("*") || new Map();
24
- const globalRecipe = globalScope.get(component) || {
25
- component: null,
26
- hocs: []
27
- };
28
- existingHocs.unshift(...globalRecipe.hocs);
29
- }
30
- const finalHocs = [...existingHocs, ...newHocs];
31
- scopeMap.set(component, {
32
- component: compose(...[...finalHocs].reverse())(component),
33
- hocs: finalHocs
34
- });
35
- components.set(scope, scopeMap);
36
- }
37
- return components;
38
- };
14
+ const CompositionStoreContext = /*#__PURE__*/createContext(undefined);
39
15
  export const CompositionProvider = ({
40
16
  decorators = [],
41
17
  children
42
18
  }) => {
43
- const [components, setComponents] = useState(() => {
44
- return composeComponents(new Map(), decorators.map(tuple => {
45
- return [tuple[0].original, tuple[1]];
46
- }));
47
- });
48
- const composeComponent = useCallback((component, hocs, scope = "*", inherit = false) => {
49
- setComponents(prevComponents => {
50
- return composeComponents(new Map(prevComponents), [[component, hocs]], scope, inherit);
51
- });
52
-
53
- // Return a function that will remove the added HOCs.
54
- return () => {
55
- setComponents(prevComponents => {
56
- const components = new Map(prevComponents);
57
- const scopeMap = components.get(scope) || new Map();
58
- const recipe = scopeMap.get(component) || {
59
- component: null,
60
- hocs: []
61
- };
62
- const newHOCs = [...recipe.hocs].filter(hoc => !hocs.includes(hoc));
63
- const NewComponent = compose(...[...newHOCs].reverse())(component);
64
- scopeMap.set(component, {
65
- component: NewComponent,
66
- hocs: newHOCs
67
- });
68
- components.set(scope, scopeMap);
69
- return components;
70
- });
71
- };
72
- }, [setComponents]);
73
- const getComponent = useCallback((Component, scope = []) => {
74
- const scopesToResolve = ["*", ...scope].reverse();
75
- for (const scope of scopesToResolve) {
76
- const scopeMap = components.get(scope) || new Map();
77
- const composedComponent = scopeMap.get(Component);
78
- if (composedComponent) {
79
- return composedComponent.component;
80
- }
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);
81
25
  }
82
- return undefined;
83
- }, [components]);
84
- const context = useMemo(() => ({
85
- getComponent,
86
- composeComponent,
87
- components
88
- }), [components, composeComponent]);
89
- return /*#__PURE__*/React.createElement(CompositionContext.Provider, {
90
- value: context
26
+ storeRef.current = store;
27
+ }
28
+ return /*#__PURE__*/React.createElement(CompositionStoreContext.Provider, {
29
+ value: storeRef.current
91
30
  }, children);
92
31
  };
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
+ }
93
42
  export function useComponent(baseFunction) {
94
- const context = useOptionalComposition();
43
+ const store = useOptionalCompositionStore();
95
44
  const scope = useCompositionScope();
96
- if (!context) {
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) {
97
49
  return baseFunction;
98
50
  }
99
- return context.getComponent(baseFunction, scope.scope) || baseFunction;
51
+ const result = store.getComponent(baseFunction, scope.scope) || baseFunction;
52
+ return result;
100
53
  }
54
+ const noopSubscribe = () => () => {};
55
+ const noopGetSnapshot = () => 0;
56
+
57
+ // Legacy compatibility — kept for any external consumers.
101
58
 
102
59
  /**
103
60
  * This hook will throw an error if composition context doesn't exist.
104
61
  */
105
62
  export function useComposition() {
106
- const context = useContext(CompositionContext);
107
- if (!context) {
108
- throw new Error(`You're missing a <CompositionProvider> higher up in your component hierarchy!`);
109
- }
110
- return context;
63
+ const store = useCompositionStore();
64
+ return {
65
+ composeComponent: (component, hocs, scope = "*", inherit = false) => {
66
+ return store.register(component, hocs, scope, inherit);
67
+ },
68
+ getComponent: (component, scope) => {
69
+ return store.getComponent(component, scope);
70
+ }
71
+ };
111
72
  }
112
73
 
113
74
  /**
114
75
  * This hook will not throw an error if composition context doesn't exist.
115
76
  */
116
77
  export function useOptionalComposition() {
117
- return useContext(CompositionContext);
78
+ const store = useOptionalCompositionStore();
79
+ if (!store) {
80
+ return undefined;
81
+ }
82
+ return {
83
+ composeComponent: (component, hocs, scope = "*", inherit = false) => {
84
+ return store.register(component, hocs, scope, inherit);
85
+ },
86
+ getComponent: (component, scope) => {
87
+ return store.getComponent(component, scope);
88
+ }
89
+ };
118
90
  }
119
91
 
120
92
  //# sourceMappingURL=Context.js.map
package/Context.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["React","createContext","useCallback","useContext","useMemo","useState","useCompositionScope","compose","fns","decoratee","reduceRight","decorator","CompositionContext","undefined","composeComponents","components","decorators","scope","inherit","scopeMap","get","Map","component","newHocs","recipe","hocs","existingHocs","globalScope","globalRecipe","unshift","finalHocs","set","reverse","CompositionProvider","children","setComponents","map","tuple","original","composeComponent","prevComponents","newHOCs","filter","hoc","includes","NewComponent","getComponent","Component","scopesToResolve","composedComponent","context","createElement","Provider","value","useComponent","baseFunction","useOptionalComposition","useComposition","Error"],"sources":["Context.tsx"],"sourcesContent":["import type { ComponentType } from \"react\";\nimport React, { createContext, useCallback, useContext, useMemo, useState } from \"react\";\nimport { useCompositionScope } from \"~/CompositionScope\";\nimport type {\n ComposedFunction,\n ComposeWith,\n Decoratable,\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) as T;\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 inherit?: boolean\n ): void;\n}\n\nconst CompositionContext = createContext<CompositionContext | 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\nconst composeComponents = (\n components: ComponentScopes,\n decorators: Array<[GenericComponent | GenericHook, Decorator<any>[]]>,\n scope = \"*\",\n inherit = false\n) => {\n const scopeMap: ComposedComponents = components.get(scope) || new Map();\n for (const [component, newHocs] of decorators) {\n const recipe = scopeMap.get(component) || { component: null, hocs: [] };\n\n const existingHocs = [...(recipe.hocs || [])];\n if (inherit && scope !== \"*\") {\n const globalScope = components.get(\"*\") || new Map();\n const globalRecipe = globalScope.get(component) || { component: null, hocs: [] };\n existingHocs.unshift(...globalRecipe.hocs);\n }\n\n const finalHocs = [...existingHocs, ...newHocs] as Decorator<\n GenericHook | GenericComponent\n >[];\n\n scopeMap.set(component, {\n component: compose(...[...finalHocs].reverse())(component),\n hocs: finalHocs\n });\n\n components.set(scope, scopeMap);\n }\n\n return components;\n};\n\nexport const CompositionProvider = ({ decorators = [], children }: CompositionProviderProps) => {\n const [components, setComponents] = useState<ComponentScopes>(() => {\n return composeComponents(\n new Map(),\n decorators.map(tuple => {\n return [tuple[0].original, tuple[1]];\n })\n );\n });\n\n const composeComponent = useCallback(\n (\n component: GenericComponent | GenericHook,\n hocs: HigherOrderComponent<any, any>[],\n scope: string | undefined = \"*\",\n inherit = false\n ) => {\n setComponents(prevComponents => {\n return composeComponents(\n new Map(prevComponents),\n [[component, hocs]],\n scope,\n inherit\n );\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 scopesToResolve = [\"*\", ...scope].reverse();\n for (const scope of scopesToResolve) {\n const scopeMap: ComposedComponents = components.get(scope) || new Map();\n const composedComponent = scopeMap.get(Component);\n if (composedComponent) {\n return composedComponent.component;\n }\n }\n\n return 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.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":"AACA,OAAOA,KAAK,IAAIC,aAAa,EAAEC,WAAW,EAAEC,UAAU,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,OAAO;AACxF,SAASC,mBAAmB;AAa5B,OAAO,SAASC,OAAOA,CAAI,GAAGC,GAAmB,EAAE;EAC/C,OAAQC,SAAY,IAAQ;IACxB,OAAOD,GAAG,CAACE,WAAW,CAAC,CAACD,SAAS,EAAEE,SAAS,KAAKA,SAAS,CAACF,SAAS,CAAC,EAAEA,SAAS,CAAC;EACrF,CAAC;AACL;;AAiBA;AACA;AACA;;AA4BA,MAAMG,kBAAkB,gB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AC;EACxC,MAAMvC,KAAK,GAAGX,mBAAmB,CAAC,CAAC;EAEnC,IAAI,CAAC4C,OAAO,EAAE;IACV,OAAOK,YAAY;EACvB;EAEA,OAAQL,OAAO,CAACJ,YAAY,CAACS,YAAY,EAAStC,KAAK,CAACA,KAAK,CAAC,IAAIsC,YAAY;AAClF;;AAEA;AACA;AACA;AACA,OAAO,SAASE,cAAcA,CAAA,EAAG;EAC7B,MAAMP,OAAO,GAAG/C,UAAU,CAACS,kBAAkB,CAAC;EAC9C,IAAI,CAACsC,OAAO,EAAE;IACV,MAAM,IAAIQ,KAAK,CACX,+EACJ,CAAC;EACL;EAEA,OAAOR,OAAO;AAClB;;AAEA;AACA;AACA;AACA,OAAO,SAASM,sBAAsBA,CAAA,EAAG;EACrC,OAAOrD,UAAU,CAACS,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","result","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\";\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"],"mappings":"AACA,OAAOA,KAAK,IAAIC,aAAa,EAAEC,UAAU,EAAEC,MAAM,EAAEC,oBAAoB,QAAQ,OAAO;AACtF,SAASC,mBAAmB;AAC5B,SAASC,gBAAgB;AAazB,OAAO,SAASC,OAAOA,CAAI,GAAGC,GAAmB,EAAE;EAC/C,OAAQC,SAAY,IAAQ;IACxB,OAAOD,GAAG,CAACE,WAAW,CAAC,CAACD,SAAS,EAAEE,SAAS,KAAKA,SAAS,CAACF,SAAS,CAAC,EAAEA,SAAS,CAAC;EACrF,CAAC;AACL;;AAEA;AACA;AACA;;AAOA,MAAMG,uBAAuB,gBAAGX,aAAa,CAA+BY,SAAS,CAAC;AAUtF,OAAO,MAAMC,mBAAmB,GAAGA,CAAC;EAAEC,UAAU,GAAG,EAAE;EAAEC;AAAmC,CAAC,KAAK;EAC5F,MAAMC,QAAQ,GAAGd,MAAM,CAA0B,IAAI,CAAC;EACtD,IAAIc,QAAQ,CAACC,OAAO,KAAK,IAAI,EAAE;IAC3B,MAAMC,KAAK,GAAG,IAAIb,gBAAgB,CAAC,CAAC;IACpC;IACA,KAAK,MAAM,CAACc,WAAW,EAAEC,IAAI,CAAC,IAAIN,UAAU,EAAE;MAC1CI,KAAK,CAACG,QAAQ,CAACF,WAAW,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IAAI,EAAEW,KAAK,GAAG,GAAG,EAAEU,OAAO,GAAG,KAAK,KAAK;MACjE,OAAOvB,KAAK,CAACG,QAAQ,CAACmB,SAAS,EAAEpB,IAAI,EAAWW,KAAK,EAAEU,OAAO,CAAC;IACnE,CAAC;IACDJ,YAAY,EAAEA,CAACG,SAAS,EAAET,KAAK,KAAK;MAChC,OAAOb,KAAK,CAACmB,YAAY,CAACG,SAAS,EAAET,KAAK,CAAC;IAC/C;EACJ,CAAC;AACL;;AAEA;AACA;AACA;AACA,OAAO,SAASW,sBAAsBA,CAAA,EAAwC;EAC1E,MAAMxB,KAAK,GAAGU,2BAA2B,CAAC,CAAC;EAC3C,IAAI,CAACV,KAAK,EAAE;IACR,OAAON,SAAS;EACpB;EAEA,OAAO;IACH2B,gBAAgB,EAAEA,CAACC,SAAS,EAAEpB,IAAI,EAAEW,KAAK,GAAG,GAAG,EAAEU,OAAO,GAAG,KAAK,KAAK;MACjE,OAAOvB,KAAK,CAACG,QAAQ,CAACmB,SAAS,EAAEpB,IAAI,EAAWW,KAAK,EAAEU,OAAO,CAAC;IACnE,CAAC;IACDJ,YAAY,EAAEA,CAACG,SAAS,EAAET,KAAK,KAAK;MAChC,OAAOb,KAAK,CAACmB,YAAY,CAACG,SAAS,EAAET,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,5 +1,5 @@
1
1
  import React from "react";
2
- import type { CanReturnNullOrElement, Decoratable, DecoratableComponent, DecoratableHook, Decorator } from "./types";
2
+ import type { CanReturnNullOrElement, Decoratable, DecoratableComponent, DecoratableHook, Decorator } from "./types.js";
3
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.
@@ -1,5 +1,5 @@
1
1
  import React from "react";
2
- import { Compose } from "./Compose";
2
+ import { Compose } from "./Compose.js";
3
3
  /**
4
4
  * Creates a component which, when mounted, registers a Higher Order Component for the given base component.
5
5
  * This is particularly useful for decorating (wrapping) existing composable components.
@@ -1 +1 @@
1
- {"version":3,"names":["React","Compose","createComponentPlugin","Base","hoc","createDecorator","isDecoratableComponent","decoratable","DecoratorPlugin","createElement","component","with","displayName"],"sources":["createDecorator.tsx"],"sourcesContent":["import React from \"react\";\nimport type {\n CanReturnNullOrElement,\n Decoratable,\n DecoratableComponent,\n DecoratableHook,\n Decorator\n} from \"~/types\";\nimport { Compose } from \"~/Compose\";\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> = T extends DecoratableHook<infer F>\n ? F\n : T extends DecoratableComponent<infer F>\n ? F\n : 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"],"mappings":"AAAA,OAAOA,KAAK,MAAM,OAAO;AAQzB,SAASC,OAAO;AAIhB;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,qBAAqBA,CACjCC,IAAO,EACPC,GAEmC,EACrC;EACE,OAAOC,eAAe,CAACF,IAAI,EAAEC,GAAG,CAAC;AACrC;;AAEA;AACA;;AAaA,MAAME,sBAAsB,GACxBC,WAAmD,IACb;EACtC,OAAO,aAAa,IAAIA,WAAW;AACvC,CAAC;AAED,OAAO,SAASF,eAAeA,CAC3BF,IAAO,EACPC,GAEmC,EACrC;EACE,MAAMI,eAAe,GAAGA,CAAA,kBAAMR,KAAA,CAAAS,aAAA,CAACR,OAAO;IAACS,SAAS,EAAEP,IAAK;IAACQ,IAAI,EAAEP;EAAW,CAAE,CAAC;EAC5E,IAAIE,sBAAsB,CAACH,IAAI,CAAC,EAAE;IAC9BK,eAAe,CAACI,WAAW,GAAGT,IAAI,CAACS,WAAW;EAClD;EACA,OAAOJ,eAAe;AAC1B","ignoreList":[]}
1
+ {"version":3,"names":["React","Compose","createComponentPlugin","Base","hoc","createDecorator","isDecoratableComponent","decoratable","DecoratorPlugin","createElement","component","with","displayName"],"sources":["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"],"mappings":"AAAA,OAAOA,KAAK,MAAM,OAAO;AAQzB,SAASC,OAAO;AAIhB;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,qBAAqBA,CACjCC,IAAO,EACPC,GAEmC,EACrC;EACE,OAAOC,eAAe,CAACF,IAAI,EAAEC,GAAG,CAAC;AACrC;;AAEA;AACA;;AAUA,MAAME,sBAAsB,GACxBC,WAAmD,IACb;EACtC,OAAO,aAAa,IAAIA,WAAW;AACvC,CAAC;AAED,OAAO,SAASF,eAAeA,CAC3BF,IAAO,EACPC,GAEmC,EACrC;EACE,MAAMI,eAAe,GAAGA,CAAA,kBAAMR,KAAA,CAAAS,aAAA,CAACR,OAAO;IAACS,SAAS,EAAEP,IAAK;IAACQ,IAAI,EAAEP;EAAW,CAAE,CAAC;EAC5E,IAAIE,sBAAsB,CAACH,IAAI,CAAC,EAAE;IAC9BK,eAAe,CAACI,WAAW,GAAGT,IAAI,CAACS,WAAW;EAClD;EACA,OAAOJ,eAAe;AAC1B","ignoreList":[]}
package/decorators.d.ts CHANGED
@@ -1,18 +1,15 @@
1
1
  import React from "react";
2
- import type { GetDecoratee, GetDecorateeParams } from "./createDecorator";
3
- import type { DecoratableComponent, GenericComponent, Decorator, GenericHook, DecoratableHook, ComponentDecorator } from "./types";
2
+ import type { GetDecoratee, GetDecorateeParams } from "./createDecorator.js";
3
+ import type { DecoratableComponent, GenericComponent, Decorator, GenericHook, DecoratableHook, ComponentDecorator } from "./types.js";
4
4
  export interface ShouldDecorate<TDecorator = any, TComponent = any> {
5
5
  (decoratorProps: TDecorator, componentProps: TComponent): boolean;
6
6
  }
7
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>>> | undefined) => (decorator: ComponentDecorator<GetDecoratee<TDecoratable>>) => (props: TDecorator) => React.JSX.Element;
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
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>>> | undefined) => TDecoratable & {
10
+ export declare function withDecoratorFactory<TDecorator>(): <TDecoratable extends DecoratableComponent>(Component: TDecoratable, shouldDecorate?: ShouldDecorate<TDecorator, GetDecorateeParams<GetDecoratee<TDecoratable>>>) => TDecoratable & {
11
11
  createDecorator: (decorator: ComponentDecorator<GetDecoratee<TDecoratable>>) => (props: TDecorator) => React.JSX.Element;
12
12
  };
13
- export declare function withHookDecoratorFactory(): <TDecoratable extends DecoratableHook>(hook: TDecoratable) => GenericHook<GetDecorateeParams<GetDecoratee<TDecoratable>>, ReturnType<GetDecoratee<TDecoratable>>> & {
14
- original: GenericHook<GetDecorateeParams<GetDecoratee<TDecoratable>>, ReturnType<GetDecoratee<TDecoratable>>>;
15
- originalName: string;
16
- } & {
13
+ export declare function withHookDecoratorFactory(): <TDecoratable extends DecoratableHook>(hook: TDecoratable) => DecoratableHook<GenericHook<GetDecorateeParams<GetDecoratee<TDecoratable>>, ReturnType<GetDecoratee<TDecoratable>>>> & {
17
14
  createDecorator: (decorator: Decorator<GetDecoratee<TDecoratable>>) => () => React.JSX.Element;
18
15
  };
package/decorators.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import React from "react";
2
- import { Compose } from "./Compose";
2
+ import { Compose } from "./Compose.js";
3
3
  export function createConditionalDecorator(shouldDecorate, decorator, decoratorProps) {
4
4
  return Original => {
5
5
  const DecoratedComponent = /*#__PURE__*/React.memo(decorator(Original));
package/decorators.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["React","Compose","createConditionalDecorator","shouldDecorate","decorator","decoratorProps","Original","DecoratedComponent","memo","displayName","ShouldDecorate","props","createElement","memoizedComponent","decoratee","createDecoratorFactory","from","decoratable","createDecorator","DecoratorPlugin","componentDecorator","function","with","createHookDecoratorFactory","withDecoratorFactory","WithDecorator","Component","Object","assign","withHookDecoratorFactory","WithHookDecorator","hook"],"sources":["decorators.tsx"],"sourcesContent":["import React from \"react\";\nimport { Compose } from \"~/Compose\";\nimport type { GetDecoratee, GetDecorateeParams } from \"~/createDecorator\";\nimport type {\n DecoratableComponent,\n GenericComponent,\n Decorator,\n GenericHook,\n DecoratableHook,\n ComponentDecorator\n} from \"~/types\";\n\nexport interface ShouldDecorate<TDecorator = any, TComponent = any> {\n (decoratorProps: TDecorator, componentProps: TComponent): boolean;\n}\n\nexport function createConditionalDecorator<TDecoratee extends GenericComponent>(\n shouldDecorate: ShouldDecorate,\n decorator: Decorator<TDecoratee>,\n decoratorProps: unknown\n): Decorator<TDecoratee> {\n return (Original => {\n const DecoratedComponent = React.memo(decorator(Original));\n DecoratedComponent.displayName = Original.displayName;\n\n return function ShouldDecorate(props: unknown) {\n if (shouldDecorate(decoratorProps, props)) {\n // @ts-expect-error\n return <DecoratedComponent {...props} />;\n }\n\n // @ts-expect-error\n return <Original {...props} />;\n };\n }) as Decorator<TDecoratee>;\n}\n\nconst memoizedComponent = <T extends GenericComponent>(decorator: Decorator<T>) => {\n return (decoratee: T) => {\n return React.memo(decorator(decoratee));\n };\n};\n\nexport function createDecoratorFactory<TDecorator>() {\n return function from<TDecoratable extends DecoratableComponent>(\n decoratable: TDecoratable,\n shouldDecorate?: ShouldDecorate<TDecorator, GetDecorateeParams<GetDecoratee<TDecoratable>>>\n ) {\n return function createDecorator(decorator: ComponentDecorator<GetDecoratee<TDecoratable>>) {\n return function DecoratorPlugin(props: TDecorator) {\n if (shouldDecorate) {\n const componentDecorator = createConditionalDecorator<GenericComponent>(\n shouldDecorate,\n decorator as unknown as Decorator<GenericComponent>,\n props\n );\n\n return <Compose function={decoratable} with={componentDecorator} />;\n }\n\n return (\n <Compose\n function={decoratable}\n with={memoizedComponent(\n decorator as unknown as Decorator<GenericComponent>\n )}\n />\n );\n };\n };\n };\n}\n\nexport function createHookDecoratorFactory() {\n return function from<TDecoratable extends DecoratableHook>(decoratable: TDecoratable) {\n return function createDecorator(decorator: Decorator<GetDecoratee<TDecoratable>>) {\n return function DecoratorPlugin() {\n return (\n <Compose\n function={decoratable}\n with={decorator as unknown as Decorator<GenericHook>}\n />\n );\n };\n };\n };\n}\n\nexport function withDecoratorFactory<TDecorator>() {\n return function WithDecorator<TDecoratable extends DecoratableComponent>(\n Component: TDecoratable,\n shouldDecorate?: ShouldDecorate<TDecorator, GetDecorateeParams<GetDecoratee<TDecoratable>>>\n ) {\n const createDecorator = createDecoratorFactory<TDecorator>()(Component, shouldDecorate);\n\n return Object.assign(Component, { createDecorator }) as TDecoratable & {\n createDecorator: typeof createDecorator;\n };\n };\n}\n\nexport function withHookDecoratorFactory() {\n return function WithHookDecorator<TDecoratable extends DecoratableHook>(hook: TDecoratable) {\n const createDecorator = createHookDecoratorFactory()(hook);\n\n return Object.assign(hook, { createDecorator }) as unknown as DecoratableHook<\n GenericHook<\n GetDecorateeParams<GetDecoratee<TDecoratable>>,\n ReturnType<GetDecoratee<TDecoratable>>\n >\n > & { createDecorator: typeof createDecorator };\n };\n}\n"],"mappings":"AAAA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,OAAO;AAehB,OAAO,SAASC,0BAA0BA,CACtCC,cAA8B,EAC9BC,SAAgC,EAChCC,cAAuB,EACF;EACrB,OAAQC,QAAQ,IAAI;IAChB,MAAMC,kBAAkB,gBAAGP,KAAK,CAACQ,IAAI,CAACJ,SAAS,CAACE,QAAQ,CAAC,CAAC;IAC1DC,kBAAkB,CAACE,WAAW,GAAGH,QAAQ,CAACG,WAAW;IAErD,OAAO,SAASC,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ACJoB,QAAQ,EAAEJ,WAAY;UACtBK,IAAI,EAAElB;QAA+C,CACxD,CAAC;MAEV,CAAC;IACL,CAAC;EACL,CAAC;AACL;AAEA,OAAO,SAASoB,oBAAoBA,CAAA,EAAe;EAC/C,OAAO,SAASC,aAAaA,CACzBC,SAAuB,EACvBvB,cAA2F,EAC7F;IACE,MAAMe,eAAe,GAAGH,sBAAsB,CAAa,CAAC,CAACW,SAAS,EAAEvB,cAAc,CAAC;IAEvF,OAAOwB,MAAM,CAACC,MAAM,CAACF,SAAS,EAAE;MAAER;IAAgB,CAAC,CAAC;EAGxD,CAAC;AACL;AAEA,OAAO,SAASW,wBAAwBA,CAAA,EAAG;EACvC,OAAO,SAASC,iBAAiBA,CAAuCC,IAAkB,EAAE;IACxF,MAAMb,eAAe,GAAGK,0BAA0B,CAAC,CAAC,CAACQ,IAAI,CAAC;IAE1D,OAAOJ,MAAM,CAACC,MAAM,CAACG,IAAI,EAAE;MAAEb;IAAgB,CAAC,CAAC;EAMnD,CAAC;AACL","ignoreList":[]}
1
+ {"version":3,"names":["React","Compose","createConditionalDecorator","shouldDecorate","decorator","decoratorProps","Original","DecoratedComponent","memo","displayName","ShouldDecorate","props","createElement","memoizedComponent","decoratee","createDecoratorFactory","from","decoratable","createDecorator","DecoratorPlugin","componentDecorator","function","with","createHookDecoratorFactory","withDecoratorFactory","WithDecorator","Component","Object","assign","withHookDecoratorFactory","WithHookDecorator","hook"],"sources":["decorators.tsx"],"sourcesContent":["import React from \"react\";\nimport { Compose } from \"~/Compose.js\";\nimport type { GetDecoratee, GetDecorateeParams } from \"~/createDecorator.js\";\nimport type {\n DecoratableComponent,\n GenericComponent,\n Decorator,\n GenericHook,\n DecoratableHook,\n ComponentDecorator\n} from \"~/types.js\";\n\nexport interface ShouldDecorate<TDecorator = any, TComponent = any> {\n (decoratorProps: TDecorator, componentProps: TComponent): boolean;\n}\n\nexport function createConditionalDecorator<TDecoratee extends GenericComponent>(\n shouldDecorate: ShouldDecorate,\n decorator: Decorator<TDecoratee>,\n decoratorProps: unknown\n): Decorator<TDecoratee> {\n return (Original => {\n const DecoratedComponent = React.memo(decorator(Original));\n DecoratedComponent.displayName = Original.displayName;\n\n return function ShouldDecorate(props: unknown) {\n if (shouldDecorate(decoratorProps, props)) {\n // @ts-expect-error\n return <DecoratedComponent {...props} />;\n }\n\n // @ts-expect-error\n return <Original {...props} />;\n };\n }) as Decorator<TDecoratee>;\n}\n\nconst memoizedComponent = <T extends GenericComponent>(decorator: Decorator<T>) => {\n return (decoratee: T) => {\n return React.memo(decorator(decoratee));\n };\n};\n\nexport function createDecoratorFactory<TDecorator>() {\n return function from<TDecoratable extends DecoratableComponent>(\n decoratable: TDecoratable,\n shouldDecorate?: ShouldDecorate<TDecorator, GetDecorateeParams<GetDecoratee<TDecoratable>>>\n ) {\n return function createDecorator(decorator: ComponentDecorator<GetDecoratee<TDecoratable>>) {\n return function DecoratorPlugin(props: TDecorator) {\n if (shouldDecorate) {\n const componentDecorator = createConditionalDecorator<GenericComponent>(\n shouldDecorate,\n decorator as unknown as Decorator<GenericComponent>,\n props\n );\n\n return <Compose function={decoratable} with={componentDecorator} />;\n }\n\n return (\n <Compose\n function={decoratable}\n with={memoizedComponent(\n decorator as unknown as Decorator<GenericComponent>\n )}\n />\n );\n };\n };\n };\n}\n\nexport function createHookDecoratorFactory() {\n return function from<TDecoratable extends DecoratableHook>(decoratable: TDecoratable) {\n return function createDecorator(decorator: Decorator<GetDecoratee<TDecoratable>>) {\n return function DecoratorPlugin() {\n return (\n <Compose\n function={decoratable}\n with={decorator as unknown as Decorator<GenericHook>}\n />\n );\n };\n };\n };\n}\n\nexport function withDecoratorFactory<TDecorator>() {\n return function WithDecorator<TDecoratable extends DecoratableComponent>(\n Component: TDecoratable,\n shouldDecorate?: ShouldDecorate<TDecorator, GetDecorateeParams<GetDecoratee<TDecoratable>>>\n ) {\n const createDecorator = createDecoratorFactory<TDecorator>()(Component, shouldDecorate);\n\n return Object.assign(Component, { createDecorator }) as TDecoratable & {\n createDecorator: typeof createDecorator;\n };\n };\n}\n\nexport function withHookDecoratorFactory() {\n return function WithHookDecorator<TDecoratable extends DecoratableHook>(hook: TDecoratable) {\n const createDecorator = createHookDecoratorFactory()(hook);\n\n return Object.assign(hook, { createDecorator }) as unknown as DecoratableHook<\n GenericHook<\n GetDecorateeParams<GetDecoratee<TDecoratable>>,\n ReturnType<GetDecoratee<TDecoratable>>\n >\n > & { createDecorator: typeof createDecorator };\n };\n}\n"],"mappings":"AAAA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,OAAO;AAehB,OAAO,SAASC,0BAA0BA,CACtCC,cAA8B,EAC9BC,SAAgC,EAChCC,cAAuB,EACF;EACrB,OAAQC,QAAQ,IAAI;IAChB,MAAMC,kBAAkB,gBAAGP,KAAK,CAACQ,IAAI,CAACJ,SAAS,CAACE,QAAQ,CAAC,CAAC;IAC1DC,kBAAkB,CAACE,WAAW,GAAGH,QAAQ,CAACG,WAAW;IAErD,OAAO,SAASC,cAAcA,CAACC,KAAc,EAAE;MAC3C,IAAIR,cAAc,CAACE,cAAc,EAAEM,KAAK,CAAC,EAAE;QACvC;QACA,oBAAOX,KAAA,CAAAY,aAAA,CAACL,kBAAkB,EAAKI,KAAQ,CAAC;MAC5C;;MAEA;MACA,oBAAOX,KAAA,CAAAY,aAAA,CAACN,QAAQ,EAAKK,KAAQ,CAAC;IAClC,CAAC;EACL,CAAC;AACL;AAEA,MAAME,iBAAiB,GAAgCT,SAAuB,IAAK;EAC/E,OAAQU,SAAY,IAAK;IACrB,oBAAOd,KAAK,CAACQ,IAAI,CAACJ,SAAS,CAACU,SAAS,CAAC,CAAC;EAC3C,CAAC;AACL,CAAC;AAED,OAAO,SAASC,sBAAsBA,CAAA,EAAe;EACjD,OAAO,SAASC,IAAIA,CAChBC,WAAyB,EACzBd,cAA2F,EAC7F;IACE,OAAO,SAASe,eAAeA,CAACd,SAAyD,EAAE;MACvF,OAAO,SAASe,eAAeA,CAACR,KAA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AAC,CAAC;EAMnD,CAAC;AACL","ignoreList":[]}
@@ -0,0 +1,21 @@
1
+ import type { ComponentType } from "react";
2
+ import type { Decorator, GenericComponent, GenericHook } from "../types.js";
3
+ type Listener = () => void;
4
+ export declare class CompositionStore {
5
+ private scopes;
6
+ private version;
7
+ private listeners;
8
+ register(component: ComponentType<unknown>, hocs: Decorator<GenericComponent | GenericHook>[], scope?: string, inherit?: boolean, silent?: boolean, replaces?: Decorator<GenericComponent | GenericHook>[]): () => void;
9
+ unregister(component: ComponentType<unknown>, hocs: Decorator<GenericComponent | GenericHook>[], scope?: string): void;
10
+ getComponent(component: ComponentType<unknown>, scope?: string[]): GenericComponent | GenericHook | undefined;
11
+ /**
12
+ * Bump version and notify listeners without changing store state.
13
+ * Used after a render-phase atomic swap (silent) to inform subscribers
14
+ * that the swap has settled and they should re-render with the final state.
15
+ */
16
+ notify(): void;
17
+ subscribe: (listener: Listener) => (() => void);
18
+ getSnapshot: () => number;
19
+ private notifyListeners;
20
+ }
21
+ export {};
@@ -0,0 +1,117 @@
1
+ import { compose } from "../Context.js";
2
+ export class CompositionStore {
3
+ scopes = new Map();
4
+ version = 0;
5
+ listeners = new Set();
6
+ register(component, hocs, scope = "*", inherit = false, silent = false, replaces = []) {
7
+ const scopeMap = this.scopes.get(scope) || new Map();
8
+ const recipe = scopeMap.get(component) || {
9
+ component: component,
10
+ hocs: []
11
+ };
12
+
13
+ // Idempotent: skip if all HOCs are already registered (handles StrictMode double-render).
14
+ const newHocs = hocs.filter(hoc => !recipe.hocs.includes(hoc));
15
+ if (newHocs.length === 0 && replaces.length === 0) {
16
+ return () => this.unregister(component, hocs, scope);
17
+ }
18
+
19
+ // Atomically remove the HOCs being replaced so the store never transiently
20
+ // holds both the old and new decorators at the same time. This prevents
21
+ // useSyncExternalStore subscribers from seeing a doubly-wrapped component
22
+ // in the window between a render-phase registration and its effect cleanup.
23
+ const existingHocs = replaces.length ? recipe.hocs.filter(hoc => !replaces.includes(hoc)) : [...recipe.hocs];
24
+ if (inherit && scope !== "*") {
25
+ const globalScope = this.scopes.get("*") || new Map();
26
+ const globalRecipe = globalScope.get(component) || {
27
+ component: component,
28
+ hocs: []
29
+ };
30
+ // Only prepend global HOCs that aren't already present.
31
+ const globalHocsToAdd = globalRecipe.hocs.filter(hoc => !existingHocs.includes(hoc));
32
+ existingHocs.unshift(...globalHocsToAdd);
33
+ }
34
+ const finalHocs = [...existingHocs, ...newHocs];
35
+ scopeMap.set(component, {
36
+ component: compose(...[...finalHocs].reverse())(component),
37
+ hocs: finalHocs
38
+ });
39
+ this.scopes.set(scope, scopeMap);
40
+
41
+ // Bump the version so useSyncExternalStore sees a new snapshot.
42
+ this.version++;
43
+
44
+ // When called during render (silent=true), don't notify listeners —
45
+ // that would trigger setState in other components mid-render.
46
+ // Components that render after this point will see the updated snapshot.
47
+ if (!silent) {
48
+ this.notifyListeners();
49
+ }
50
+ return () => this.unregister(component, hocs, scope);
51
+ }
52
+ unregister(component, hocs, scope = "*") {
53
+ const scopeMap = this.scopes.get(scope);
54
+ if (!scopeMap) {
55
+ return;
56
+ }
57
+ const recipe = scopeMap.get(component);
58
+ if (!recipe) {
59
+ return;
60
+ }
61
+ const newHocs = recipe.hocs.filter(hoc => !hocs.includes(hoc));
62
+ if (newHocs.length === recipe.hocs.length) {
63
+ // Nothing was removed.
64
+ return;
65
+ }
66
+ if (newHocs.length === 0) {
67
+ scopeMap.delete(component);
68
+ } else {
69
+ scopeMap.set(component, {
70
+ component: compose(...[...newHocs].reverse())(component),
71
+ hocs: newHocs
72
+ });
73
+ }
74
+ this.version++;
75
+ this.notifyListeners();
76
+ }
77
+ getComponent(component, scope = []) {
78
+ const scopesToResolve = ["*", ...scope].reverse();
79
+ for (const s of scopesToResolve) {
80
+ const scopeMap = this.scopes.get(s);
81
+ if (!scopeMap) {
82
+ continue;
83
+ }
84
+ const composed = scopeMap.get(component);
85
+ if (composed) {
86
+ return composed.component;
87
+ }
88
+ }
89
+ return undefined;
90
+ }
91
+
92
+ /**
93
+ * Bump version and notify listeners without changing store state.
94
+ * Used after a render-phase atomic swap (silent) to inform subscribers
95
+ * that the swap has settled and they should re-render with the final state.
96
+ */
97
+ notify() {
98
+ this.version++;
99
+ this.notifyListeners();
100
+ }
101
+ subscribe = listener => {
102
+ this.listeners.add(listener);
103
+ return () => {
104
+ this.listeners.delete(listener);
105
+ };
106
+ };
107
+ getSnapshot = () => {
108
+ return this.version;
109
+ };
110
+ notifyListeners() {
111
+ for (const listener of this.listeners) {
112
+ listener();
113
+ }
114
+ }
115
+ }
116
+
117
+ //# sourceMappingURL=CompositionStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["compose","CompositionStore","scopes","Map","version","listeners","Set","register","component","hocs","scope","inherit","silent","replaces","scopeMap","get","recipe","newHocs","filter","hoc","includes","length","unregister","existingHocs","globalScope","globalRecipe","globalHocsToAdd","unshift","finalHocs","set","reverse","notifyListeners","delete","getComponent","scopesToResolve","s","composed","undefined","notify","subscribe","listener","add","getSnapshot"],"sources":["CompositionStore.ts"],"sourcesContent":["import type { ComponentType } from \"react\";\nimport { compose } from \"~/Context.js\";\nimport type { Decorator, GenericComponent, GenericHook } from \"~/types.js\";\n\ninterface ComposedComponent {\n component: GenericHook | GenericComponent;\n hocs: Decorator<GenericComponent | GenericHook>[];\n}\n\ntype ComposedComponents = Map<ComponentType<unknown>, ComposedComponent>;\ntype ComponentScopes = Map<string, ComposedComponents>;\n\ntype Listener = () => void;\n\nexport class CompositionStore {\n private scopes: ComponentScopes = new Map();\n private version = 0;\n private listeners = new Set<Listener>();\n\n register(\n component: ComponentType<unknown>,\n hocs: Decorator<GenericComponent | GenericHook>[],\n scope = \"*\",\n inherit = false,\n silent = false,\n replaces: Decorator<GenericComponent | GenericHook>[] = []\n ): () => void {\n const scopeMap: ComposedComponents = this.scopes.get(scope) || new Map();\n const recipe = scopeMap.get(component) || {\n component: component as any,\n hocs: [] as Decorator<GenericComponent | GenericHook>[]\n };\n\n // Idempotent: skip if all HOCs are already registered (handles StrictMode double-render).\n const newHocs = hocs.filter(hoc => !recipe.hocs.includes(hoc));\n if (newHocs.length === 0 && replaces.length === 0) {\n return () => this.unregister(component, hocs, scope);\n }\n\n // Atomically remove the HOCs being replaced so the store never transiently\n // holds both the old and new decorators at the same time. This prevents\n // useSyncExternalStore subscribers from seeing a doubly-wrapped component\n // in the window between a render-phase registration and its effect cleanup.\n const existingHocs = replaces.length\n ? recipe.hocs.filter(hoc => !replaces.includes(hoc))\n : [...recipe.hocs];\n if (inherit && scope !== \"*\") {\n const globalScope = this.scopes.get(\"*\") || new Map();\n const globalRecipe = globalScope.get(component) || {\n component: component as any,\n hocs: [] as Decorator<GenericComponent | GenericHook>[]\n };\n // Only prepend global HOCs that aren't already present.\n const globalHocsToAdd = globalRecipe.hocs.filter(\n (hoc: Decorator<GenericComponent | GenericHook>) => !existingHocs.includes(hoc)\n );\n existingHocs.unshift(...globalHocsToAdd);\n }\n\n const finalHocs = [...existingHocs, ...newHocs];\n\n scopeMap.set(component, {\n component: compose(...[...finalHocs].reverse())(component as any),\n hocs: finalHocs\n });\n\n this.scopes.set(scope, scopeMap);\n\n // Bump the version so useSyncExternalStore sees a new snapshot.\n this.version++;\n\n // When called during render (silent=true), don't notify listeners —\n // that would trigger setState in other components mid-render.\n // Components that render after this point will see the updated snapshot.\n if (!silent) {\n this.notifyListeners();\n }\n\n return () => this.unregister(component, hocs, scope);\n }\n\n unregister(\n component: ComponentType<unknown>,\n hocs: Decorator<GenericComponent | GenericHook>[],\n scope = \"*\"\n ): void {\n const scopeMap = this.scopes.get(scope);\n if (!scopeMap) {\n return;\n }\n\n const recipe = scopeMap.get(component);\n if (!recipe) {\n return;\n }\n\n const newHocs = recipe.hocs.filter(hoc => !hocs.includes(hoc));\n if (newHocs.length === recipe.hocs.length) {\n // Nothing was removed.\n return;\n }\n\n if (newHocs.length === 0) {\n scopeMap.delete(component);\n } else {\n scopeMap.set(component, {\n component: compose(...[...newHocs].reverse())(component as any),\n hocs: newHocs\n });\n }\n\n this.version++;\n this.notifyListeners();\n }\n\n getComponent(\n component: ComponentType<unknown>,\n scope: string[] = []\n ): GenericComponent | GenericHook | undefined {\n const scopesToResolve = [\"*\", ...scope].reverse();\n for (const s of scopesToResolve) {\n const scopeMap = this.scopes.get(s);\n if (!scopeMap) {\n continue;\n }\n const composed = scopeMap.get(component);\n if (composed) {\n return composed.component;\n }\n }\n return undefined;\n }\n\n /**\n * Bump version and notify listeners without changing store state.\n * Used after a render-phase atomic swap (silent) to inform subscribers\n * that the swap has settled and they should re-render with the final state.\n */\n notify(): void {\n this.version++;\n this.notifyListeners();\n }\n\n subscribe = (listener: Listener): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n getSnapshot = (): number => {\n return this.version;\n };\n\n private notifyListeners(): void {\n for (const listener of this.listeners) {\n listener();\n }\n }\n}\n"],"mappings":"AACA,SAASA,OAAO;AAahB,OAAO,MAAMC,gBAAgB,CAAC;EAClBC,MAAM,GAAoB,IAAIC,GAAG,CAAC,CAAC;EACnCC,OAAO,GAAG,CAAC;EACXC,SAAS,GAAG,IAAIC,GAAG,CAAW,CAAC;EAEvCC,QAAQA,CACJC,SAAiC,EACjCC,IAAiD,EACjDC,KAAK,GAAG,GAAG,EACXC,OAAO,GAAG,KAAK,EACfC,MAAM,GAAG,KAAK,EACdC,QAAqD,GAAG,EAAE,EAChD;IACV,MAAMC,QAA4B,GAAG,IAAI,CAACZ,MAAM,CAACa,GAAG,CAACL,KAAK,CAAC,IAAI,IAAIP,GAAG,CAAC,CAAC;IACxE,MAAMa,MAAM,GAAGF,QAAQ,CAACC,GAAG,CAACP,SAAS,CAAC,IAAI;MACtCA,SAAS,EAAEA,SAAgB;MAC3BC,IAAI,EAAE;IACV,CAAC;;IAED;IACA,MAAMQ,OAAO,GAAGR,IAAI,CAACS,MAAM,CAACC,GAAG,IAAI,CAACH,MAAM,CAACP,IAAI,CAACW,QAAQ,CAACD,GAAG,CAA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,CAAC,CAACoB,OAAO,CAAC,CAAC;IACjD,KAAK,MAAMK,CAAC,IAAID,eAAe,EAAE;MAC7B,MAAMpB,QAAQ,GAAG,IAAI,CAACZ,MAAM,CAACa,GAAG,CAACoB,CAAC,CAAC;MACnC,IAAI,CAACrB,QAAQ,EAAE;QACX;MACJ;MACA,MAAMsB,QAAQ,GAAGtB,QAAQ,CAACC,GAAG,CAACP,SAAS,CAAC;MACxC,IAAI4B,QAAQ,EAAE;QACV,OAAOA,QAAQ,CAAC5B,SAAS;MAC7B;IACJ;IACA,OAAO6B,SAAS;EACpB;;EAEA;AACJ;AACA;AACA;AACA;EACIC,MAAMA,CAAA,EAAS;IACX,IAAI,CAAClC,OAAO,EAAE;IACd,IAAI,CAAC2B,eAAe,CAAC,CAAC;EAC1B;EAEAQ,SAAS,GAAIC,QAAkB,IAAmB;IAC9C,IAAI,CAACnC,SAAS,CAACoC,GAAG,CAACD,QAAQ,CAAC;IAC5B,OAAO,MAAM;MACT,IAAI,CAACnC,SAAS,CAAC2B,MAAM,CAACQ,QAAQ,CAAC;IACnC,CAAC;EACL,CAAC;EAEDE,WAAW,GAAGA,CAAA,KAAc;IACxB,OAAO,IAAI,CAACtC,OAAO;EACvB,CAAC;EAEO2B,eAAeA,CAAA,EAAS;IAC5B,KAAK,MAAMS,QAAQ,IAAI,IAAI,CAACnC,SAAS,EAAE;MACnCmC,QAAQ,CAAC,CAAC;IACd;EACJ;AACJ","ignoreList":[]}
package/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- export * from "./Context";
2
- export * from "./Compose";
3
- export * from "./makeComposable";
4
- export * from "./makeDecoratable";
5
- export * from "./createDecorator";
6
- export * from "./decorators";
7
- export * from "./CompositionScope";
8
- export * from "./types";
1
+ export * from "./Context.js";
2
+ export * from "./Compose.js";
3
+ export * from "./makeComposable.js";
4
+ export * from "./makeDecoratable.js";
5
+ export * from "./createDecorator.js";
6
+ export * from "./decorators.js";
7
+ export * from "./CompositionScope.js";
8
+ export { CompositionStore } from "./domain/CompositionStore.js";
9
+ export type * from "./types.js";
package/index.js CHANGED
@@ -1,10 +1,10 @@
1
- export * from "./Context";
2
- export * from "./Compose";
3
- export * from "./makeComposable";
4
- export * from "./makeDecoratable";
5
- export * from "./createDecorator";
6
- export * from "./decorators";
7
- export * from "./CompositionScope";
8
- export * from "./types";
1
+ export * from "./Context.js";
2
+ export * from "./Compose.js";
3
+ export * from "./makeComposable.js";
4
+ export * from "./makeDecoratable.js";
5
+ export * from "./createDecorator.js";
6
+ export * from "./decorators.js";
7
+ export * from "./CompositionScope.js";
8
+ export { CompositionStore } from "./domain/CompositionStore.js";
9
9
 
10
10
  //# sourceMappingURL=index.js.map
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":[],"sources":["index.ts"],"sourcesContent":["export * from \"./Context\";\nexport * from \"./Compose\";\nexport * from \"./makeComposable\";\nexport * from \"./makeDecoratable\";\nexport * from \"./createDecorator\";\nexport * from \"./decorators\";\nexport * from \"./CompositionScope\";\nexport * from \"./types\";\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","ignoreList":[]}
1
+ {"version":3,"names":["CompositionStore"],"sources":["index.ts"],"sourcesContent":["export * from \"./Context.js\";\nexport * from \"./Compose.js\";\nexport * from \"./makeComposable.js\";\nexport * from \"./makeDecoratable.js\";\nexport * from \"./createDecorator.js\";\nexport * from \"./decorators.js\";\nexport * from \"./CompositionScope.js\";\nexport { CompositionStore } from \"./domain/CompositionStore.js\";\nexport type * from \"./types.js\";\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,gBAAgB","ignoreList":[]}
@@ -1,13 +1,12 @@
1
- /// <reference types="react" />
2
- import type { GenericComponent } from "./types";
1
+ import type { GenericComponent } from "./types.js";
3
2
  /**
4
3
  * @deprecated Use `makeDecoratable` instead.
5
4
  */
6
- export declare function makeComposable<T extends GenericComponent>(name: string, Component?: T): ((() => null) | T) & {
5
+ export declare function makeComposable<T extends GenericComponent>(name: string, Component?: T): (((() => null) | T) & {
7
6
  original: (() => null) | T;
8
7
  originalName: string;
9
8
  displayName: string;
10
- } & {
9
+ }) & {
11
10
  original: ((() => null) | T) & {
12
11
  original: (() => null) | T;
13
12
  originalName: string;
@@ -16,7 +15,7 @@ export declare function makeComposable<T extends GenericComponent>(name: string,
16
15
  originalName: string;
17
16
  displayName: string;
18
17
  } & {
19
- createDecorator: (decorator: import("./types").ComponentDecorator<import("./createDecorator").GetDecoratee<(() => null) & {
18
+ createDecorator: (decorator: import("~/types.js").ComponentDecorator<import("./createDecorator").GetDecoratee<(() => null) & {
20
19
  original: (() => null) | T;
21
20
  originalName: string;
22
21
  displayName: string;
package/makeComposable.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createContext } from "react";
2
- import { makeDecoratable } from "./makeDecoratable";
2
+ import { makeDecoratable } from "./makeDecoratable.js";
3
3
  const ComposableContext = /*#__PURE__*/createContext([]);
4
4
  ComposableContext.displayName = "ComposableContext";
5
5
  const nullRenderer = () => null;
@@ -1 +1 @@
1
- {"version":3,"names":["createContext","makeDecoratable","ComposableContext","displayName","nullRenderer","makeComposable","name","Component"],"sources":["makeComposable.tsx"],"sourcesContent":["import { createContext } from \"react\";\nimport type { GenericComponent } from \"~/types\";\nimport { makeDecoratable } from \"~/makeDecoratable\";\n\nconst ComposableContext = createContext<string[]>([]);\nComposableContext.displayName = \"ComposableContext\";\n\nconst nullRenderer = () => null;\n\n/**\n * @deprecated Use `makeDecoratable` instead.\n */\nexport function makeComposable<T extends GenericComponent>(name: string, Component?: T) {\n return makeDecoratable(name, Component ?? nullRenderer);\n}\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,OAAO;AAErC,SAASC,eAAe;AAExB,MAAMC,iBAAiB,gBAAGF,aAAa,CAAW,EAAE,CAAC;AACrDE,iBAAiB,CAACC,WAAW,GAAG,mBAAmB;AAEnD,MAAMC,YAAY,GAAGA,CAAA,KAAM,IAAI;;AAE/B;AACA;AACA;AACA,OAAO,SAASC,cAAcA,CAA6BC,IAAY,EAAEC,SAAa,EAAE;EACpF,OAAON,eAAe,CAACK,IAAI,EAAEC,SAAS,IAAIH,YAAY,CAAC;AAC3D","ignoreList":[]}
1
+ {"version":3,"names":["createContext","makeDecoratable","ComposableContext","displayName","nullRenderer","makeComposable","name","Component"],"sources":["makeComposable.tsx"],"sourcesContent":["import { createContext } from \"react\";\nimport type { GenericComponent } from \"~/types.js\";\nimport { makeDecoratable } from \"~/makeDecoratable.js\";\n\nconst ComposableContext = createContext<string[]>([]);\nComposableContext.displayName = \"ComposableContext\";\n\nconst nullRenderer = () => null;\n\n/**\n * @deprecated Use `makeDecoratable` instead.\n */\nexport function makeComposable<T extends GenericComponent>(name: string, Component?: T) {\n return makeDecoratable(name, Component ?? nullRenderer);\n}\n"],"mappings":"AAAA,SAASA,aAAa,QAAQ,OAAO;AAErC,SAASC,eAAe;AAExB,MAAMC,iBAAiB,gBAAGF,aAAa,CAAW,EAAE,CAAC;AACrDE,iBAAiB,CAACC,WAAW,GAAG,mBAAmB;AAEnD,MAAMC,YAAY,GAAGA,CAAA,KAAM,IAAI;;AAE/B;AACA;AACA;AACA,OAAO,SAASC,cAAcA,CAA6BC,IAAY,EAAEC,SAAa,EAAE;EACpF,OAAON,eAAe,CAACK,IAAI,EAAEC,SAAS,IAAIH,YAAY,CAAC;AAC3D","ignoreList":[]}
@@ -1,5 +1,5 @@
1
1
  import React from "react";
2
- import type { DecoratableComponent, DecoratableHook, GenericComponent, GenericHook } from "./types";
2
+ import type { DecoratableComponent, DecoratableHook, GenericComponent, GenericHook } from "./types.js";
3
3
  declare function makeDecoratableComponent<T extends GenericComponent>(name: string, Component?: T): T & {
4
4
  original: T;
5
5
  originalName: string;
@@ -13,19 +13,19 @@ declare function makeDecoratableComponent<T extends GenericComponent>(name: stri
13
13
  originalName: string;
14
14
  displayName: string;
15
15
  } & {
16
- createDecorator: (decorator: import("./types").ComponentDecorator<import("./createDecorator").GetDecoratee<DecoratableComponent<T & {
16
+ createDecorator: (decorator: import("~/types.js").ComponentDecorator<import("./createDecorator.js").GetDecoratee<DecoratableComponent<T & {
17
17
  original: T;
18
18
  originalName: string;
19
19
  displayName: string;
20
20
  }>>>) => (props: unknown) => React.JSX.Element;
21
21
  };
22
- export declare function makeDecoratableHook<T extends GenericHook>(hook: T): GenericHook<import("./createDecorator").GetDecorateeParams<import("./createDecorator").GetDecoratee<DecoratableHook<T>>>, ReturnType<import("./createDecorator").GetDecoratee<DecoratableHook<T>>>> & {
23
- original: GenericHook<import("./createDecorator").GetDecorateeParams<import("./createDecorator").GetDecoratee<DecoratableHook<T>>>, ReturnType<import("./createDecorator").GetDecoratee<DecoratableHook<T>>>>;
22
+ export declare function makeDecoratableHook<T extends GenericHook>(hook: T): GenericHook<import("./createDecorator.js").GetDecorateeParams<import("./createDecorator.js").GetDecoratee<DecoratableHook<T>>>, ReturnType<import("./createDecorator.js").GetDecoratee<DecoratableHook<T>>>> & {
23
+ original: GenericHook<import("./createDecorator.js").GetDecorateeParams<import("./createDecorator.js").GetDecoratee<DecoratableHook<T>>>, ReturnType<import("./createDecorator.js").GetDecoratee<DecoratableHook<T>>>>;
24
24
  originalName: string;
25
25
  } & {
26
- createDecorator: (decorator: import("./types").Decorator<import("./createDecorator").GetDecoratee<DecoratableHook<T>>>) => () => React.JSX.Element;
26
+ createDecorator: (decorator: import("~/types.js").Decorator<import("./createDecorator.js").GetDecoratee<DecoratableHook<T>>>) => () => React.JSX.Element;
27
27
  };
28
- export declare function createVoidComponent<T>(): (props: T) => JSX.Element | null;
28
+ export declare function createVoidComponent<T>(): (props: T) => React.JSX.Element | null;
29
29
  export declare function makeDecoratable<T extends GenericHook>(hook: T): ReturnType<typeof makeDecoratableHook<T>>;
30
30
  export declare function makeDecoratable<T extends GenericComponent>(name: string, Component: T): ReturnType<typeof makeDecoratableComponent<T>>;
31
31
  export {};
@@ -1,6 +1,41 @@
1
1
  import React, { createContext, useContext, useMemo } from "react";
2
- import { useComponent } from "./Context";
3
- import { withDecoratorFactory, withHookDecoratorFactory } from "./decorators";
2
+ import { useComponent } from "./Context.js";
3
+ import { withDecoratorFactory, withHookDecoratorFactory } from "./decorators.js";
4
+ class DecoratableErrorBoundary extends React.Component {
5
+ constructor(props) {
6
+ super(props);
7
+ this.state = {
8
+ hasError: false,
9
+ error: undefined
10
+ };
11
+ }
12
+ static getDerivedStateFromError(error) {
13
+ return {
14
+ hasError: true,
15
+ error
16
+ };
17
+ }
18
+ componentDidCatch(error, errorInfo) {
19
+ console.groupCollapsed(`%cCOMPONENT ERROR%c: "${this.props.name}" failed to render.`, "color:red", "color:default");
20
+ console.error(error, errorInfo);
21
+ console.groupEnd();
22
+ }
23
+ render() {
24
+ if (this.state.hasError) {
25
+ return /*#__PURE__*/React.createElement("div", {
26
+ style: {
27
+ padding: "8px 12px",
28
+ border: "1px solid #e53e3e",
29
+ borderRadius: 4,
30
+ background: "#fff5f5",
31
+ color: "#c53030",
32
+ fontSize: 13
33
+ }
34
+ }, /*#__PURE__*/React.createElement("strong", null, this.props.name), ": ", this.state.error?.message);
35
+ }
36
+ return this.props.children;
37
+ }
38
+ }
4
39
  const ComposableContext = /*#__PURE__*/createContext([]);
5
40
  ComposableContext.displayName = "ComposableContext";
6
41
  function useComposableParents() {
@@ -18,7 +53,9 @@ function makeDecoratableComponent(name, Component = nullRenderer) {
18
53
  const context = useMemo(() => [...parents, name], [parents, name]);
19
54
  return /*#__PURE__*/React.createElement(ComposableContext.Provider, {
20
55
  value: context
21
- }, /*#__PURE__*/React.createElement(ComposedComponent, props, props.children));
56
+ }, /*#__PURE__*/React.createElement(DecoratableErrorBoundary, {
57
+ name: name
58
+ }, /*#__PURE__*/React.createElement(ComposedComponent, props, props.children)));
22
59
  };
23
60
  const staticProps = {
24
61
  original: Component,
@@ -36,7 +73,7 @@ export function makeDecoratableHook(hook) {
36
73
  return withHookDecoratorFactory()(decoratableHook);
37
74
  }
38
75
  export function createVoidComponent() {
39
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
76
+ // oxlint-disable-next-line typescript/no-unused-vars
40
77
  return props => {
41
78
  return null;
42
79
  };
@@ -1 +1 @@
1
- {"version":3,"names":["React","createContext","useContext","useMemo","useComponent","withDecoratorFactory","withHookDecoratorFactory","ComposableContext","displayName","useComposableParents","context","nullRenderer","makeDecoratableComponent","name","Component","Decoratable","props","parents","ComposedComponent","createElement","Provider","value","children","staticProps","original","originalName","Object","assign","makeDecoratableHook","hook","decoratableHook","params","composedHook","createVoidComponent","makeDecoratable","hookOrName","component","memo"],"sources":["makeDecoratable.tsx"],"sourcesContent":["import React, { createContext, useContext, useMemo } from \"react\";\nimport { useComponent } from \"./Context\";\nimport type { DecoratableComponent, DecoratableHook, GenericComponent, GenericHook } from \"~/types\";\nimport { withDecoratorFactory, withHookDecoratorFactory } from \"~/decorators\";\n\nconst ComposableContext = createContext<string[]>([]);\nComposableContext.displayName = \"ComposableContext\";\n\nfunction useComposableParents() {\n const context = useContext(ComposableContext);\n if (!context) {\n return [];\n }\n\n return context;\n}\n\nconst nullRenderer = () => null;\n\nfunction makeDecoratableComponent<T extends GenericComponent>(\n name: string,\n Component: T = nullRenderer as unknown as T\n) {\n const Decoratable = (props: React.ComponentProps<T>): JSX.Element | null => {\n const parents = useComposableParents();\n const ComposedComponent = useComponent(Component) as GenericComponent<\n React.ComponentProps<T>\n >;\n\n const context = useMemo(() => [...parents, name], [parents, name]);\n\n return (\n <ComposableContext.Provider value={context}>\n <ComposedComponent {...props}>{props.children}</ComposedComponent>\n </ComposableContext.Provider>\n );\n };\n\n const staticProps = {\n original: Component,\n originalName: name,\n displayName: `Decoratable<${name}>`\n };\n\n return withDecoratorFactory()(\n Object.assign(Decoratable, staticProps) as DecoratableComponent<\n typeof Component & typeof staticProps\n >\n );\n}\n\nexport function makeDecoratableHook<T extends GenericHook>(hook: T) {\n const decoratableHook = (params: Parameters<T>) => {\n const composedHook = useComponent(hook);\n\n return composedHook(params) as DecoratableHook<T>;\n };\n\n decoratableHook.original = hook;\n\n return withHookDecoratorFactory()(decoratableHook as DecoratableHook<T>);\n}\n\nexport function createVoidComponent<T>() {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n return (props: T): JSX.Element | null => {\n return null;\n };\n}\n\nexport function makeDecoratable<T extends GenericHook>(\n hook: T\n): ReturnType<typeof makeDecoratableHook<T>>;\nexport function makeDecoratable<T extends GenericComponent>(\n name: string,\n Component: T\n): ReturnType<typeof makeDecoratableComponent<T>>;\nexport function makeDecoratable(hookOrName: any, Component?: any) {\n if (Component) {\n const component = makeDecoratableComponent(hookOrName, React.memo(Component));\n component.original.displayName = hookOrName;\n return component;\n }\n\n return makeDecoratableHook(hookOrName);\n}\n"],"mappings":"AAAA,OAAOA,KAAK,IAAIC,aAAa,EAAEC,UAAU,EAAEC,OAAO,QAAQ,OAAO;AACjE,SAASC,YAAY;AAErB,SAASC,oBAAoB,EAAEC,wBAAwB;AAEvD,MAAMC,iBAAiB,gBAAGN,aAAa,CAAW,EAAE,CAAC;AACrDM,iBAAiB,CAACC,WAAW,GAAG,mBAAmB;AAEnD,SAASC,oBAAoBA,CAAA,EAAG;EAC5B,MAAMC,OAAO,GAAGR,UAAU,CAACK,iBAAiB,CAAC;EAC7C,IAAI,CAACG,OAAO,EAAE;IACV,OAAO,EAAE;EACb;EAEA,OAAOA,OAAO;AAClB;AAEA,MAAMC,YAAY,GAAGA,CAAA,KAAM,IAAI;AAE/B,SAASC,wBAAwBA,CAC7BC,IAAY,EACZC,SAAY,GAAGH,YAA4B,EAC7C;EACE,MAAMI,WAAW,GAAIC,KAA8B,IAAyB;IACxE,MAAMC,OAAO,GAAGR,oBAAoB,CAAC,CAAC;IACtC,MAAMS,iBAAiB,GAAGd,YAAY,CAACU,SAAS,CAE/C;IAED,MAAMJ,OAAO,GAAGP,OAAO,CAAC,MAAM,CAAC,GAAGc,OAAO,EAAEJ,IAAI,CAAC,EAAE,CAACI,OAAO,EAAEJ,IAAI,CAAC,CAAC;IAElE,oBACIb,KAAA,CAAAmB,aAAA,CAACZ,iBAAiB,CAACa,QAAQ;MAACC,KAAK,EAAEX;IAAQ,gBACvCV,KAAA,CAAAmB,aAAA,CAACD,iBAAiB,EAAKF,KAAK,EAAGA,KAAK,CAACM,QAA4B,CACzC,CAAC;EAErC,CAAC;EAED,MAAMC,WAAW,GAAG;IAChBC,QAAQ,EAAEV,SAAS;IACnBW,YAAY,EAAEZ,IAAI;IAClBL,WAAW,EAAE,eAAeK,IAAI;EACpC,CAAC;EAED,OAAOR,oBAAoB,CAAC,CAAC,CACzBqB,MAAM,CAACC,MAAM,CAACZ,WAAW,EAAEQ,WAAW,CAG1C,CAAC;AACL;AAEA,OAAO,SAASK,mBAAmBA,CAAwBC,IAAO,EAAE;EAChE,MAAMC,eAAe,GAAIC,MAAqB,IAAK;IAC/C,MAAMC,YAAY,GAAG5B,YAAY,CAACyB,IAAI,CAAC;IAEvC,OAAOG,YAAY,CAACD,MAAM,CAAC;EAC/B,CAAC;EAEDD,eAAe,CAACN,QAAQ,GAAGK,IAAI;EAE/B,OAAOvB,wBAAwB,CAAC,CAAC,CAACwB,eAAqC,CAAC;AAC5E;AAEA,OAAO,SAASG,mBAAmBA,CAAA,EAAM;EACrC;EACA,OAAQjB,KAAQ,IAAyB;IACrC,OAAO,IAAI;EACf,CAAC;AACL;AASA,OAAO,SAASkB,eAAeA,CAACC,UAAe,EAAErB,SAAe,EAAE;EAC9D,IAAIA,SAAS,EAAE;IACX,MAAMsB,SAAS,GAAGxB,wBAAwB,CAACuB,UAAU,eAAEnC,KAAK,CAACqC,IAAI,CAACvB,SAAS,CAAC,CAAC;IAC7EsB,SAAS,CAACZ,QAAQ,CAAChB,WAAW,GAAG2B,UAAU;IAC3C,OAAOC,SAAS;EACpB;EAEA,OAAOR,mBAAmB,CAACO,UAAU,CAAC;AAC1C","ignoreList":[]}
1
+ {"version":3,"names":["React","createContext","useContext","useMemo","useComponent","withDecoratorFactory","withHookDecoratorFactory","DecoratableErrorBoundary","Component","constructor","props","state","hasError","error","undefined","getDerivedStateFromError","componentDidCatch","errorInfo","console","groupCollapsed","name","groupEnd","render","createElement","style","padding","border","borderRadius","background","color","fontSize","message","children","ComposableContext","displayName","useComposableParents","context","nullRenderer","makeDecoratableComponent","Decoratable","parents","ComposedComponent","Provider","value","staticProps","original","originalName","Object","assign","makeDecoratableHook","hook","decoratableHook","params","composedHook","createVoidComponent","makeDecoratable","hookOrName","component","memo"],"sources":["makeDecoratable.tsx"],"sourcesContent":["import React, { createContext, useContext, useMemo } from \"react\";\nimport type { ErrorInfo } from \"react\";\nimport { useComponent } from \"./Context.js\";\nimport type {\n DecoratableComponent,\n DecoratableHook,\n GenericComponent,\n GenericHook\n} from \"~/types.js\";\nimport { withDecoratorFactory, withHookDecoratorFactory } from \"~/decorators.js\";\n\ninterface ErrorBoundaryProps {\n name: string;\n children: React.ReactNode;\n}\n\ninterface ErrorBoundaryState {\n hasError: boolean;\n error: Error | undefined;\n}\n\nclass DecoratableErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {\n constructor(props: ErrorBoundaryProps) {\n super(props);\n this.state = { hasError: false, error: undefined };\n }\n\n static getDerivedStateFromError(error: Error): ErrorBoundaryState {\n return { hasError: true, error };\n }\n\n override componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n console.groupCollapsed(\n `%cCOMPONENT ERROR%c: \"${this.props.name}\" failed to render.`,\n \"color:red\",\n \"color:default\"\n );\n console.error(error, errorInfo);\n console.groupEnd();\n }\n\n override render() {\n if (this.state.hasError) {\n return (\n <div\n style={{\n padding: \"8px 12px\",\n border: \"1px solid #e53e3e\",\n borderRadius: 4,\n background: \"#fff5f5\",\n color: \"#c53030\",\n fontSize: 13\n }}\n >\n <strong>{this.props.name}</strong>: {this.state.error?.message}\n </div>\n );\n }\n return this.props.children;\n }\n}\n\nconst ComposableContext = createContext<string[]>([]);\nComposableContext.displayName = \"ComposableContext\";\n\nfunction useComposableParents() {\n const context = useContext(ComposableContext);\n if (!context) {\n return [];\n }\n\n return context;\n}\n\nconst nullRenderer = () => null;\n\nfunction makeDecoratableComponent<T extends GenericComponent>(\n name: string,\n Component: T = nullRenderer as unknown as T\n) {\n const Decoratable = (props: React.ComponentProps<T>): React.JSX.Element | null => {\n const parents = useComposableParents();\n const ComposedComponent = useComponent(Component) as GenericComponent<\n React.ComponentProps<T>\n >;\n\n const context = useMemo(() => [...parents, name], [parents, name]);\n\n return (\n <ComposableContext.Provider value={context}>\n <DecoratableErrorBoundary name={name}>\n <ComposedComponent {...props}>{props.children}</ComposedComponent>\n </DecoratableErrorBoundary>\n </ComposableContext.Provider>\n );\n };\n\n const staticProps = {\n original: Component,\n originalName: name,\n displayName: `Decoratable<${name}>`\n };\n\n return withDecoratorFactory()(\n Object.assign(Decoratable, staticProps) as DecoratableComponent<\n typeof Component & typeof staticProps\n >\n );\n}\n\nexport function makeDecoratableHook<T extends GenericHook>(hook: T) {\n const decoratableHook = (params: Parameters<T>) => {\n const composedHook = useComponent(hook);\n\n return composedHook(params) as DecoratableHook<T>;\n };\n\n decoratableHook.original = hook;\n\n return withHookDecoratorFactory()(decoratableHook as DecoratableHook<T>);\n}\n\nexport function createVoidComponent<T>() {\n // oxlint-disable-next-line typescript/no-unused-vars\n return (props: T): React.JSX.Element | null => {\n return null;\n };\n}\n\nexport function makeDecoratable<T extends GenericHook>(\n hook: T\n): ReturnType<typeof makeDecoratableHook<T>>;\nexport function makeDecoratable<T extends GenericComponent>(\n name: string,\n Component: T\n): ReturnType<typeof makeDecoratableComponent<T>>;\nexport function makeDecoratable(hookOrName: any, Component?: any) {\n if (Component) {\n const component = makeDecoratableComponent(hookOrName, React.memo(Component));\n component.original.displayName = hookOrName;\n return component;\n }\n\n return makeDecoratableHook(hookOrName);\n}\n"],"mappings":"AAAA,OAAOA,KAAK,IAAIC,aAAa,EAAEC,UAAU,EAAEC,OAAO,QAAQ,OAAO;AAEjE,SAASC,YAAY;AAOrB,SAASC,oBAAoB,EAAEC,wBA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GK,IAAI;EAE/B,OAAO5C,wBAAwB,CAAC,CAAC,CAAC6C,eAAqC,CAAC;AAC5E;AAEA,OAAO,SAASG,mBAAmBA,CAAA,EAAM;EACrC;EACA,OAAQ5C,KAAQ,IAA+B;IAC3C,OAAO,IAAI;EACf,CAAC;AACL;AASA,OAAO,SAAS6C,eAAeA,CAACC,UAAe,EAAEhD,SAAe,EAAE;EAC9D,IAAIA,SAAS,EAAE;IACX,MAAMiD,SAAS,GAAGnB,wBAAwB,CAACkB,UAAU,eAAExD,KAAK,CAAC0D,IAAI,CAAClD,SAAS,CAAC,CAAC;IAC7EiD,SAAS,CAACZ,QAAQ,CAACX,WAAW,GAAGsB,UAAU;IAC3C,OAAOC,SAAS;EACpB;EAEA,OAAOR,mBAAmB,CAACO,UAAU,CAAC;AAC1C","ignoreList":[]}
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "@webiny/react-composition",
3
- "version": "0.0.0-unstable.e53eceafb5",
4
- "main": "index.js",
3
+ "version": "0.0.0-unstable.e6f0dc8ca7",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./index.js",
7
+ "./*": "./*"
8
+ },
5
9
  "repository": {
6
10
  "type": "git",
7
11
  "url": "https://github.com/webiny/webiny-js.git"
@@ -14,22 +18,19 @@
14
18
  ],
15
19
  "license": "MIT",
16
20
  "dependencies": {
17
- "@types/react": "18.2.79",
18
- "react": "18.2.0",
19
- "react-dom": "18.2.0"
21
+ "@types/react": "18.3.28",
22
+ "react": "18.3.1",
23
+ "react-dom": "18.3.1"
20
24
  },
21
25
  "devDependencies": {
22
- "@testing-library/react": "15.0.7",
23
- "@webiny/project-utils": "0.0.0-unstable.e53eceafb5",
24
- "typescript": "5.3.3"
26
+ "@testing-library/react": "16.3.2",
27
+ "@webiny/build-tools": "0.0.0-unstable.e6f0dc8ca7",
28
+ "typescript": "6.0.3",
29
+ "vitest": "4.1.5"
25
30
  },
26
31
  "publishConfig": {
27
32
  "access": "public",
28
33
  "directory": "dist"
29
34
  },
30
- "scripts": {
31
- "build": "node ../cli/bin.js run build",
32
- "watch": "node ../cli/bin.js run watch"
33
- },
34
- "gitHead": "e53eceafb5ce1a3872c9b4548939bb2eae5b1aef"
35
+ "gitHead": "e6f0dc8ca741c1fcc3fec9a5b9e86fdd49544641"
35
36
  }
package/types.d.ts CHANGED
@@ -32,4 +32,4 @@ export type Decoratable = DecoratableComponent | DecoratableHook;
32
32
  /**
33
33
  * @internal Add `null` to the ReturnType of the given function.
34
34
  */
35
- export type CanReturnNullOrElement<T> = T extends (...args: any) => any ? (...args: Parameters<T>) => JSX.Element | null : never;
35
+ export type CanReturnNullOrElement<T> = T extends (...args: any) => any ? (...args: Parameters<T>) => React.JSX.Element | null : never;
package/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":[],"sources":["types.ts"],"sourcesContent":["import type React from \"react\";\n\nexport type GenericHook<TParams = any, TReturn = any> = (...args: TParams[]) => TReturn;\n\nexport type GenericComponent<T = any> = React.FunctionComponent<T>;\n\nexport type ComposedFunction = GenericHook;\n\nexport type Decorator<T> = (decoratee: T) => T;\n\n/**\n * Some decoratable components will always return `null`, by design.\n * To allow you to decorate these components, we must tell TS that the decorator is allowed to return not just `null`\n * (which is inferred from the component type), but also a JSX.Element.\n */\nexport type ComponentDecorator<T> = (decoratee: T) => CanReturnNullOrElement<T>;\n\n/**\n * @deprecated\n */\nexport type ComposableFC<T> = T & {\n displayName?: string;\n original: T;\n originalName: string;\n};\n\nexport type Enumerable<T> = T extends Array<infer D> ? Array<D> : never;\n\nexport type ComposeWith =\n | Decorator<GenericComponent>\n | Decorator<GenericComponent>[]\n | Decorator<GenericHook>\n | Decorator<GenericHook>[];\n\nexport type DecoratableHook<T extends GenericHook = GenericHook> = T & {\n original: T;\n originalName: string;\n};\n\nexport type DecoratableComponent<T = GenericComponent> = T & {\n original: T;\n originalName: string;\n displayName: string;\n};\n\nexport type Decoratable = DecoratableComponent | DecoratableHook;\n\n/**\n * @internal Add `null` to the ReturnType of the given function.\n */\nexport type CanReturnNullOrElement<T> = T extends (...args: any) => any\n ? (...args: Parameters<T>) => JSX.Element | null\n : never;\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"names":[],"sources":["types.ts"],"sourcesContent":["import type React from \"react\";\n\nexport type GenericHook<TParams = any, TReturn = any> = (...args: TParams[]) => TReturn;\n\nexport type GenericComponent<T = any> = React.FunctionComponent<T>;\n\nexport type ComposedFunction = GenericHook;\n\nexport type Decorator<T> = (decoratee: T) => T;\n\n/**\n * Some decoratable components will always return `null`, by design.\n * To allow you to decorate these components, we must tell TS that the decorator is allowed to return not just `null`\n * (which is inferred from the component type), but also a JSX.Element.\n */\nexport type ComponentDecorator<T> = (decoratee: T) => CanReturnNullOrElement<T>;\n\n/**\n * @deprecated\n */\nexport type ComposableFC<T> = T & {\n displayName?: string;\n original: T;\n originalName: string;\n};\n\nexport type Enumerable<T> = T extends Array<infer D> ? Array<D> : never;\n\nexport type ComposeWith =\n | Decorator<GenericComponent>\n | Decorator<GenericComponent>[]\n | Decorator<GenericHook>\n | Decorator<GenericHook>[];\n\nexport type DecoratableHook<T extends GenericHook = GenericHook> = T & {\n original: T;\n originalName: string;\n};\n\nexport type DecoratableComponent<T = GenericComponent> = T & {\n original: T;\n originalName: string;\n displayName: string;\n};\n\nexport type Decoratable = DecoratableComponent | DecoratableHook;\n\n/**\n * @internal Add `null` to the ReturnType of the given function.\n */\nexport type CanReturnNullOrElement<T> = T extends (...args: any) => any\n ? (...args: Parameters<T>) => React.JSX.Element | null\n : never;\n"],"mappings":"","ignoreList":[]}