@ptolemy2002/react-proxy-context 1.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.
Files changed (3) hide show
  1. package/README.md +83 -0
  2. package/index.js +124 -0
  3. package/package.json +44 -0
package/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # React Proxy Context
2
+ This library is a solution for React that uses Javascript Proxies to allow React context consumers to listen to mutations as well as reassignments. Another benefit is that you can listen to the mutation of only specific properties. I find that many consider this style more intuitive to work with, though it is considered bad practice by others.
3
+
4
+ The functions are not exported as default, so you can import them in one of the following ways:
5
+ ```
6
+ // ES6
7
+ import { functionName } from '@ptolemy2002/react-utils';
8
+ // CommonJS
9
+ const { functionName } = require('@ptolemy2002/react-utils');
10
+ ```
11
+
12
+ ## Functions
13
+ The following functions are available in the library:
14
+
15
+ ### createProxyContext
16
+ #### Description
17
+ Creates a new instance of the ProxyContext, essentially to be used as the context type, with the specified default value and name. This is effectively just the normal React createContext function, but with a check to ensure that the browser supports Proxies.
18
+
19
+ #### Parameters
20
+ - `defaultValue` (Object): The default value of the context. This is what is reported when the context is not provided.
21
+ - `name` (String): The name of the context. This is used for debugging purposes.
22
+
23
+ #### Returns
24
+ Object - The ProxyContext object, which is a React context object.
25
+
26
+ ## Components
27
+ The following components are available in the library:
28
+
29
+ ### ProxyContextProvider
30
+ #### Description
31
+ A component that provides context of the specified class to its children using proxies. `useProxyContext` can only be used to access the context provided by this component.
32
+
33
+ #### Props
34
+ - `contextClass` (Object): The class of the context to provide. This is the class that was created using `createProxyContext`.
35
+ - `value` (Object): The value of the context. This is what is reported when the context is not provided.
36
+ - `onChange` (Function): A function that is called whenever the context is changed. The first parameter is the property that was changed (null if it was reassignment), the second parameter is the current value of the context, and the third parameter is the previous value of the context. This is useful for listening to changes in the provider's parent component.
37
+ - `proxyRef` (Object): A ref object that is assigned the proxy object of the context. This is useful for accessing the proxy object directly by the provider's parent component.
38
+
39
+ ## Hooks
40
+ The following hooks are available in the library:
41
+
42
+ ### useProxyContext
43
+ A hook that uses the context provided by the `ProxyContextProvider` component. This hook also provides options to choose which properties to listen to and whether to listen to full reassignments.
44
+
45
+ #### Parameters
46
+ - `contextClass` (Object): The class of the context to use. This is the class that was created using `createProxyContext`.
47
+ - `deps` (Array): An array of dependencies to listen to. If any of these properties on the context change, the hook will re-render. If this is falsy, any mutation will trigger a re-render. You can also specify a function that returns a boolean to determine whether to re-render (provided with the same arguments as `onChange` would be and a 4th argument that is the current value of the context).
48
+ - `listenReinit` (Boolean): Whether to listen to full reassignments of the context and re-render when they occur. Default is `true`.
49
+
50
+ #### Returns
51
+ Array - An array with the first element being the current value of the context and the second element being a setter function to reassign the context.
52
+
53
+ ## Meta
54
+ This is a React Library Created by Ptolemy2002's [cra-template-react-library](https://www.npmjs.com/package/@ptolemy2002/cra-template-react-library) template in combination with [create-react-app](https://www.npmjs.com/package/create-react-app). It contains methods of building and publishing your library to npm.
55
+ For now, the library makes use of React 18 and does not use TypeScript.
56
+
57
+ ## Peer Dependencies
58
+ These should be installed in order to use the library, as npm does not automatically add peer dependencies to your project.
59
+ - @types/react: ^18.3.3
60
+ - @types/react-dom: ^18.3.0
61
+ - react: ^18.3.1
62
+ - react-dom: ^18.3.1
63
+ - @types/is-callable: ^1.1.2
64
+ - is-callable: ^1.2.7
65
+ - nanoid: ^5.0.7
66
+ - @ptolemy2002/react-mount-effects: ^1.1.4
67
+ - @ptolemy2002/react-force-rerender: ^1.0.4
68
+ - @ptolemy2002/js-utils: ^1.0.3
69
+
70
+ ## Commands
71
+ The following commands exist in the project:
72
+
73
+ - `npm run uninstall` - Uninstalls all dependencies for the library
74
+ - `npm run reinstall` - Uninstalls and then Reinstalls all dependencies for the library
75
+ - `npm run example-uninstall` - Uninstalls all dependencies for the example app
76
+ - `npm run example-install` - Installs all dependencies for the example app
77
+ - `npm run example-reinstall` - Uninstalls and then Reinstalls all dependencies for the example app
78
+ - `npm run example-start` - Starts the example app after building the library
79
+ - `npm run build` - Builds the library
80
+ - `npm run release` - Publishes the library to npm without changing the version
81
+ - `npm run release-patch` - Publishes the library to npm with a patch version bump
82
+ - `npm run release-minor` - Publishes the library to npm with a minor version bump
83
+ - `npm run release-major` - Publishes the library to npm with a major version bump
package/index.js ADDED
@@ -0,0 +1,124 @@
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
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/index.js
30
+ var src_exports = {};
31
+ __export(src_exports, {
32
+ ProxyContextProvider: () => ProxyContextProvider,
33
+ createProxyContext: () => createProxyContext,
34
+ useProxyContext: () => useProxyContext
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+ var import_react = __toESM(require("react"));
38
+ var import_nanoid = require("nanoid");
39
+ var import_is_callable = __toESM(require("is-callable"));
40
+ var import_react_force_rerender = __toESM(require("@ptolemy2002/react-force-rerender"));
41
+ var import_react_mount_effects = require("@ptolemy2002/react-mount-effects");
42
+ var import_js_utils = require("@ptolemy2002/js-utils");
43
+ function createProxyContext(defaultValue, name) {
44
+ if (typeof Proxy == "undefined") throw new Error("Proxy is not supported in this environment.");
45
+ const context = (0, import_react.createContext)(defaultValue);
46
+ context.name = name;
47
+ return context;
48
+ }
49
+ function ProxyContextProvider({ contextClass, children, value, onChange, proxyRef }) {
50
+ const changeSubscribers = (0, import_react.useRef)({});
51
+ const objRef = (0, import_react.useRef)();
52
+ const contextRef = (0, import_react.useRef)({});
53
+ const subscribe = (0, import_react.useCallback)((callback, deps, listenReinit = true) => {
54
+ const id = (0, import_nanoid.nanoid)();
55
+ changeSubscribers.current[id] = {
56
+ deps,
57
+ callback,
58
+ listenReinit
59
+ };
60
+ return id;
61
+ }, []);
62
+ const unsubscribe = (0, import_react.useCallback)((id) => {
63
+ delete changeSubscribers.current[id];
64
+ }, []);
65
+ const set = (0, import_react.useCallback)((newObj) => {
66
+ if (newObj !== objRef.current) {
67
+ const prevObj = objRef.current;
68
+ if (!(0, import_js_utils.isNullOrUndefined)(newObj)) {
69
+ objRef.current = new Proxy(newObj, {
70
+ get: function(target, prop) {
71
+ const result = Reflect.get(target, prop, objRef.current);
72
+ if ((0, import_is_callable.default)(result)) {
73
+ return result.bind(objRef.current);
74
+ } else {
75
+ return result;
76
+ }
77
+ },
78
+ set: function(target, prop, value2) {
79
+ const prevValue = target[prop];
80
+ Reflect.set(target, prop, value2, objRef.current);
81
+ value2 = target[prop];
82
+ Object.values(changeSubscribers.current).forEach((subscriber) => {
83
+ if (!subscriber.deps || subscriber.deps.includes(prop) && prevValue !== value2 || subscriber.deps.some((subProp) => (0, import_is_callable.default)(subProp) && subProp(prop, value2, prevValue, objRef.current))) {
84
+ subscriber.callback(prop, value2, prevValue);
85
+ }
86
+ });
87
+ if ((0, import_is_callable.default)(onChange)) onChange(prop, value2, prevValue);
88
+ return true;
89
+ }
90
+ });
91
+ }
92
+ Object.values(changeSubscribers.current).forEach((subscriber) => {
93
+ if (subscriber.listenReinit) subscriber.callback(null, objRef.current, prevObj);
94
+ });
95
+ proxyRef && (proxyRef.current = objRef.current);
96
+ if ((0, import_is_callable.default)(onChange)) onChange(null, objRef.current, prevObj);
97
+ }
98
+ return objRef.current;
99
+ }, [onChange, proxyRef]);
100
+ if (objRef.current === void 0) objRef.current = set(value);
101
+ contextRef.current.obj = objRef.current;
102
+ contextRef.current.set = set;
103
+ contextRef.current.subscribe = subscribe;
104
+ contextRef.current.unsubscribe = unsubscribe;
105
+ return /* @__PURE__ */ import_react.default.createElement(contextClass.Provider, { value: contextRef.current }, children);
106
+ }
107
+ function useProxyContext(contextClass, deps, onChange, listenReinit = true) {
108
+ const context = (0, import_react.useContext)(contextClass);
109
+ const forceRerender = (0, import_react_force_rerender.default)();
110
+ const id = (0, import_react.useRef)(null);
111
+ if (context === void 0) {
112
+ throw new Error(`No ${contextClass.name} provider found.`);
113
+ }
114
+ (0, import_react_mount_effects.useMountEffect)(() => {
115
+ id.current = context?.subscribe((prop, current, prev) => {
116
+ forceRerender();
117
+ if ((0, import_is_callable.default)(onChange)) onChange(prop, current, prev);
118
+ }, deps, listenReinit);
119
+ });
120
+ (0, import_react_mount_effects.useUnmountEffect)(() => {
121
+ context?.unsubscribe(id.current);
122
+ });
123
+ return [context?.obj, context?.set];
124
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@ptolemy2002/react-proxy-context",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "files": [
6
+ "index.js"
7
+ ],
8
+ "scripts": {
9
+ "build": "esbuild src/index.js --bundle --format=cjs --outfile=index.js --loader:.js=jsx --external:react --external:react-dom --external:@types/react --external:@types/react-dom --external:is-callable --external:nanoid --external:@ptolemy2002/react-mount-effects --external:@ptolemy2002/react-force-rerender --external:@ptolemy2002/js-utils",
10
+ "postinstall": "npx typesync",
11
+ "uninstall": "bash ./scripts/uninstall.sh",
12
+ "reinstall": "bash ./scripts/reinstall.sh",
13
+ "example-uninstall": "bash ./scripts/example-uninstall.sh",
14
+ "example-install": "bash ./scripts/example-install.sh",
15
+ "example-reinstall": "bash ./scripts/example-reinstall.sh",
16
+ "example-start": "bash ./scripts/example-start.sh",
17
+ "release": "bash ./scripts/release.sh",
18
+ "release-patch": "bash ./scripts/release.sh patch",
19
+ "release-minor": "bash ./scripts/release.sh minor",
20
+ "release-major": "bash ./scripts/release.sh major"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/Ptolemy2002/react-proxy-context",
25
+ "directory": "lib"
26
+ },
27
+ "description": "React Context with Support for Mutation with Proxies",
28
+ "license": "ISC",
29
+ "peerDependencies": {
30
+ "@types/react": "^18.3.3",
31
+ "@types/react-dom": "^18.3.0",
32
+ "react": "^18.3.1",
33
+ "react-dom": "^18.3.1",
34
+ "@types/is-callable": "^1.1.2",
35
+ "is-callable": "^1.2.7",
36
+ "nanoid": "^5.0.7",
37
+ "@ptolemy2002/react-mount-effects": "^1.1.4",
38
+ "@ptolemy2002/react-force-rerender": "^1.0.4",
39
+ "@ptolemy2002/js-utils": "^1.0.3"
40
+ },
41
+ "devDependencies": {
42
+ "esbuild": "^0.23.0"
43
+ }
44
+ }