@webkrafters/react-observable-context 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +259 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +182 -0
- package/index.js +1 -0
- package/package.json +78 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Stephen Isienyi
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
# React-Observable-Context
|
|
2
|
+
|
|
3
|
+
Observable react context - prevents an automatic total component tree re-rendering at context change.
|
|
4
|
+
|
|
5
|
+
<h4><u>Install</u></h4>
|
|
6
|
+
|
|
7
|
+
npm i -S @webkrafters/react-hoc-memo
|
|
8
|
+
|
|
9
|
+
npm install --save @webkrafters/react-hoc-memo
|
|
10
|
+
|
|
11
|
+
## API
|
|
12
|
+
|
|
13
|
+
The React-Observable-Context package exports only **2** modules namely: the **Provider** component and the **useStore** method.
|
|
14
|
+
|
|
15
|
+
The `Provider` can immediately be used as-is anywhere the React-Observable-Context is required. No React::createContext(...) nor any other preparation is required.
|
|
16
|
+
|
|
17
|
+
The `useStore` returns the context `store` object for consuming the React-Observable-Context.
|
|
18
|
+
|
|
19
|
+
The context `store` exposes **4** methods for interacting with the context namely:
|
|
20
|
+
|
|
21
|
+
* **getState**: (selector?: (state: State) => PartialState\<State\>) => PartialState\<State\>
|
|
22
|
+
|
|
23
|
+
* **resetState**: VoidFunction // resets the state to the Provider latest `value` prop.
|
|
24
|
+
|
|
25
|
+
* **setState**: (changes: PartialState\<State\>) => void
|
|
26
|
+
|
|
27
|
+
* **subscribe**: (listener: (newValue: PartialState\<State\>, oldValue: PartialState\<State\>) => void) => ***UnsubscribeFunction***
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
<i><u>tally-display.js</u></i>
|
|
32
|
+
|
|
33
|
+
import React, { useEffect, useState } from 'react';
|
|
34
|
+
import { useStore } from '@webkrafters/react-observable-context';
|
|
35
|
+
|
|
36
|
+
const TallyDisplay = () => {
|
|
37
|
+
|
|
38
|
+
const { getState, subscribe } = useStore();
|
|
39
|
+
|
|
40
|
+
const [ , setUpdateTs ] = useState();
|
|
41
|
+
|
|
42
|
+
useEffect(() => subscribe( newValue => {
|
|
43
|
+
[ 'color', 'price', 'type' ].some( k => k in newValue ) &&
|
|
44
|
+
setUpdateTs( Date.now() );
|
|
45
|
+
}), []);
|
|
46
|
+
|
|
47
|
+
useEffect(() => console.log( 'TallyDisplay component rendered.....' ));
|
|
48
|
+
|
|
49
|
+
return (
|
|
50
|
+
<table>
|
|
51
|
+
<tbody>
|
|
52
|
+
<tr><td><label>Type:</label></td><td>{ getState( s => s.type ) }</td></tr>
|
|
53
|
+
<tr><td><label>Color:</label></td><td>{ getState( s => s.color ) }</td></tr>
|
|
54
|
+
<tr><td><label>Price:</label></td><td>{ getState( s => s.price ).toFixed( 2 ) }</td></tr>
|
|
55
|
+
</tbody>
|
|
56
|
+
</table>
|
|
57
|
+
);
|
|
58
|
+
};
|
|
59
|
+
TallyDisplay.displayName = 'TallyDisplay';
|
|
60
|
+
|
|
61
|
+
export default TallyDisplay;
|
|
62
|
+
|
|
63
|
+
<i><u>editor.js</u></i>
|
|
64
|
+
|
|
65
|
+
import React, { useCallback, useEffect, useRef } from 'react';
|
|
66
|
+
import { useStore } from '@webkrafters/react-observable-context';
|
|
67
|
+
|
|
68
|
+
const Editor = () => {
|
|
69
|
+
|
|
70
|
+
const { setState } = useStore();
|
|
71
|
+
|
|
72
|
+
const priceInputRef = useRef();
|
|
73
|
+
const colorInputRef = useRef();
|
|
74
|
+
const typeInputRef = useRef();
|
|
75
|
+
|
|
76
|
+
const updatePrice = useCallback(() => {
|
|
77
|
+
setState({ price: Number( priceInputRef.current.value ) });
|
|
78
|
+
}, []);
|
|
79
|
+
|
|
80
|
+
const updateColor = useCallback(() => {
|
|
81
|
+
setState({ color: colorInputRef.current.value });
|
|
82
|
+
}, []);
|
|
83
|
+
|
|
84
|
+
const updateType = useCallback(() => {
|
|
85
|
+
setState({ type: typeInputRef.current.value });
|
|
86
|
+
}, []);
|
|
87
|
+
|
|
88
|
+
useEffect(() => console.log( 'Editor component rendered.....' ));
|
|
89
|
+
|
|
90
|
+
return (
|
|
91
|
+
<fieldset style={{ margin: '10px 0' }}>
|
|
92
|
+
<legend>Editor</legend>
|
|
93
|
+
<div style={{ margin: '10px 0' }}>
|
|
94
|
+
<label>New Price: <input ref={ priceInputRef } /></label>
|
|
95
|
+
{ ' ' }
|
|
96
|
+
<button onClick={ updatePrice }>update price</button>
|
|
97
|
+
</div>
|
|
98
|
+
<div style={{ margin: '10px 0' }}>
|
|
99
|
+
<label>New Color: <input ref={ colorInputRef } /></label>
|
|
100
|
+
{ ' ' }
|
|
101
|
+
<button onClick={ updateColor }>update color</button>
|
|
102
|
+
</div>
|
|
103
|
+
<div style={{ margin: '10px 0' }}>
|
|
104
|
+
<label>New Type: <input ref={ typeInputRef } /></label>
|
|
105
|
+
{ ' ' }
|
|
106
|
+
<button onClick={ updateType }>update type</button>
|
|
107
|
+
</div>
|
|
108
|
+
</fieldset>
|
|
109
|
+
);
|
|
110
|
+
};
|
|
111
|
+
Editor.displayName = 'Editor';
|
|
112
|
+
|
|
113
|
+
export default Editor;
|
|
114
|
+
|
|
115
|
+
<i><u>product-description.js</u></i>
|
|
116
|
+
|
|
117
|
+
import React, { useEffect, useState } from 'react';
|
|
118
|
+
import { useStore } from '@webkrafters/react-observable-context';
|
|
119
|
+
|
|
120
|
+
const ProductDescription = () => {
|
|
121
|
+
|
|
122
|
+
const store = useStore();
|
|
123
|
+
|
|
124
|
+
const [ , setUpdateTs ] = useState();
|
|
125
|
+
|
|
126
|
+
useEffect(() => store.subscribe( newValue => {
|
|
127
|
+
( 'color' in newValue || 'type' in newValue ) &&
|
|
128
|
+
setUpdateTs( Date.now() );
|
|
129
|
+
} ), []);
|
|
130
|
+
|
|
131
|
+
useEffect(() => console.log( 'ProductDescription component rendered.....' ));
|
|
132
|
+
|
|
133
|
+
const color = store.getState( s => s.color );
|
|
134
|
+
const type = store.getState( s => s.type );
|
|
135
|
+
|
|
136
|
+
return (
|
|
137
|
+
<div style={{ fontSize: 24 }}>
|
|
138
|
+
<strong>Description:</strong> { color } { type }
|
|
139
|
+
</div>
|
|
140
|
+
);
|
|
141
|
+
};
|
|
142
|
+
ProductDescription.displayName = 'ProductDescription';
|
|
143
|
+
|
|
144
|
+
export default ProductDescription;
|
|
145
|
+
|
|
146
|
+
<i><u>price-sticker.js</u></i>
|
|
147
|
+
|
|
148
|
+
import React, { useEffect, useState } from 'react'
|
|
149
|
+
import { useStore } from '@webkrafters/react-observable-context';
|
|
150
|
+
|
|
151
|
+
const PriceSticker = () => {
|
|
152
|
+
|
|
153
|
+
const store = useStore();
|
|
154
|
+
|
|
155
|
+
const [ price, setPrice ] = useState(() => store.getState( s => s.price ));
|
|
156
|
+
|
|
157
|
+
useEffect(() => store.subscribe( newValue => {
|
|
158
|
+
'price' in newValue && setPrice( newValue.price );
|
|
159
|
+
} ), []);
|
|
160
|
+
|
|
161
|
+
useEffect(() => console.log( 'PriceSticker component rendered.....' ));
|
|
162
|
+
|
|
163
|
+
return (
|
|
164
|
+
<div style={{ fontSize: 36, fontWeight: 800 }}>
|
|
165
|
+
${ price.toFixed( 2 ) }
|
|
166
|
+
</div>
|
|
167
|
+
);
|
|
168
|
+
};
|
|
169
|
+
PriceSticker.displayName = 'PriceSticker';
|
|
170
|
+
|
|
171
|
+
export default PriceSticker;
|
|
172
|
+
|
|
173
|
+
<i><u>product.js</u></i>
|
|
174
|
+
|
|
175
|
+
import React, { useCallback, useEffect, useState } from 'react';
|
|
176
|
+
import { Provider } from '@webkrafters/react-observable-context';
|
|
177
|
+
|
|
178
|
+
import Editor from './editor';
|
|
179
|
+
import PriceSticker from './price-sticker';
|
|
180
|
+
import ProductDescription from './product-description';
|
|
181
|
+
import TallyDisplay from './tally-display';
|
|
182
|
+
|
|
183
|
+
const Product = ({ type }) => {
|
|
184
|
+
|
|
185
|
+
const [ state, setState ] = useState(() => ({
|
|
186
|
+
color: 'Burgundy',
|
|
187
|
+
price: 22.5,
|
|
188
|
+
type
|
|
189
|
+
}));
|
|
190
|
+
|
|
191
|
+
useEffect(() => {
|
|
192
|
+
setState({ type }); // use this to update only the changed state
|
|
193
|
+
// setState({ ...state, type }); // this will reset the context internal state
|
|
194
|
+
}, [ type ]);
|
|
195
|
+
|
|
196
|
+
const overridePricing = useCallback( e => setState({ price: Number( e.target.value ) }), [] );
|
|
197
|
+
|
|
198
|
+
return (
|
|
199
|
+
<div>
|
|
200
|
+
<div style={{ marginBottom: 10 }}>
|
|
201
|
+
<label>$ <input onKeyUp={ overridePricing } placeholder="override price here..."/></label>
|
|
202
|
+
</div>
|
|
203
|
+
<Provider value={ state }>
|
|
204
|
+
<div style={{
|
|
205
|
+
borderBottom: '1px solid #333',
|
|
206
|
+
marginBottom: 10,
|
|
207
|
+
paddingBottom: 5
|
|
208
|
+
}}>
|
|
209
|
+
<Editor />
|
|
210
|
+
<TallyDisplay />
|
|
211
|
+
</div>
|
|
212
|
+
<ProductDescription />
|
|
213
|
+
<PriceSticker />
|
|
214
|
+
</Provider>
|
|
215
|
+
</div>
|
|
216
|
+
);
|
|
217
|
+
};
|
|
218
|
+
Product.displayName = 'Product';
|
|
219
|
+
|
|
220
|
+
export default Product;
|
|
221
|
+
|
|
222
|
+
<i><u>app.js</u></i>
|
|
223
|
+
|
|
224
|
+
import React, { useCallback, useState } from 'react';
|
|
225
|
+
|
|
226
|
+
import Product from './product';
|
|
227
|
+
|
|
228
|
+
const App = () => {
|
|
229
|
+
|
|
230
|
+
const [ productType, setProductType ] = useState( 'Calculator' );
|
|
231
|
+
|
|
232
|
+
const updateType = useCallback( e => setProductType( e.target.value ), [] );
|
|
233
|
+
|
|
234
|
+
return (
|
|
235
|
+
<div className="App">
|
|
236
|
+
<h1>Demo</h1>
|
|
237
|
+
<h2>A contrived product app.</h2>
|
|
238
|
+
<div style={{ marginBottom: 10 }}>
|
|
239
|
+
<label>Type: <input onKeyUp={ updateType } placeholder="override product type here..." /></label>
|
|
240
|
+
</div>
|
|
241
|
+
<Product type={ productType } />
|
|
242
|
+
</div>
|
|
243
|
+
);
|
|
244
|
+
|
|
245
|
+
};
|
|
246
|
+
App.displayName = 'App';
|
|
247
|
+
|
|
248
|
+
export default App;
|
|
249
|
+
|
|
250
|
+
<i><u>index.js</i></b>
|
|
251
|
+
|
|
252
|
+
import React from 'react';
|
|
253
|
+
import ReactDOM from 'react-dom';
|
|
254
|
+
import App from './app';
|
|
255
|
+
ReactDOM.render(<App />, document.getElementById('root'));
|
|
256
|
+
|
|
257
|
+
## License
|
|
258
|
+
|
|
259
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export class UsageError extends Error {
|
|
2
|
+
}
|
|
3
|
+
export function useStore<T_1 extends State>(): Store<T_1>;
|
|
4
|
+
/**
|
|
5
|
+
* @type {import("react").Provider<T>}
|
|
6
|
+
* @template {State} T
|
|
7
|
+
*/
|
|
8
|
+
export const Provider: import("react").Provider<T>;
|
|
9
|
+
export type ObservableContext<T_1 extends State> = import("react").Context<Store<T>>;
|
|
10
|
+
export type OptionalTask<F = void> = F extends void ? () => never : F;
|
|
11
|
+
export type Listener<T_1 extends State> = (newValue: PartialState<T>, oldValue: PartialState<T>) => void;
|
|
12
|
+
export type State = {
|
|
13
|
+
[x: string]: any;
|
|
14
|
+
};
|
|
15
|
+
export type PartialState<T_1 extends State> = {
|
|
16
|
+
[x: string]: any;
|
|
17
|
+
} & { [K in keyof T]?: T[K]; };
|
|
18
|
+
export type Selector<T_1 extends State> = (state: T) => PartialState<T>;
|
|
19
|
+
export type Store<T_1 extends State> = {
|
|
20
|
+
getState: (selector?: Selector<T>) => PartialState<T>;
|
|
21
|
+
resetState: OptionalTask<VoidFunction>;
|
|
22
|
+
setState: (changes: PartialState<T>) => void;
|
|
23
|
+
subscribe: (listener: Listener<T>) => Unsubscribe;
|
|
24
|
+
};
|
|
25
|
+
export type Unsubscribe = VoidFunction;
|
|
26
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
|
|
4
|
+
Object.defineProperty(exports, "__esModule", {
|
|
5
|
+
value: true
|
|
6
|
+
});
|
|
7
|
+
exports.useStore = exports.UsageError = exports.Provider = void 0;
|
|
8
|
+
var _react = _interopRequireWildcard(require("react"));
|
|
9
|
+
var _lodash = _interopRequireDefault(require("lodash.isempty"));
|
|
10
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
|
|
11
|
+
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
|
|
12
|
+
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
|
|
13
|
+
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
|
|
14
|
+
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
|
|
15
|
+
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
|
|
16
|
+
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
|
|
17
|
+
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
|
|
18
|
+
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
|
|
19
|
+
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
|
|
20
|
+
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
|
|
21
|
+
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
|
22
|
+
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
|
|
23
|
+
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
|
|
24
|
+
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
|
|
25
|
+
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
|
|
26
|
+
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
|
|
27
|
+
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
|
|
28
|
+
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
|
|
29
|
+
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
|
|
30
|
+
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
|
|
31
|
+
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
|
|
32
|
+
var UsageError = /*#__PURE__*/function (_Error) {
|
|
33
|
+
_inherits(UsageError, _Error);
|
|
34
|
+
var _super = _createSuper(UsageError);
|
|
35
|
+
function UsageError() {
|
|
36
|
+
_classCallCheck(this, UsageError);
|
|
37
|
+
return _super.apply(this, arguments);
|
|
38
|
+
}
|
|
39
|
+
return _createClass(UsageError);
|
|
40
|
+
}( /*#__PURE__*/_wrapNativeSuper(Error));
|
|
41
|
+
/** @type {OptionalTask} */
|
|
42
|
+
exports.UsageError = UsageError;
|
|
43
|
+
var reportNonReactUsage = function reportNonReactUsage() {
|
|
44
|
+
throw new UsageError('Detected usage outside of this context\'s Provider component tree. Please apply the exported Provider component');
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @type {(state: T) => PartialState<T>}
|
|
49
|
+
* @template {State} T
|
|
50
|
+
*/
|
|
51
|
+
var defaultSelector = function defaultSelector(state) {
|
|
52
|
+
return state;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @type {ObservableContext<T>}
|
|
57
|
+
* @template {State} T
|
|
58
|
+
*/
|
|
59
|
+
var StoreContext = /*#__PURE__*/(0, _react.createContext)({
|
|
60
|
+
getState: reportNonReactUsage,
|
|
61
|
+
resetState: reportNonReactUsage,
|
|
62
|
+
setState: reportNonReactUsage,
|
|
63
|
+
subscribe: reportNonReactUsage
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @return {Store<T>}
|
|
68
|
+
* @template {State} T
|
|
69
|
+
*/
|
|
70
|
+
var useStore = function useStore() {
|
|
71
|
+
return (0, _react.useContext)(StoreContext);
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @type {import("react").Provider<T>}
|
|
76
|
+
* @template {State} T
|
|
77
|
+
*/
|
|
78
|
+
exports.useStore = useStore;
|
|
79
|
+
var Provider = function Provider(_ref) {
|
|
80
|
+
var _ref$children = _ref.children,
|
|
81
|
+
children = _ref$children === void 0 ? null : _ref$children,
|
|
82
|
+
value = _ref.value;
|
|
83
|
+
var valueRef = (0, _react.useRef)(value);
|
|
84
|
+
/** @type {[Set<Listener<T>>, Function]} */
|
|
85
|
+
var _useState = (0, _react.useState)(function () {
|
|
86
|
+
return new Set();
|
|
87
|
+
}),
|
|
88
|
+
_useState2 = _slicedToArray(_useState, 1),
|
|
89
|
+
listeners = _useState2[0];
|
|
90
|
+
/** @type {Listener<T>} */
|
|
91
|
+
var onChange = function onChange(newValue, oldValue) {
|
|
92
|
+
return listeners.forEach(function (listener) {
|
|
93
|
+
return listener(newValue, oldValue);
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
/** @type {Store<T>["getState"]} */
|
|
97
|
+
var getState = (0, _react.useCallback)(function () {
|
|
98
|
+
var selector = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultSelector;
|
|
99
|
+
return selector(valueRef.current);
|
|
100
|
+
}, []);
|
|
101
|
+
/** @type {Store<T>["resetState"]} */
|
|
102
|
+
var resetState = (0, _react.useCallback)(function () {
|
|
103
|
+
return setState(value);
|
|
104
|
+
}, []);
|
|
105
|
+
/** @type {Store<T>["setState"]} */
|
|
106
|
+
var setState = (0, _react.useCallback)(function (changes) {
|
|
107
|
+
/** @type {PartialState<T>} */
|
|
108
|
+
var newChanges = {};
|
|
109
|
+
/** @type {PartialState<T>} */
|
|
110
|
+
var replacedValue = {};
|
|
111
|
+
for (var k in changes) {
|
|
112
|
+
if (valueRef.current[k] === changes[k]) {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
replacedValue[k] = valueRef.current[k];
|
|
116
|
+
valueRef.current[k] = changes[k];
|
|
117
|
+
newChanges[k] = changes[k];
|
|
118
|
+
}
|
|
119
|
+
!(0, _lodash["default"])(newChanges) && onChange(newChanges, replacedValue);
|
|
120
|
+
}, []);
|
|
121
|
+
/** @type {Store<T>["subscribe"]} */
|
|
122
|
+
var subscribe = (0, _react.useCallback)(function (listener) {
|
|
123
|
+
listeners.add(listener);
|
|
124
|
+
return function () {
|
|
125
|
+
return listeners["delete"](listener);
|
|
126
|
+
};
|
|
127
|
+
}, []);
|
|
128
|
+
(0, _react.useEffect)(function () {
|
|
129
|
+
return setState(value);
|
|
130
|
+
}, [value]);
|
|
131
|
+
/** @type {[Store<T>, Function]} */
|
|
132
|
+
var _useState3 = (0, _react.useState)(function () {
|
|
133
|
+
return {
|
|
134
|
+
getState: getState,
|
|
135
|
+
resetState: resetState,
|
|
136
|
+
setState: setState,
|
|
137
|
+
subscribe: subscribe
|
|
138
|
+
};
|
|
139
|
+
}),
|
|
140
|
+
_useState4 = _slicedToArray(_useState3, 1),
|
|
141
|
+
store = _useState4[0];
|
|
142
|
+
return /*#__PURE__*/_react["default"].createElement(StoreContext.Provider, {
|
|
143
|
+
value: store
|
|
144
|
+
}, children);
|
|
145
|
+
};
|
|
146
|
+
exports.Provider = Provider;
|
|
147
|
+
Provider.displayName = 'ObservableContext.Provider';
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @typedef {import("react").Context<Store<T>>} ObservableContext
|
|
151
|
+
* @template {State} T
|
|
152
|
+
*/
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* @typedef {F extends void ? () => never : F} OptionalTask
|
|
156
|
+
* @template [F=void]
|
|
157
|
+
*/
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
@typedef {(newValue: PartialState<T>, oldValue: PartialState<T>) => void} Listener
|
|
161
|
+
@template {State} T
|
|
162
|
+
*/
|
|
163
|
+
/** @typedef {{[x:string]: *}} State */
|
|
164
|
+
/**
|
|
165
|
+
@typedef {{[x:string]: *} & {[K in keyof T]?: T[K]}} PartialState
|
|
166
|
+
@template {State} T
|
|
167
|
+
*/
|
|
168
|
+
/**
|
|
169
|
+
@typedef {(state: T) => PartialState<T>} Selector
|
|
170
|
+
@template {State} T
|
|
171
|
+
*/
|
|
172
|
+
/**
|
|
173
|
+
* @typedef {{
|
|
174
|
+
* getState: OptionalTask<(selector?: Selector<T>) => PartialState<T>>,
|
|
175
|
+
* resetState: OptionalTask<VoidFunction>,
|
|
176
|
+
* setState: OptionalTask<(changes: PartialState<T>) => void>,
|
|
177
|
+
* subscribe: OptionalTask<(listener: Listener<T>) => Unsubscribe>
|
|
178
|
+
* }} Store
|
|
179
|
+
@template {State} T
|
|
180
|
+
*/
|
|
181
|
+
|
|
182
|
+
/** @typedef {VoidFunction} Unsubscribe */
|
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require( './dist' );
|
package/package.json
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
{
|
|
2
|
+
"author": "Stephen Isienyi <stephen.isienyi@webkrafting.com>",
|
|
3
|
+
"bugs": {
|
|
4
|
+
"url": "https://github.com/steveswork/react-observable-context/issues"
|
|
5
|
+
},
|
|
6
|
+
"contributors": [
|
|
7
|
+
"steveswork <stephen.isienyi@webkrafting.com> (https://github.com/steveswork)"
|
|
8
|
+
],
|
|
9
|
+
"dependencies": {
|
|
10
|
+
"@types/react": "^18.0.17",
|
|
11
|
+
"lodash.isempty": "^4.4.0",
|
|
12
|
+
"react": "^18.2.0"
|
|
13
|
+
},
|
|
14
|
+
"description": "Observable react context - prevents an automatic total component tree tear-down and re-rendering during context updates.",
|
|
15
|
+
"devDependencies": {
|
|
16
|
+
"@babel/cli": "^7.17.0",
|
|
17
|
+
"@babel/core": "^7.12.10",
|
|
18
|
+
"@babel/node": "^7.12.10",
|
|
19
|
+
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",
|
|
20
|
+
"@babel/plugin-transform-runtime": "^7.17.0",
|
|
21
|
+
"@babel/preset-env": "^7.12.11",
|
|
22
|
+
"@babel/preset-react": "^7.18.6",
|
|
23
|
+
"@testing-library/jest-dom": "^5.16.5",
|
|
24
|
+
"@testing-library/react": "^13.4.0",
|
|
25
|
+
"@testing-library/user-event": "^14.4.3",
|
|
26
|
+
"@types/jest-cli": "^24.3.0",
|
|
27
|
+
"babel-jest": "^26.6.3",
|
|
28
|
+
"babel-loader": "^8.2.5",
|
|
29
|
+
"eslint": "^7.15.0",
|
|
30
|
+
"eslint-config-standard": "^16.0.2",
|
|
31
|
+
"eslint-plugin-import": "^2.22.1",
|
|
32
|
+
"eslint-plugin-jest": "^24.1.3",
|
|
33
|
+
"eslint-plugin-node": "^11.1.0",
|
|
34
|
+
"eslint-plugin-promise": "^4.2.1",
|
|
35
|
+
"eslint-plugin-react": "^7.31.11",
|
|
36
|
+
"eslint-plugin-standard": "^5.0.0",
|
|
37
|
+
"jest-cli": "^26.6.3",
|
|
38
|
+
"react-dom": "^18.2.0",
|
|
39
|
+
"react-performance-testing": "^2.0.0",
|
|
40
|
+
"typescript": "^4.8.2"
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"dist/index.js",
|
|
44
|
+
"dist/index.d.ts",
|
|
45
|
+
"index",
|
|
46
|
+
"package.json"
|
|
47
|
+
],
|
|
48
|
+
"homepage": "https://github.com/steveswork/react-observable-context#readme",
|
|
49
|
+
"jest": {
|
|
50
|
+
"transform": {
|
|
51
|
+
"\\.[jt]sx?$": "babel-jest"
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"keywords": [
|
|
55
|
+
"context",
|
|
56
|
+
"react-hooks",
|
|
57
|
+
"react-context",
|
|
58
|
+
"react",
|
|
59
|
+
"useContext"
|
|
60
|
+
],
|
|
61
|
+
"license": "MIT",
|
|
62
|
+
"main": "index.js",
|
|
63
|
+
"name": "@webkrafters/react-observable-context",
|
|
64
|
+
"publishConfig": {
|
|
65
|
+
"access": "public"
|
|
66
|
+
},
|
|
67
|
+
"repository": {
|
|
68
|
+
"type": "git",
|
|
69
|
+
"url": "git+https://github.com/steveswork/react-observable-context.git"
|
|
70
|
+
},
|
|
71
|
+
"scripts": {
|
|
72
|
+
"build": "eslint --fix && rm -rf dist && babel src -d dist && npx -p typescript tsc",
|
|
73
|
+
"test": "eslint --fix && jest",
|
|
74
|
+
"test:watch": "eslint --fix && jest --watchAll"
|
|
75
|
+
},
|
|
76
|
+
"types": "dist/index.d.ts",
|
|
77
|
+
"version": "0.0.1"
|
|
78
|
+
}
|