@hanzogui/create-context 2.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Nate Wienert
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,130 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf,
6
+ __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: !0
11
+ });
12
+ },
13
+ __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
15
+ get: () => from[key],
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
26
+ value: mod,
27
+ enumerable: !0
28
+ }) : target, mod)),
29
+ __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
30
+ value: !0
31
+ }), mod);
32
+ var create_context_exports = {};
33
+ __export(create_context_exports, {
34
+ createContext: () => createContext,
35
+ createContextScope: () => createContextScope
36
+ });
37
+ module.exports = __toCommonJS(create_context_exports);
38
+ var React = __toESM(require("react"), 1),
39
+ import_jsx_runtime = require("react/jsx-runtime");
40
+ function createContext(rootComponentName, defaultContext) {
41
+ const Context = React.createContext(defaultContext);
42
+ function Provider(props) {
43
+ const {
44
+ children,
45
+ ...context
46
+ } = props,
47
+ value = React.useMemo(() => context, Object.values(context));
48
+ return /* @__PURE__ */(0, import_jsx_runtime.jsx)(Context.Provider, {
49
+ value,
50
+ children
51
+ });
52
+ }
53
+ function useContext(consumerName) {
54
+ const context = React.useContext(Context);
55
+ if (context) return context;
56
+ if (defaultContext !== void 0) return defaultContext;
57
+ throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
58
+ }
59
+ return [Provider, useContext];
60
+ }
61
+ function createContextScope(scopeName, createContextScopeDeps = []) {
62
+ let defaultContexts = [];
63
+ function createContext2(rootComponentName, defaultContext) {
64
+ const BaseContext = React.createContext(defaultContext),
65
+ index = defaultContexts.length;
66
+ defaultContexts = [...defaultContexts, defaultContext];
67
+ function Provider(props) {
68
+ const {
69
+ scope,
70
+ children,
71
+ ...context
72
+ } = props,
73
+ Context = scope?.[scopeName]?.[index] || BaseContext,
74
+ value = React.useMemo(() => context, Object.values(context));
75
+ return /* @__PURE__ */(0, import_jsx_runtime.jsx)(Context.Provider, {
76
+ value,
77
+ children
78
+ });
79
+ }
80
+ function useContext(consumerName, scope, options) {
81
+ const Context = scope?.[scopeName]?.[index] || BaseContext,
82
+ context = React.useContext(Context);
83
+ if (context) return context;
84
+ if (defaultContext !== void 0) return defaultContext;
85
+ const missingContextMessage = `\`${consumerName}\` must be used within \`${rootComponentName}\``;
86
+ if (options?.fallback) return options?.warn !== !1 && console.warn(missingContextMessage), options.fallback;
87
+ throw new Error(missingContextMessage);
88
+ }
89
+ return [Provider, useContext];
90
+ }
91
+ const createScope = () => {
92
+ const scopeContexts = defaultContexts.map(defaultContext => React.createContext(defaultContext));
93
+ return function (scope) {
94
+ const contexts = scope?.[scopeName] || scopeContexts;
95
+ return React.useMemo(() => ({
96
+ [`__scope${scopeName}`]: {
97
+ ...scope,
98
+ [scopeName]: contexts
99
+ }
100
+ }), [scope, contexts]);
101
+ };
102
+ };
103
+ return createScope.scopeName = scopeName, [createContext2, composeContextScopes(createScope, ...createContextScopeDeps)];
104
+ }
105
+ function composeContextScopes(...scopes) {
106
+ const baseScope = scopes[0];
107
+ if (scopes.length === 1) return baseScope;
108
+ const createScope = () => {
109
+ const scopeHooks = scopes.map(createScope2 => ({
110
+ useScope: createScope2(),
111
+ scopeName: createScope2.scopeName
112
+ }));
113
+ return function (overrideScopes) {
114
+ const nextScopes = scopeHooks.reduce((nextScopes2, {
115
+ useScope,
116
+ scopeName
117
+ }) => {
118
+ const currentScope = useScope(overrideScopes)[`__scope${scopeName}`];
119
+ return {
120
+ ...nextScopes2,
121
+ ...currentScope
122
+ };
123
+ }, {});
124
+ return React.useMemo(() => ({
125
+ [`__scope${baseScope.scopeName}`]: nextScopes
126
+ }), [nextScopes]);
127
+ };
128
+ };
129
+ return createScope.scopeName = baseScope.scopeName, createScope;
130
+ }
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf,
8
+ __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all) __defProp(target, name, {
11
+ get: all[name],
12
+ enumerable: !0
13
+ });
14
+ },
15
+ __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
17
+ get: () => from[key],
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
28
+ value: mod,
29
+ enumerable: !0
30
+ }) : target, mod)),
31
+ __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
32
+ value: !0
33
+ }), mod);
34
+ var create_context_exports = {};
35
+ __export(create_context_exports, {
36
+ createContext: () => createContext,
37
+ createContextScope: () => createContextScope
38
+ });
39
+ module.exports = __toCommonJS(create_context_exports);
40
+ var import_jsx_runtime = require("react/jsx-runtime"),
41
+ React = __toESM(require("react"), 1);
42
+ function createContext(rootComponentName, defaultContext) {
43
+ var Context = /* @__PURE__ */React.createContext(defaultContext);
44
+ function Provider(props) {
45
+ var {
46
+ children,
47
+ ...context
48
+ } = props,
49
+ value = React.useMemo(function () {
50
+ return context;
51
+ }, Object.values(context));
52
+ return /* @__PURE__ */(0, import_jsx_runtime.jsx)(Context.Provider, {
53
+ value,
54
+ children
55
+ });
56
+ }
57
+ function useContext(consumerName) {
58
+ var context = React.useContext(Context);
59
+ if (context) return context;
60
+ if (defaultContext !== void 0) return defaultContext;
61
+ throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
62
+ }
63
+ return [Provider, useContext];
64
+ }
65
+ function createContextScope(scopeName) {
66
+ var createContextScopeDeps = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [],
67
+ defaultContexts = [];
68
+ function createContext2(rootComponentName, defaultContext) {
69
+ var BaseContext = /* @__PURE__ */React.createContext(defaultContext),
70
+ index = defaultContexts.length;
71
+ defaultContexts = [...defaultContexts, defaultContext];
72
+ function Provider(props) {
73
+ var _scope_scopeName,
74
+ {
75
+ scope,
76
+ children,
77
+ ...context
78
+ } = props,
79
+ Context = (scope == null || (_scope_scopeName = scope[scopeName]) === null || _scope_scopeName === void 0 ? void 0 : _scope_scopeName[index]) || BaseContext,
80
+ value = React.useMemo(function () {
81
+ return context;
82
+ }, Object.values(context));
83
+ return /* @__PURE__ */(0, import_jsx_runtime.jsx)(Context.Provider, {
84
+ value,
85
+ children
86
+ });
87
+ }
88
+ function useContext(consumerName, scope, options) {
89
+ var _scope_scopeName,
90
+ Context = (scope == null || (_scope_scopeName = scope[scopeName]) === null || _scope_scopeName === void 0 ? void 0 : _scope_scopeName[index]) || BaseContext,
91
+ context = React.useContext(Context);
92
+ if (context) return context;
93
+ if (defaultContext !== void 0) return defaultContext;
94
+ var missingContextMessage = `\`${consumerName}\` must be used within \`${rootComponentName}\``;
95
+ if (options?.fallback) return options?.warn !== !1 && console.warn(missingContextMessage), options.fallback;
96
+ throw new Error(missingContextMessage);
97
+ }
98
+ return [Provider, useContext];
99
+ }
100
+ var createScope = function () {
101
+ var scopeContexts = defaultContexts.map(function (defaultContext) {
102
+ return /* @__PURE__ */React.createContext(defaultContext);
103
+ });
104
+ return function (scope) {
105
+ var contexts = scope?.[scopeName] || scopeContexts;
106
+ return React.useMemo(function () {
107
+ return {
108
+ [`__scope${scopeName}`]: {
109
+ ...scope,
110
+ [scopeName]: contexts
111
+ }
112
+ };
113
+ }, [scope, contexts]);
114
+ };
115
+ };
116
+ return createScope.scopeName = scopeName, [createContext2, composeContextScopes(createScope, ...createContextScopeDeps)];
117
+ }
118
+ function composeContextScopes() {
119
+ for (var _len = arguments.length, scopes = new Array(_len), _key = 0; _key < _len; _key++) scopes[_key] = arguments[_key];
120
+ var baseScope = scopes[0];
121
+ if (scopes.length === 1) return baseScope;
122
+ var createScope = function () {
123
+ var scopeHooks = scopes.map(function (createScope2) {
124
+ return {
125
+ useScope: createScope2(),
126
+ scopeName: createScope2.scopeName
127
+ };
128
+ });
129
+ return function (overrideScopes) {
130
+ var nextScopes = scopeHooks.reduce(function (nextScopes2, param) {
131
+ var {
132
+ useScope,
133
+ scopeName
134
+ } = param,
135
+ scopeProps = useScope(overrideScopes),
136
+ currentScope = scopeProps[`__scope${scopeName}`];
137
+ return {
138
+ ...nextScopes2,
139
+ ...currentScope
140
+ };
141
+ }, {});
142
+ return React.useMemo(function () {
143
+ return {
144
+ [`__scope${baseScope.scopeName}`]: nextScopes
145
+ };
146
+ }, [nextScopes]);
147
+ };
148
+ };
149
+ return createScope.scopeName = baseScope.scopeName, createScope;
150
+ }
151
+ //# sourceMappingURL=create-context.native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["__toCommonJS","mod","__copyProps","__defProp","value","create_context_exports","__export","createContext","createContextScope","module","exports","import_jsx_runtime","require","React","__toESM","rootComponentName","defaultContext","Context","Provider","props","children","context","useMemo","Object","values","jsx","useContext","consumerName","Error","scopeName","createContextScopeDeps","arguments","length","defaultContexts","createContext2","BaseContext","index","_scope_scopeName","scope","options","missingContextMessage","fallback","warn","console","createScope","scopeContexts","map","contexts"],"sources":["../../src/create-context.tsx"],"sourcesContent":[null],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAAA;EAAAA,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AAc;IAEzB,IAAMC,aAAA,GAA2BZ,eAAM,CAAAa,GAAA,WAAA9B,cAAA;MACrC,OAAM,eAAaH,KAAW,CAACN,aAAA,CAAAS,cAAiB;IAAA,EAC9C;IAAsB,OACtB,UAAWsB,KAAA;MACX,IAAAS,QAAA,GAAAT,KAAA,GAAAT,SAAA,KAAAgB,aAAA;MAEF,OAAOhC,KAAA,CAAAS,OAA2B,aAAgB;QAChD,OAAM;UAKJ,WAAMO,SADa;YAEnB,GAAOS,KAAK;YACT,CAAAT,SAAA,GAAAkB;UAEL;QACE;MAAuD,GACtD,CACHT,KAAA,EACFS,QAAA,CACF;IAEA;EAEF","ignoreList":[]}
@@ -0,0 +1,18 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
7
+ get: () => from[key],
8
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
9
+ });
10
+ return to;
11
+ },
12
+ __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
13
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
14
+ value: !0
15
+ }), mod);
16
+ var index_exports = {};
17
+ module.exports = __toCommonJS(index_exports);
18
+ __reExport(index_exports, require("./create-context.cjs"), module.exports);
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __copyProps = (to, from, except, desc) => {
8
+ if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
9
+ get: () => from[key],
10
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
11
+ });
12
+ return to;
13
+ },
14
+ __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
16
+ value: !0
17
+ }), mod);
18
+ var index_exports = {};
19
+ module.exports = __toCommonJS(index_exports);
20
+ __reExport(index_exports, require("./create-context.native.js"), module.exports);
21
+ //# sourceMappingURL=index.native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["__toCommonJS","mod","__copyProps","__defProp","value","index_exports","module","exports"],"sources":["../../src/index.ts"],"sourcesContent":[null],"mappings":";;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,GAAA,IAAAC,WAAA,CAAAC,SAAA;EAAAC,KAAA;AAAA,IAAAH,GAAA;AAAA,IAAAI,aAAA;AAAAC,MAAA,CAAAC,OAAA,GAAAP,YAAc,CAAAK,aAAA","ignoreList":[]}
@@ -0,0 +1,95 @@
1
+ import * as React from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+ function createContext(rootComponentName, defaultContext) {
4
+ const Context = React.createContext(defaultContext);
5
+ function Provider(props) {
6
+ const {
7
+ children,
8
+ ...context
9
+ } = props,
10
+ value = React.useMemo(() => context, Object.values(context));
11
+ return /* @__PURE__ */jsx(Context.Provider, {
12
+ value,
13
+ children
14
+ });
15
+ }
16
+ function useContext(consumerName) {
17
+ const context = React.useContext(Context);
18
+ if (context) return context;
19
+ if (defaultContext !== void 0) return defaultContext;
20
+ throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
21
+ }
22
+ return [Provider, useContext];
23
+ }
24
+ function createContextScope(scopeName, createContextScopeDeps = []) {
25
+ let defaultContexts = [];
26
+ function createContext2(rootComponentName, defaultContext) {
27
+ const BaseContext = React.createContext(defaultContext),
28
+ index = defaultContexts.length;
29
+ defaultContexts = [...defaultContexts, defaultContext];
30
+ function Provider(props) {
31
+ const {
32
+ scope,
33
+ children,
34
+ ...context
35
+ } = props,
36
+ Context = scope?.[scopeName]?.[index] || BaseContext,
37
+ value = React.useMemo(() => context, Object.values(context));
38
+ return /* @__PURE__ */jsx(Context.Provider, {
39
+ value,
40
+ children
41
+ });
42
+ }
43
+ function useContext(consumerName, scope, options) {
44
+ const Context = scope?.[scopeName]?.[index] || BaseContext,
45
+ context = React.useContext(Context);
46
+ if (context) return context;
47
+ if (defaultContext !== void 0) return defaultContext;
48
+ const missingContextMessage = `\`${consumerName}\` must be used within \`${rootComponentName}\``;
49
+ if (options?.fallback) return options?.warn !== !1 && console.warn(missingContextMessage), options.fallback;
50
+ throw new Error(missingContextMessage);
51
+ }
52
+ return [Provider, useContext];
53
+ }
54
+ const createScope = () => {
55
+ const scopeContexts = defaultContexts.map(defaultContext => React.createContext(defaultContext));
56
+ return function (scope) {
57
+ const contexts = scope?.[scopeName] || scopeContexts;
58
+ return React.useMemo(() => ({
59
+ [`__scope${scopeName}`]: {
60
+ ...scope,
61
+ [scopeName]: contexts
62
+ }
63
+ }), [scope, contexts]);
64
+ };
65
+ };
66
+ return createScope.scopeName = scopeName, [createContext2, composeContextScopes(createScope, ...createContextScopeDeps)];
67
+ }
68
+ function composeContextScopes(...scopes) {
69
+ const baseScope = scopes[0];
70
+ if (scopes.length === 1) return baseScope;
71
+ const createScope = () => {
72
+ const scopeHooks = scopes.map(createScope2 => ({
73
+ useScope: createScope2(),
74
+ scopeName: createScope2.scopeName
75
+ }));
76
+ return function (overrideScopes) {
77
+ const nextScopes = scopeHooks.reduce((nextScopes2, {
78
+ useScope,
79
+ scopeName
80
+ }) => {
81
+ const currentScope = useScope(overrideScopes)[`__scope${scopeName}`];
82
+ return {
83
+ ...nextScopes2,
84
+ ...currentScope
85
+ };
86
+ }, {});
87
+ return React.useMemo(() => ({
88
+ [`__scope${baseScope.scopeName}`]: nextScopes
89
+ }), [nextScopes]);
90
+ };
91
+ };
92
+ return createScope.scopeName = baseScope.scopeName, createScope;
93
+ }
94
+ export { createContext, createContextScope };
95
+ //# sourceMappingURL=create-context.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["React","jsx","createContext","rootComponentName","defaultContext","Context","Provider","props","children","context","value","useMemo","Object","values","useContext","consumerName","Error","createContextScope","scopeName","createContextScopeDeps","defaultContexts","createContext2","BaseContext","index","length","scope","options","missingContextMessage","fallback","warn","console","createScope","scopeContexts","map","contexts","composeContextScopes","scopes","baseScope","scopeHooks","createScope2","useScope","overrideScopes","nextScopes","reduce","nextScopes2","currentScope"],"sources":["../../src/create-context.tsx"],"sourcesContent":[null],"mappings":"AAGA,YAAYA,KAAA,MAAW;AAkBZ,SAAAC,GAAA;AAdJ,SAASC,cACdC,iBAAA,EACAC,cAAA,EAIA;EACA,MAAMC,OAAA,GAAUL,KAAA,CAAME,aAAA,CAA4CE,cAAc;EAEhF,SAASE,SAASC,KAAA,EAAyD;IACzE,MAAM;QAAEC,QAAA;QAAU,GAAGC;MAAQ,IAAIF,KAAA;MAG3BG,KAAA,GAAQV,KAAA,CAAMW,OAAA,CAAQ,MAAMF,OAAA,EAASG,MAAA,CAAOC,MAAA,CAAOJ,OAAO,CAAC;IACjE,OAAO,eAAAR,GAAA,CAACI,OAAA,CAAQC,QAAA,EAAR;MAAiBI,KAAA;MAAeF;IAAA,CAAS;EACnD;EAEA,SAASM,WAAWC,YAAA,EAA0D;IAC5E,MAAMN,OAAA,GAAUT,KAAA,CAAMc,UAAA,CAAWT,OAAO;IACxC,IAAII,OAAA,EAAS,OAAOA,OAAA;IACpB,IAAIL,cAAA,KAAmB,QAAW,OAAOA,cAAA;IAEzC,MAAM,IAAIY,KAAA,CAAM,KAAKD,YAAY,4BAA4BZ,iBAAiB,IAAI;EACpF;EAEA,OAAO,CAACG,QAAA,EAAUQ,UAAU;AAC9B;AAeO,SAASG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AU0B,SAAA,CAAUnB,SAAS,EAAE,GAAGwB;MAAW,IACvD,CAACA,UAAU,CACb;IACF;EACF;EAEA,OAAAX,WAAA,CAAYb,SAAA,GAAYmB,SAAA,CAAUnB,SAAA,EAC3Ba,WAAA;AACT","ignoreList":[]}
@@ -0,0 +1,113 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import * as React from "react";
3
+ function createContext(rootComponentName, defaultContext) {
4
+ var Context = /* @__PURE__ */React.createContext(defaultContext);
5
+ function Provider(props) {
6
+ var {
7
+ children,
8
+ ...context
9
+ } = props,
10
+ value = React.useMemo(function () {
11
+ return context;
12
+ }, Object.values(context));
13
+ return /* @__PURE__ */_jsx(Context.Provider, {
14
+ value,
15
+ children
16
+ });
17
+ }
18
+ function useContext(consumerName) {
19
+ var context = React.useContext(Context);
20
+ if (context) return context;
21
+ if (defaultContext !== void 0) return defaultContext;
22
+ throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
23
+ }
24
+ return [Provider, useContext];
25
+ }
26
+ function createContextScope(scopeName) {
27
+ var createContextScopeDeps = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [],
28
+ defaultContexts = [];
29
+ function createContext2(rootComponentName, defaultContext) {
30
+ var BaseContext = /* @__PURE__ */React.createContext(defaultContext),
31
+ index = defaultContexts.length;
32
+ defaultContexts = [...defaultContexts, defaultContext];
33
+ function Provider(props) {
34
+ var _scope_scopeName,
35
+ {
36
+ scope,
37
+ children,
38
+ ...context
39
+ } = props,
40
+ Context = (scope == null || (_scope_scopeName = scope[scopeName]) === null || _scope_scopeName === void 0 ? void 0 : _scope_scopeName[index]) || BaseContext,
41
+ value = React.useMemo(function () {
42
+ return context;
43
+ }, Object.values(context));
44
+ return /* @__PURE__ */_jsx(Context.Provider, {
45
+ value,
46
+ children
47
+ });
48
+ }
49
+ function useContext(consumerName, scope, options) {
50
+ var _scope_scopeName,
51
+ Context = (scope == null || (_scope_scopeName = scope[scopeName]) === null || _scope_scopeName === void 0 ? void 0 : _scope_scopeName[index]) || BaseContext,
52
+ context = React.useContext(Context);
53
+ if (context) return context;
54
+ if (defaultContext !== void 0) return defaultContext;
55
+ var missingContextMessage = `\`${consumerName}\` must be used within \`${rootComponentName}\``;
56
+ if (options?.fallback) return options?.warn !== !1 && console.warn(missingContextMessage), options.fallback;
57
+ throw new Error(missingContextMessage);
58
+ }
59
+ return [Provider, useContext];
60
+ }
61
+ var createScope = function () {
62
+ var scopeContexts = defaultContexts.map(function (defaultContext) {
63
+ return /* @__PURE__ */React.createContext(defaultContext);
64
+ });
65
+ return function (scope) {
66
+ var contexts = scope?.[scopeName] || scopeContexts;
67
+ return React.useMemo(function () {
68
+ return {
69
+ [`__scope${scopeName}`]: {
70
+ ...scope,
71
+ [scopeName]: contexts
72
+ }
73
+ };
74
+ }, [scope, contexts]);
75
+ };
76
+ };
77
+ return createScope.scopeName = scopeName, [createContext2, composeContextScopes(createScope, ...createContextScopeDeps)];
78
+ }
79
+ function composeContextScopes() {
80
+ for (var _len = arguments.length, scopes = new Array(_len), _key = 0; _key < _len; _key++) scopes[_key] = arguments[_key];
81
+ var baseScope = scopes[0];
82
+ if (scopes.length === 1) return baseScope;
83
+ var createScope = function () {
84
+ var scopeHooks = scopes.map(function (createScope2) {
85
+ return {
86
+ useScope: createScope2(),
87
+ scopeName: createScope2.scopeName
88
+ };
89
+ });
90
+ return function (overrideScopes) {
91
+ var nextScopes = scopeHooks.reduce(function (nextScopes2, param) {
92
+ var {
93
+ useScope,
94
+ scopeName
95
+ } = param,
96
+ scopeProps = useScope(overrideScopes),
97
+ currentScope = scopeProps[`__scope${scopeName}`];
98
+ return {
99
+ ...nextScopes2,
100
+ ...currentScope
101
+ };
102
+ }, {});
103
+ return React.useMemo(function () {
104
+ return {
105
+ [`__scope${baseScope.scopeName}`]: nextScopes
106
+ };
107
+ }, [nextScopes]);
108
+ };
109
+ };
110
+ return createScope.scopeName = baseScope.scopeName, createScope;
111
+ }
112
+ export { createContext, createContextScope };
113
+ //# sourceMappingURL=create-context.native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["jsx","_jsx","React","createContext","rootComponentName","defaultContext","Context","Provider","props","children","context","value","useMemo","Object","values","useContext","consumerName","Error","createContextScope","scopeName","createContextScopeDeps","arguments","length","defaultContexts","createContext2","BaseContext","index","_scope_scopeName","scope","options","missingContextMessage","fallback","warn","console","createScope","scopeContexts","map","contexts"],"sources":["../../src/create-context.tsx"],"sourcesContent":[null],"mappings":"AAGA,SAAAA,GAAY,IAAAC,IAAA,QAAW;AAkBZ,YAAAC,KAAA;AAdJ,SAASC,cACdC,iBAAA,EACAC,cAAA,EAIA;EACA,IAAAC,OAAM,kBAAgBJ,KAAA,CAA4CC,aAAA,CAAcE,cAAA;EAEhF,SAASE,SAASC,KAAA,EAAyD;IACzE;QAAMC,QAAE;QAAA,GAAUC;MAAG,IAAQF,KAAI;MAAAG,KAG3B,GAAAT,KAAQ,CAAAU,OAAM,aAAc;QAClC,OAAOF,OAAA;MACT,GAAAG,MAAA,CAAAC,MAAA,CAAAJ,OAAA;IAEA,OAAS,eAAWT,IAAA,CAAAK,OAA0D,CAAAC,QAAA;MAC5EI,KAAM;MACNF;IACA;EAEA;EACF,SAAAM,WAAAC,YAAA;IAEA,IAAAN,OAAQ,GAAAR,KAAU,CAAAa,UAAU,CAAAT,OAAA;IAC9B,IAAAI,OAAA,SAAAA,OAAA;IAeO,IAAAL,cAAS,UACd,UACAA,cAAA;IAuBA,MAAI,IAAAY,KAAA,MAA0BD,YAAA,4BAAAZ,iBAAA;EAM9B;EAIE,QAEAG,QAAA,EAEAQ,UAAS,CAMP;AAIoB;AACZ,SACNG,kBAAcA,CAAAC,SAAO;EAAA,IACvBC,sBAAA,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,iBAAAA,SAAA;IAAAE,eAAA;EACA,SAAAC,cAAOA,CAAApB,iBAAS,EAAAC,cAAS,EAAe;IAC1C,IAAAoB,WAAA,kBAAAvB,KAAA,C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,GAAWZ,eAAU,CAAAa,GAAA,WAAA/B,cAAA;MAEhC,OAAM,eAAiCH,KAAA,CAAAC,aAAA,CAAAE,cAAA;IACrC;IAAgD,OAC9C,UAAUuB,KAAA;MACV,IAAAS,QAAW,GAAAT,KAAA,GAAAT,SAAY,KAAAgB,aAAA;MACvB,OAAAjC,KAAA,CAAAU,OAAA;QAEF,OAAO;UACL,WAAMO,SAAa;YAKjB,GAAMS,KAAA;YACN,CAAAT,SAAY,GAAAkB;UACV;QAEJ;MAAa,GACX,CACAT,KAAC,EACHS,QAAA,CACF;IACF;EAEA;EAEF,OAAAH,WAAA,CAAAf,SAAA,GAAAA,SAAA,G","ignoreList":[]}
@@ -0,0 +1,2 @@
1
+ export * from "./create-context.mjs";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":[],"sources":["../../src/index.ts"],"sourcesContent":[null],"mappings":"AAAA,cAAc","ignoreList":[]}
@@ -0,0 +1,2 @@
1
+ export * from "./create-context.mjs";
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":[],"sources":["../../src/index.ts"],"sourcesContent":[null],"mappings":"AAAA,cAAc","ignoreList":[]}
@@ -0,0 +1,2 @@
1
+ export * from "./create-context.native.js";
2
+ //# sourceMappingURL=index.native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":[],"sources":["../../src/index.ts"],"sourcesContent":[null],"mappings":"AAAA,cAAc","ignoreList":[]}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@hanzogui/create-context",
3
+ "version": "2.0.0",
4
+ "gitHead": "a49cc7ea6b93ba384e77a4880ae48ac4a5635c14",
5
+ "source": "src/index.ts",
6
+ "files": [
7
+ "src",
8
+ "types",
9
+ "dist"
10
+ ],
11
+ "type": "module",
12
+ "sideEffects": false,
13
+ "main": "dist/cjs",
14
+ "module": "dist/esm",
15
+ "types": "./types/index.d.ts",
16
+ "exports": {
17
+ "./package.json": "./package.json",
18
+ ".": {
19
+ "types": "./types/index.d.ts",
20
+ "react-native": "./dist/esm/index.native.js",
21
+ "browser": "./dist/esm/index.mjs",
22
+ "module": "./dist/esm/index.mjs",
23
+ "import": "./dist/esm/index.mjs",
24
+ "require": "./dist/cjs/index.cjs",
25
+ "default": "./dist/esm/index.mjs"
26
+ }
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "scripts": {
32
+ "build": "hanzo-gui-build",
33
+ "watch": "hanzo-gui-build --watch",
34
+ "clean": "hanzo-gui-build clean",
35
+ "clean:build": "hanzo-gui-build clean:build"
36
+ },
37
+ "devDependencies": {
38
+ "@hanzogui/build": "workspace:*",
39
+ "react": ">=19"
40
+ },
41
+ "peerDependencies": {
42
+ "react": ">=19"
43
+ }
44
+ }
@@ -0,0 +1,192 @@
1
+ // from radix
2
+ // https://github.com/radix-ui/primitives/blob/main/packages/react/context/src/createContext.tsx
3
+
4
+ import * as React from 'react'
5
+
6
+ export type ScopedProps<P, K extends string> = P & { [Key in `__scope${K}`]?: Scope }
7
+
8
+ export function createContext<ContextValueType extends object | null>(
9
+ rootComponentName: string,
10
+ defaultContext?: ContextValueType
11
+ ): readonly [
12
+ (props: ContextValueType & { children: React.ReactNode }) => React.JSX.Element,
13
+ (consumerName: string) => Exclude<ContextValueType | undefined, undefined>,
14
+ ] {
15
+ const Context = React.createContext<ContextValueType | undefined>(defaultContext)
16
+
17
+ function Provider(props: ContextValueType & { children: React.ReactNode }) {
18
+ const { children, ...context } = props
19
+ // Only re-memoize when prop values change
20
+
21
+ const value = React.useMemo(() => context, Object.values(context)) as ContextValueType
22
+ return <Context.Provider value={value}>{children}</Context.Provider>
23
+ }
24
+
25
+ function useContext(consumerName: string): Exclude<typeof context, undefined> {
26
+ const context = React.useContext(Context)
27
+ if (context) return context as any
28
+ if (defaultContext !== undefined) return defaultContext as any
29
+ // if a defaultContext wasn't specified, it's a required context.
30
+ throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``)
31
+ }
32
+
33
+ return [Provider, useContext] as const
34
+ }
35
+
36
+ /* -------------------------------------------------------------------------------------------------
37
+ * createContextScope
38
+ * -----------------------------------------------------------------------------------------------*/
39
+
40
+ type ScopeHook = (scope: Scope) => { [__scopeProp: string]: Scope }
41
+
42
+ export type Scope<C = any> = { [scopeName: string]: React.Context<C>[] } | undefined
43
+
44
+ export interface CreateScope {
45
+ scopeName: string
46
+ (): ScopeHook
47
+ }
48
+
49
+ export function createContextScope(
50
+ scopeName: string,
51
+ createContextScopeDeps: CreateScope[] = []
52
+ ): readonly [
53
+ <ContextValueType extends object | null>(
54
+ rootComponentName: string,
55
+ defaultContext?: ContextValueType
56
+ ) => readonly [
57
+ (
58
+ props: ContextValueType & {
59
+ scope: Scope<ContextValueType>
60
+ children: React.ReactNode
61
+ }
62
+ ) => import('react/jsx-runtime').JSX.Element,
63
+ (
64
+ consumerName: string,
65
+ scope: Scope<ContextValueType | undefined>,
66
+ options?: {
67
+ warn?: boolean
68
+ fallback?: Partial<ContextValueType>
69
+ }
70
+ ) => ContextValueType,
71
+ ],
72
+ CreateScope,
73
+ ] {
74
+ let defaultContexts: any[] = []
75
+
76
+ /* -----------------------------------------------------------------------------------------------
77
+ * createContext
78
+ * ---------------------------------------------------------------------------------------------*/
79
+
80
+ function createContext<ContextValueType extends object | null>(
81
+ rootComponentName: string,
82
+ defaultContext?: ContextValueType
83
+ ) {
84
+ const BaseContext = React.createContext<ContextValueType | undefined>(defaultContext)
85
+ const index = defaultContexts.length
86
+ defaultContexts = [...defaultContexts, defaultContext]
87
+
88
+ function Provider(
89
+ props: ContextValueType & {
90
+ scope: Scope<ContextValueType>
91
+ children: React.ReactNode
92
+ }
93
+ ) {
94
+ const { scope, children, ...context } = props
95
+ const Context = scope?.[scopeName]?.[index] || BaseContext
96
+ // Only re-memoize when prop values change
97
+
98
+ const value = React.useMemo(
99
+ () => context,
100
+ Object.values(context)
101
+ ) as ContextValueType
102
+ return <Context.Provider value={value}>{children}</Context.Provider>
103
+ }
104
+
105
+ function useContext(
106
+ consumerName: string,
107
+ scope: Scope<ContextValueType | undefined>,
108
+ options?: {
109
+ warn?: boolean
110
+ fallback?: Partial<ContextValueType>
111
+ }
112
+ ) {
113
+ const Context = scope?.[scopeName]?.[index] || BaseContext
114
+ const context = React.useContext(Context)
115
+ if (context) return context
116
+ // if a defaultContext wasn't specified, it's a required context.
117
+ if (defaultContext !== undefined) return defaultContext
118
+ const missingContextMessage = `\`${consumerName}\` must be used within \`${rootComponentName}\``
119
+ // fallback can be given per-hook as well
120
+ if (options?.fallback) {
121
+ if (options?.warn !== false) {
122
+ console.warn(missingContextMessage)
123
+ }
124
+ return options.fallback as ContextValueType
125
+ }
126
+ throw new Error(missingContextMessage)
127
+ }
128
+
129
+ return [Provider, useContext] as const
130
+ }
131
+
132
+ /* -----------------------------------------------------------------------------------------------
133
+ * createScope
134
+ * ---------------------------------------------------------------------------------------------*/
135
+
136
+ const createScope: CreateScope = () => {
137
+ const scopeContexts = defaultContexts.map((defaultContext) => {
138
+ return React.createContext(defaultContext)
139
+ })
140
+ return function useScope(scope: Scope) {
141
+ const contexts = scope?.[scopeName] || scopeContexts
142
+ return React.useMemo(
143
+ () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),
144
+ [scope, contexts]
145
+ )
146
+ }
147
+ }
148
+
149
+ createScope.scopeName = scopeName
150
+
151
+ return [
152
+ createContext,
153
+ composeContextScopes(createScope, ...createContextScopeDeps),
154
+ ] as const
155
+ }
156
+
157
+ /* -------------------------------------------------------------------------------------------------
158
+ * composeContextScopes
159
+ * -----------------------------------------------------------------------------------------------*/
160
+
161
+ function composeContextScopes(...scopes: CreateScope[]) {
162
+ const baseScope = scopes[0]
163
+ if (scopes.length === 1) return baseScope
164
+
165
+ const createScope: CreateScope = () => {
166
+ const scopeHooks = scopes.map((createScope) => ({
167
+ useScope: createScope(),
168
+ scopeName: createScope.scopeName,
169
+ }))
170
+
171
+ return function useComposedScopes(overrideScopes) {
172
+ const nextScopes = scopeHooks.reduce((nextScopes, { useScope, scopeName }) => {
173
+ // We are calling a hook inside a callback which React warns against to avoid inconsistent
174
+ // renders, however, scoping doesn't have render side effects so we ignore the rule.
175
+
176
+ const scopeProps = useScope(overrideScopes)
177
+ const currentScope = scopeProps[`__scope${scopeName}`]
178
+ return { ...nextScopes, ...currentScope }
179
+ }, {})
180
+
181
+ return React.useMemo(
182
+ () => ({ [`__scope${baseScope.scopeName}`]: nextScopes }),
183
+ [nextScopes]
184
+ )
185
+ }
186
+ }
187
+
188
+ createScope.scopeName = baseScope.scopeName
189
+ return createScope
190
+ }
191
+
192
+ /* -----------------------------------------------------------------------------------------------*/
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './create-context'
@@ -0,0 +1,28 @@
1
+ import * as React from "react";
2
+ export type ScopedProps<
3
+ P,
4
+ K extends string
5
+ > = P & { [Key in `__scope${K}`]? : Scope };
6
+ export declare function createContext<ContextValueType extends object | null>(rootComponentName: string, defaultContext?: ContextValueType): readonly [(props: ContextValueType & {
7
+ children: React.ReactNode;
8
+ }) => React.JSX.Element, (consumerName: string) => Exclude<ContextValueType | undefined, undefined>];
9
+ type ScopeHook = (scope: Scope) => {
10
+ [__scopeProp: string]: Scope;
11
+ };
12
+ export type Scope<C = any> = {
13
+ [scopeName: string]: React.Context<C>[];
14
+ } | undefined;
15
+ export interface CreateScope {
16
+ scopeName: string;
17
+ (): ScopeHook;
18
+ }
19
+ export declare function createContextScope(scopeName: string, createContextScopeDeps?: CreateScope[]): readonly [<ContextValueType extends object | null>(rootComponentName: string, defaultContext?: ContextValueType) => readonly [(props: ContextValueType & {
20
+ scope: Scope<ContextValueType>;
21
+ children: React.ReactNode;
22
+ }) => import("react/jsx-runtime").JSX.Element, (consumerName: string, scope: Scope<ContextValueType | undefined>, options?: {
23
+ warn?: boolean;
24
+ fallback?: Partial<ContextValueType>;
25
+ }) => ContextValueType], CreateScope];
26
+ export {};
27
+
28
+ //# sourceMappingURL=create-context.d.ts.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "mappings": "AAGA,YAAY,WAAW;AAEvB,YAAY;CAAY;CAAG;IAAoB,OAAO,iBAAiB,QAAO;AAE9E,OAAO,iBAAS,cAAc,wCAC5B,2BACA,iBAAiB,8BAEhB,OAAO,mBAAmB;CAAE,UAAU,MAAM;MAAgB,MAAM,IAAI,UACtE,yBAAyB,QAAQ;KA2B/B,aAAa,OAAO,UAAU;wBAAyB;;AAE5D,YAAY,MAAM,WAAW;sBAAuB,MAAM,QAAQ;;AAElE,iBAAiB,YAAY;CAC3B;KACI;;AAGN,OAAO,iBAAS,mBACd,mBACA,yBAAwB,2BAEvB,wCACC,2BACA,iBAAiB,gCAGf,OAAO,mBAAmB;CACxB,OAAO,MAAM;CACb,UAAU,MAAM;aAER,mCAEV,sBACA,OAAO,MAAM,+BACb,UAAU;CACR;CACA,WAAW,QAAQ;MAElB,mBAEP",
3
+ "names": [],
4
+ "sources": [
5
+ "src/create-context.tsx"
6
+ ],
7
+ "version": 3,
8
+ "sourcesContent": [
9
+ "// from radix\n// https://github.com/radix-ui/primitives/blob/main/packages/react/context/src/createContext.tsx\n\nimport * as React from 'react'\n\nexport type ScopedProps<P, K extends string> = P & { [Key in `__scope${K}`]?: Scope }\n\nexport function createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n): readonly [\n (props: ContextValueType & { children: React.ReactNode }) => React.JSX.Element,\n (consumerName: string) => Exclude<ContextValueType | undefined, undefined>,\n] {\n const Context = React.createContext<ContextValueType | undefined>(defaultContext)\n\n function Provider(props: ContextValueType & { children: React.ReactNode }) {\n const { children, ...context } = props\n // Only re-memoize when prop values change\n\n const value = React.useMemo(() => context, Object.values(context)) as ContextValueType\n return <Context.Provider value={value}>{children}</Context.Provider>\n }\n\n function useContext(consumerName: string): Exclude<typeof context, undefined> {\n const context = React.useContext(Context)\n if (context) return context as any\n if (defaultContext !== undefined) return defaultContext as any\n // if a defaultContext wasn't specified, it's a required context.\n throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``)\n }\n\n return [Provider, useContext] as const\n}\n\n/* -------------------------------------------------------------------------------------------------\n * createContextScope\n * -----------------------------------------------------------------------------------------------*/\n\ntype ScopeHook = (scope: Scope) => { [__scopeProp: string]: Scope }\n\nexport type Scope<C = any> = { [scopeName: string]: React.Context<C>[] } | undefined\n\nexport interface CreateScope {\n scopeName: string\n (): ScopeHook\n}\n\nexport function createContextScope(\n scopeName: string,\n createContextScopeDeps: CreateScope[] = []\n): readonly [\n <ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n ) => readonly [\n (\n props: ContextValueType & {\n scope: Scope<ContextValueType>\n children: React.ReactNode\n }\n ) => import('react/jsx-runtime').JSX.Element,\n (\n consumerName: string,\n scope: Scope<ContextValueType | undefined>,\n options?: {\n warn?: boolean\n fallback?: Partial<ContextValueType>\n }\n ) => ContextValueType,\n ],\n CreateScope,\n] {\n let defaultContexts: any[] = []\n\n /* -----------------------------------------------------------------------------------------------\n * createContext\n * ---------------------------------------------------------------------------------------------*/\n\n function createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n ) {\n const BaseContext = React.createContext<ContextValueType | undefined>(defaultContext)\n const index = defaultContexts.length\n defaultContexts = [...defaultContexts, defaultContext]\n\n function Provider(\n props: ContextValueType & {\n scope: Scope<ContextValueType>\n children: React.ReactNode\n }\n ) {\n const { scope, children, ...context } = props\n const Context = scope?.[scopeName]?.[index] || BaseContext\n // Only re-memoize when prop values change\n\n const value = React.useMemo(\n () => context,\n Object.values(context)\n ) as ContextValueType\n return <Context.Provider value={value}>{children}</Context.Provider>\n }\n\n function useContext(\n consumerName: string,\n scope: Scope<ContextValueType | undefined>,\n options?: {\n warn?: boolean\n fallback?: Partial<ContextValueType>\n }\n ) {\n const Context = scope?.[scopeName]?.[index] || BaseContext\n const context = React.useContext(Context)\n if (context) return context\n // if a defaultContext wasn't specified, it's a required context.\n if (defaultContext !== undefined) return defaultContext\n const missingContextMessage = `\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``\n // fallback can be given per-hook as well\n if (options?.fallback) {\n if (options?.warn !== false) {\n console.warn(missingContextMessage)\n }\n return options.fallback as ContextValueType\n }\n throw new Error(missingContextMessage)\n }\n\n return [Provider, useContext] as const\n }\n\n /* -----------------------------------------------------------------------------------------------\n * createScope\n * ---------------------------------------------------------------------------------------------*/\n\n const createScope: CreateScope = () => {\n const scopeContexts = defaultContexts.map((defaultContext) => {\n return React.createContext(defaultContext)\n })\n return function useScope(scope: Scope) {\n const contexts = scope?.[scopeName] || scopeContexts\n return React.useMemo(\n () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),\n [scope, contexts]\n )\n }\n }\n\n createScope.scopeName = scopeName\n\n return [\n createContext,\n composeContextScopes(createScope, ...createContextScopeDeps),\n ] as const\n}\n\n/* -------------------------------------------------------------------------------------------------\n * composeContextScopes\n * -----------------------------------------------------------------------------------------------*/\n\nfunction composeContextScopes(...scopes: CreateScope[]) {\n const baseScope = scopes[0]\n if (scopes.length === 1) return baseScope\n\n const createScope: CreateScope = () => {\n const scopeHooks = scopes.map((createScope) => ({\n useScope: createScope(),\n scopeName: createScope.scopeName,\n }))\n\n return function useComposedScopes(overrideScopes) {\n const nextScopes = scopeHooks.reduce((nextScopes, { useScope, scopeName }) => {\n // We are calling a hook inside a callback which React warns against to avoid inconsistent\n // renders, however, scoping doesn't have render side effects so we ignore the rule.\n\n const scopeProps = useScope(overrideScopes)\n const currentScope = scopeProps[`__scope${scopeName}`]\n return { ...nextScopes, ...currentScope }\n }, {})\n\n return React.useMemo(\n () => ({ [`__scope${baseScope.scopeName}`]: nextScopes }),\n [nextScopes]\n )\n }\n }\n\n createScope.scopeName = baseScope.scopeName\n return createScope\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n"
10
+ ]
11
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./create-context";
2
+
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "mappings": "AAAA,cAAc",
3
+ "names": [],
4
+ "sources": [
5
+ "src/index.ts"
6
+ ],
7
+ "version": 3,
8
+ "sourcesContent": [
9
+ "export * from './create-context'\n"
10
+ ]
11
+ }