@cleanweb/oore 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 (60) hide show
  1. package/README.md +374 -0
  2. package/README.old.md +342 -0
  3. package/build/base/index.d.ts +3 -0
  4. package/build/base/index.js +19 -0
  5. package/build/base/merged-state.d.ts +20 -0
  6. package/build/base/merged-state.js +84 -0
  7. package/build/base/methods.d.ts +59 -0
  8. package/build/base/methods.js +100 -0
  9. package/build/base/state/class-types.d.ts +20 -0
  10. package/build/base/state/class-types.js +2 -0
  11. package/build/base/state/class.d.ts +16 -0
  12. package/build/base/state/class.js +100 -0
  13. package/build/base/state/hook-types.d.ts +32 -0
  14. package/build/base/state/hook-types.js +2 -0
  15. package/build/base/state/hooks.d.ts +12 -0
  16. package/build/base/state/hooks.js +45 -0
  17. package/build/base/state/index.d.ts +8 -0
  18. package/build/base/state/index.js +35 -0
  19. package/build/classy/class/index.d.ts +115 -0
  20. package/build/classy/class/index.js +161 -0
  21. package/build/classy/class/types/extractor.d.ts +5 -0
  22. package/build/classy/class/types/extractor.js +2 -0
  23. package/build/classy/class/utils/function-name.d.ts +2 -0
  24. package/build/classy/class/utils/function-name.js +17 -0
  25. package/build/classy/index.d.ts +3 -0
  26. package/build/classy/index.js +19 -0
  27. package/build/classy/instance/index.d.ts +144 -0
  28. package/build/classy/instance/index.js +202 -0
  29. package/build/classy/instance/mount-callbacks.d.ts +5 -0
  30. package/build/classy/instance/mount-callbacks.js +30 -0
  31. package/build/classy/instance/types/hook.d.ts +13 -0
  32. package/build/classy/instance/types/hook.js +2 -0
  33. package/build/classy/logic/index.d.ts +116 -0
  34. package/build/classy/logic/index.js +128 -0
  35. package/build/classy/logic/types/hook.d.ts +16 -0
  36. package/build/classy/logic/types/hook.js +2 -0
  37. package/build/docs-src/api/base-classes.d.ts +3 -0
  38. package/build/docs-src/api/base-classes.js +9 -0
  39. package/build/docs-src/api/index.d.ts +13 -0
  40. package/build/docs-src/api/index.js +44 -0
  41. package/build/docs-src/api/references.d.ts +5 -0
  42. package/build/docs-src/api/references.js +31 -0
  43. package/build/globals.d.ts +84 -0
  44. package/build/globals.js +4 -0
  45. package/build/helpers/index.d.ts +13 -0
  46. package/build/helpers/index.js +31 -0
  47. package/build/helpers/mount-state.d.ts +5 -0
  48. package/build/helpers/mount-state.js +25 -0
  49. package/build/helpers/rerender.d.ts +5 -0
  50. package/build/helpers/rerender.js +29 -0
  51. package/build/helpers/type-guards.d.ts +1 -0
  52. package/build/helpers/type-guards.js +8 -0
  53. package/build/helpers/use-component/index.d.ts +6 -0
  54. package/build/helpers/use-component/index.js +17 -0
  55. package/build/helpers/use-component/types.d.ts +22 -0
  56. package/build/helpers/use-component/types.js +2 -0
  57. package/build/index.d.ts +4 -0
  58. package/build/index.js +19 -0
  59. package/build/tsconfig.json +49 -0
  60. package/package.json +87 -0
package/README.old.md ADDED
@@ -0,0 +1,342 @@
1
+ # Structured & Cleaner React Function Components
2
+
3
+ ## Quick Start
4
+ This package provides a suite of tools for writing cleaner React function components. It is particularly useful for larger components with lots of state variables and multiple closure functions that need to access those variables. The most likely use cases will use one of the three main exported members.
5
+
6
+ > The following sections will use examples to demonstrate how each tool can be used. These example are intended to be read as a before and after comparison. They are all based on the same "before" code, which is shown below:
7
+
8
+
9
+ ### Our Sample React Function Component
10
+ ```jsx
11
+ const Footer = (props) => {
12
+ const [state1, setState1] = useState(props.defaultValue);
13
+ const [state2, setState2] = useState();
14
+ const [label, setLabel] = useState('Click me');
15
+ const [submitted, setSubmitted] = useState(false);
16
+
17
+ const [store, updateStore] = useGlobalStore();
18
+
19
+ const { param } = props;
20
+
21
+
22
+ // Required to run once *before* the component mounts.
23
+ const paragraphs = useMemo(() => getValue(param), [param]);
24
+
25
+
26
+ /** @todo Use `useSyncExternalStore`. */
27
+ const subscribeToExternalDataSource = useCallback(() => {
28
+ externalDataSource.subscribe((data) => {
29
+ setLabel(data.label);
30
+ });
31
+ }, [setLabel]);
32
+
33
+ // Required to run once *after* the component mounts.
34
+ useEffect(subscribeToExternalDataSource, []);
35
+ useEffect(() => {
36
+ const onWindowResize = () => {};
37
+ window.addEventListener('resize', onWindowResize);
38
+
39
+ return () => {
40
+ window.removeEventListener('resize', onWindowResize);
41
+ };
42
+ }, []);
43
+
44
+ // Run *after* every render.
45
+ useEffect(() => {
46
+ doSomething();
47
+ return () => {};
48
+ })
49
+
50
+ const submit = useCallback(() => {
51
+ sendData(state1, state2);
52
+ setSubmitted(true);
53
+ }, [state1]); // Notice how `state2` above could easily be stale by the time the callback runs.
54
+
55
+
56
+ // Run before every render.
57
+ const text = `${label}, please.`;
58
+
59
+ return (
60
+ <footer>
61
+ {paragraphs ? paragraphs.map((copy) => (
62
+ <p>{copy}</p>
63
+ )) : null}
64
+
65
+ <button onClick={submit}>
66
+ {text}
67
+ </button>
68
+ </footer>
69
+ );
70
+ };
71
+
72
+ export default Footer;
73
+ // Or use in JSX as `<Footer />`.
74
+ ```
75
+
76
+
77
+ ### A Cleaner State Management API
78
+ The `useCleanState` hook provides a cleaner API for working with state, particularly in components with a relatively high number of state variables. It allows you to manage multiple state variables as a single unit. You will likely find this cleaner to work with than having multiple local variables for each state. The example below demonstrates the use of this hook.
79
+
80
+
81
+ ### Extracting and Structuring Component Logic
82
+ The `useLogic` hook allows you to write your component's logic outside the function component's body, and helps you keep them all better organized. It also provides a much cleaner API for working with multiple state variables. Here's what a function component looks like with the `useLogic` hook.
83
+
84
+ **Before**
85
+ [See the "before" code above](#our-sample-react-function-component).
86
+
87
+ **After**
88
+ ```jsx
89
+ class FooterLogic {
90
+ static getInitialState = (props) => {
91
+ return {
92
+ state1: props.defaultValue,
93
+ state2: undefined,
94
+ label: 'Click me',
95
+ submitted: false,
96
+ };
97
+ };
98
+
99
+ subscribeToExternalDataSource = () => {
100
+ externalDataSource.subscribe((data) => {
101
+ this.state.label = data.label;
102
+ });
103
+ }
104
+
105
+ useHooks = () => {
106
+ const [store, updateStore] = useGlobalStore();
107
+ const { param } = this.props;
108
+
109
+ // Required to run once *before* the component mounts.
110
+ const paragraphs = useMemo(() => getValue(param), [param]);
111
+
112
+ // Required to run once *after* the component mounts.
113
+ useEffect(this.subscribeToExternalDataSource, []);
114
+ useEffect(() => {
115
+ const onWindowResize = () => {};
116
+ window.addEventListener('resize', onWindowResize);
117
+
118
+ return () => {
119
+ window.removeEventListener('resize', onWindowResize);
120
+ };
121
+ }, []);
122
+
123
+ // Run *after* every render.
124
+ useEffect(() => {
125
+ doSomething();
126
+ return () => {};
127
+ });
128
+
129
+ return {
130
+ store,
131
+ updateStore,
132
+ paragraphs,
133
+ };
134
+ };
135
+
136
+ submit = () => {
137
+ const { state1, state2 } = this.state;
138
+ sendData(state1, state2);
139
+ this.state.submitted = true;
140
+ }; // `state2` is never stale. All `state` and `props` references return the latest value. No extra steps required.
141
+ }
142
+
143
+ // Footer Template
144
+ const Footer = (props) => {
145
+ const self = useLogic(FooterLogic, props);
146
+
147
+ const { paragraphs } = self.hooks;
148
+ const { state } = self;
149
+
150
+ // Run before every render.
151
+ const text = `${state.label}, please.`;
152
+
153
+ return (
154
+ <footer>
155
+ {paragraphs ? paragraphs.map((copy) => (
156
+ <p>{copy}</p>
157
+ )) : null}
158
+
159
+ <button onClick={self.submit}>
160
+ {text}
161
+ </button>
162
+ </footer>
163
+ );
164
+ };
165
+
166
+ export default Footer;
167
+ // Or use in JSX as `<Footer />`.
168
+ ```
169
+
170
+ The `useLogic` hook combines the functionality of two base hooks which can also be used directly. They are [`useCleanState`](https://cleanjsweb.github.io/neat-react/clean-state/index) and [`useMethods`](https://cleanjsweb.github.io/neat-react/methods/index). `useCleanState` can be used independently if you only want a cleaner state management API. `useMethods` is designed to be used together with `useCleanState`, but rather than calling both individually, you may find it more convenient to use `useLogic`, which combines both as well as the added functionality of the `useHooks` method.
171
+
172
+ > It is possible to have multiple calls to `useLogic` in the same component. This allows your function component template to consume state and logic from multiple sources, or it can simply be used to group distinct pieces of related logic into separate classes.
173
+
174
+ For a fuller discussion of how `useLogic` works, start at the [clean-state documentation](https://cleanjsweb.github.io/neat-react/clean-state/index).
175
+ For an API reference, see the [API reference](https://cleanjsweb.github.io/neat-react/logic/api).
176
+
177
+
178
+ ### Working With Lifecycle, and Migrating From a React.Component Class to a Function Component
179
+ In addition to having cleaner and more structured component logic, you can also simplify the process of working with your component's lifecycle with the final two exported members. The `useInstance` hook builds on the functionality of `useLogic` and adds lifecyle methods to the class. This means the class can now be thought of as truly representing a single instance of a React component. The `ClassComponent` class extends this to its fullest by allowing you to write the function component itself as a method within the class, and removing the need to explicitly call `useInstance`.
180
+
181
+ **Before**
182
+ [See the "before" code above](#our-sample-react-function-component).
183
+
184
+ **After**
185
+ ```jsx
186
+ class Footer extends ClassComponent {
187
+ // Call the static method extract() to retrieve the renderer for your class.
188
+ // This is a function that you can render like any other function component.
189
+ // Each instance of the renderer in your component tree will create its own instance of the class.
190
+ static readonly RC = Button.extract();
191
+
192
+ static getInitialState = (props) => {
193
+ return {
194
+ state1: props.defaultValue,
195
+ state2: undefined,
196
+ label: 'Click me',
197
+ submitted: false,
198
+ };
199
+ };
200
+
201
+ useHooks = () => {
202
+ const [store, updateStore] = useGlobalStore();
203
+ return { store, updateStore };
204
+ }
205
+
206
+ /***************************
207
+ * New Lifecycle Methods *
208
+ ***************************/
209
+
210
+ beforeMount = () => {
211
+ this.paragraphs = getValue();
212
+ }
213
+
214
+ // Run after the component is mounted.
215
+ onMount = () => {
216
+ this.subscribeToExternalDataSource();
217
+ window.addEventListener('resize', this.onWindowResize);
218
+
219
+ // Return cleanup callback.
220
+ return () => {
221
+ window.removeEventListener('resize', this.onWindowResize);
222
+ };
223
+ }
224
+
225
+ beforeRender = () => {
226
+ this.text = `${label}, please.`;
227
+ }
228
+
229
+ // Run after every render.
230
+ onRender = () => {
231
+ doSomething();
232
+
233
+ // Return cleanup callback.
234
+ return () => {};
235
+ }
236
+
237
+ cleanUp = () => {
238
+ // Run some non-mount-related cleanup when the component dismounts.
239
+ // onMount (and onRender) returns its own cleanup function.
240
+ }
241
+
242
+ /***************************
243
+ * [End] Lifecycle Methods *
244
+ ***************************/
245
+
246
+ submit = () => {
247
+ // Methods are guaranteed to have access to the most recent state values.
248
+ const { state1, state2 } = this.state;
249
+
250
+ sendData(state1, state2);
251
+
252
+ // CleanState uses JavaScript's getters and setters, allowing you to assign state values directly.
253
+ // The effect is the same as if you called the setter function, which is available through `state.put.submitted(true)`.
254
+ this.state.submitted = true;
255
+ }
256
+
257
+ onWindowResize = () => {};
258
+
259
+ subscribeToExternalDataSource = () => {
260
+ const unsubscribe = externalDataSource.subscribe((data) => {
261
+ this.state.label = data.label;
262
+ });
263
+
264
+ return unsubscribe;
265
+ }
266
+
267
+ /** You can also separate out discreet chunks of your UI template. */
268
+ Paragraphs = () => {
269
+ if (!this.paragraphs) return null;
270
+
271
+ return this.paragraphs.map((content, index) => (
272
+ <p key={index}>
273
+ {content || this.state.label}
274
+ </p>
275
+ ));
276
+ }
277
+
278
+ /** Button Template */
279
+ template = () => {
280
+ const { Paragraphs, submit, state } = this;
281
+
282
+ return (
283
+ <Fragment>
284
+ <Paragraphs />
285
+
286
+ {/* You can access the setter functions returned from useState through the state.put object. */}
287
+ {/* This is more convenient than the assignment approach if you need to pass a setter as a callback. */}
288
+ {/* Use state.putMany to set multiple values at once. It works just like setState in React.Component classes. */}
289
+ {/* e.g state.inputValue = 'foo', or state.put.inputValue('foo'), or state.putMany({ inputValue: 'foo' }) */}
290
+ <CustomInput setValue={state.put.inputValue} />
291
+
292
+ <button onClick={submit}>
293
+ {this.text}
294
+ </button>
295
+ </Fragment>
296
+ );
297
+ }
298
+ }
299
+
300
+ // Can also be used directly in JSX as `<Button.RC />`.
301
+ export default Button.RC;
302
+ ```
303
+
304
+ > If you would like to keep the actual function component separate and call `useInstance` directly, see the [`useInstance` docs](https://cleanjsweb.github.io/neat-react/instance/index) for more details and examples.
305
+
306
+ At its core, any component you write with `ClassComponent` is still just a React function component, with some supporting logic around it. This has the added advantage of making it significantly easier to migrate class components written with `React.Component` to the newer hooks-based function components, while still maintaining the overall structure of a class component, and the advantages that the class component approach provided.
307
+
308
+ For a fuller discussion of how this works, start at the [`useInstance` documentation](https://cleanjsweb.github.io/neat-react/instance/index).
309
+ For more details on the lifecycle methods and other API reference, see the [`ClassComponent` API docs](https://cleanjsweb.github.io/neat-react/class-component/api).
310
+
311
+ ### The `<Use>` Component
312
+ If you only want to use hooks in your `React.Component` class without having to refactor anything, use the [`Use` component](https://cleanjsweb.github.io/neat-react/class-component/index#the-use-component).
313
+
314
+ ```jsx
315
+ class Button extends React.Component {
316
+ handleGlobalStore = ([store, updateStore]) => {
317
+ this.setState({ userId: store.userId });
318
+ this.store = store;
319
+ this.updateStore = updateStore;
320
+ }
321
+
322
+ UseHooks = () => {
323
+ return <>
324
+ <Use hook={useGlobalStore}
325
+ onUpdate={handleGlobalStore}
326
+ argumentsList={[]}
327
+ key="useGlobalStore"
328
+ />
329
+ </>;
330
+ }
331
+
332
+ render() {
333
+ const { UseHooks } = this;
334
+
335
+ return <>
336
+ <UseHooks />
337
+
338
+ <button>Click me</button>
339
+ </>;
340
+ }
341
+ }
342
+ ```
@@ -0,0 +1,3 @@
1
+ export * from './state';
2
+ export * from './methods';
3
+ export * from './merged-state';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./state"), exports);
18
+ __exportStar(require("./methods"), exports);
19
+ __exportStar(require("./merged-state"), exports);
@@ -0,0 +1,20 @@
1
+ import '../globals';
2
+ declare class MergedState<TState extends object> {
3
+ static useRefresh<TState extends object>(this: MergedState<TState>): void;
4
+ reservedKeys: string[];
5
+ valueKeys: string[];
6
+ private _initialValues_;
7
+ private _values_;
8
+ private setState;
9
+ private _setters_;
10
+ get put(): { [Key in keyof TState]: (value: TState[Key]) => void; };
11
+ get initialState(): TState;
12
+ constructor(initialState: TState);
13
+ putMany: (newValues: Partial<TState>) => void;
14
+ }
15
+ /**
16
+ * Similar to {@link useCleanState},
17
+ * but uses a single `useState` call for the entire object.
18
+ */
19
+ export declare const useMergedState: <TState extends object>(initialState: TState) => MergedState<TState> & TState;
20
+ export {};
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.useMergedState = void 0;
15
+ require("../globals");
16
+ var react_1 = require("react");
17
+ var MergedState = /** @class */ (function () {
18
+ function MergedState(initialState) {
19
+ var _this = this;
20
+ this._initialValues_ = {};
21
+ this._values_ = {};
22
+ this._setters_ = {};
23
+ this.putMany = function (newValues) {
24
+ _this.setState(__assign(__assign({}, _this._values_), newValues));
25
+ };
26
+ this.reservedKeys = Object.keys(this);
27
+ this.valueKeys = [];
28
+ this._initialValues_ = __assign({}, initialState);
29
+ this._values_ = __assign({}, initialState);
30
+ Object.keys(initialState).forEach(function (_key) {
31
+ var key = _key;
32
+ if (_this.reservedKeys.includes(key)) {
33
+ throw new Error("The name \"".concat(key, "\" is reserved by CleanState and cannot be used to index state variables. Please use a different key."));
34
+ }
35
+ _this.valueKeys.push(key);
36
+ _this._setters_[key] = function (value) {
37
+ var _a;
38
+ // this._values_[key] = value;
39
+ _this.setState(__assign(__assign({}, _this._values_), (_a = {}, _a[key] = value, _a)));
40
+ };
41
+ var self = _this;
42
+ Object.defineProperty(_this, key, {
43
+ get: function () {
44
+ return self._values_[key];
45
+ },
46
+ set: function (value) {
47
+ self._setters_[key](value);
48
+ },
49
+ enumerable: true,
50
+ });
51
+ });
52
+ }
53
+ MergedState.useRefresh = function () {
54
+ var _a;
55
+ _a = (0, react_1.useState)(this.initialState), this._values_ = _a[0], this.setState = _a[1];
56
+ };
57
+ Object.defineProperty(MergedState.prototype, "put", {
58
+ get: function () {
59
+ return __assign({}, this._setters_);
60
+ },
61
+ enumerable: false,
62
+ configurable: true
63
+ });
64
+ Object.defineProperty(MergedState.prototype, "initialState", {
65
+ get: function () {
66
+ return __assign({}, this._initialValues_);
67
+ },
68
+ enumerable: false,
69
+ configurable: true
70
+ });
71
+ return MergedState;
72
+ }());
73
+ /**
74
+ * Similar to {@link useCleanState},
75
+ * but uses a single `useState` call for the entire object.
76
+ */
77
+ var useMergedState = function (initialState) {
78
+ var cleanState = (0, react_1.useRef)((0, react_1.useMemo)(function () {
79
+ return new MergedState(initialState);
80
+ }, [])).current;
81
+ MergedState.useRefresh.call(cleanState);
82
+ return cleanState;
83
+ };
84
+ exports.useMergedState = useMergedState;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @module ComponentMethods
3
+ */
4
+ import type { TCleanState, TStateData } from './state';
5
+ /**
6
+ * @summary
7
+ * Base class for a class that holds methods for a function component.
8
+ *
9
+ * @remarks
10
+ * These methods will have access to the components state and props via
11
+ * `this.state` and `this.props` respectively.
12
+ *
13
+ * Call the {@link useMethods} hook inside your function component to instantiate the class.
14
+ */
15
+ export declare class ComponentMethods<TProps extends object = {}, TState extends TStateData | null = null> {
16
+ readonly props: TProps;
17
+ readonly state: TState extends TStateData ? TCleanState<TState> : null;
18
+ /**
19
+ * Persist class members during HMR. {@include ../classy/logic/hrm-preserve-keys.md}
20
+ * @privateRemarks
21
+ * @see {@link https://cleanjsweb.github.io/neat-react/classes/API.BaseClasses.ComponentMethods.html#_hmrpreservekeys | Full details}
22
+ */
23
+ _hmrPreserveKeys: Array<keyof this | (string & {})>;
24
+ /**
25
+ * Run custom logic after HMR update. {@include ../classy/logic/on-hrm-update.md}
26
+ * @privateRemarks
27
+ * @see {@link https://cleanjsweb.github.io/neat-react/classes/API.BaseClasses.ComponentMethods.html#_onhmrupdate | Full details}
28
+ */
29
+ _onHmrUpdate?: <TInstance extends this>(oldInstance: TInstance) => void;
30
+ }
31
+ type UseMethods = {
32
+ <Class extends typeof ComponentMethods<object, object>>(Methods: Class & Constructor<InstanceType<Class>>, props: InstanceType<Class>['props'], state: InstanceType<Class>['state']): InstanceType<Class>;
33
+ <Class extends typeof ComponentMethods<object, null>>(Methods: Class & Constructor<InstanceType<Class>>, props: InstanceType<Class>['props'], state?: null): InstanceType<Class>;
34
+ <Class extends typeof ComponentMethods<NeverObject, null>>(Methods: Class & Constructor<InstanceType<Class>>): InstanceType<Class>;
35
+ };
36
+ /**
37
+ * Returns an instance of the provided class,
38
+ * with the state and props arguments added as instance members.
39
+ *
40
+ * `state` should be an instance of `CleanState` created with {@link useCleanState}.
41
+ */
42
+ declare const useMethods: UseMethods;
43
+ export { useMethods };
44
+ /** /type_testing: {
45
+ let a = async () => {
46
+ const a: object = {b: ''};
47
+
48
+ type t = keyof typeof a;
49
+
50
+ class MyMethods extends ComponentMethods<EmptyObject, null> {
51
+ // static getInitialState = () => ({});
52
+ };
53
+
54
+ const { useCleanState } = (await import('./state.js'));
55
+
56
+ const self = useMethods(MyMethods, {});
57
+ self.state;
58
+ }
59
+ }/**/
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ /**
3
+ * @module ComponentMethods
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.useMethods = exports.ComponentMethods = void 0;
7
+ // Values
8
+ var react_1 = require("react");
9
+ /**
10
+ * @summary
11
+ * Base class for a class that holds methods for a function component.
12
+ *
13
+ * @remarks
14
+ * These methods will have access to the components state and props via
15
+ * `this.state` and `this.props` respectively.
16
+ *
17
+ * Call the {@link useMethods} hook inside your function component to instantiate the class.
18
+ */
19
+ var ComponentMethods = /** @class */ (function () {
20
+ function ComponentMethods() {
21
+ /**
22
+ * Persist class members during HMR. {@include ../classy/logic/hrm-preserve-keys.md}
23
+ * @privateRemarks
24
+ * @see {@link https://cleanjsweb.github.io/neat-react/classes/API.BaseClasses.ComponentMethods.html#_hmrpreservekeys | Full details}
25
+ */
26
+ this._hmrPreserveKeys = []; // @todo Keep undefined. Update to empty array after instantiation in dev env.
27
+ }
28
+ return ComponentMethods;
29
+ }());
30
+ exports.ComponentMethods = ComponentMethods;
31
+ ;
32
+ /**
33
+ * Returns an instance of the provided class,
34
+ * with the state and props arguments added as instance members.
35
+ *
36
+ * `state` should be an instance of `CleanState` created with {@link useCleanState}.
37
+ */
38
+ var useMethods = function () {
39
+ var _a;
40
+ var args = [];
41
+ for (var _i = 0; _i < arguments.length; _i++) {
42
+ args[_i] = arguments[_i];
43
+ }
44
+ var Methods = args[0], _b = args[1], props = _b === void 0 ? {} : _b, state = args[2];
45
+ // Vite HMR seems to sometimes reinitialize useMemo calls after a hot update,
46
+ // causing the instance to be unexpectedly recreated in the middle of the component's lifecycle.
47
+ // But useRef and useState values appear to always be preserved whenever this happens.
48
+ // So those two are the only cross-render-persistence methods we can consider safe.
49
+ // In production, we only use the latestInstance the first time, and it's ignored every other time.
50
+ // This means changing the class at runtime will have no effect in production.
51
+ // latestInstance is only extracted into a separate variable for use in dev mode during HMR.
52
+ var latestInstance = (0, react_1.useMemo)(function () { return new Methods(); }, [Methods]);
53
+ var instanceRef = (0, react_1.useRef)(latestInstance);
54
+ var refreshState = function () {
55
+ // @ts-expect-error
56
+ instanceRef.current.props = props;
57
+ // @ts-expect-error
58
+ if (state)
59
+ instanceRef.current.state = state;
60
+ };
61
+ if (process.env.NODE_ENV === 'development' && instanceRef.current !== latestInstance) {
62
+ var oldInstance_1 = instanceRef.current;
63
+ latestInstance._hmrPreserveKeys.forEach(function (_key) {
64
+ var key = _key;
65
+ // @ts-expect-error We're assigning to readonly properties. Also, Typescript doesn't know that the type of the left and right side will always match, due to the dynamic access.
66
+ latestInstance[key] = oldInstance_1[key];
67
+ });
68
+ // Ensure that any stale references to oldInstance within the app
69
+ // will end up retrieving up-to-date values from latestInstance
70
+ // through the prototype chain.
71
+ Reflect.ownKeys(oldInstance_1).forEach(function (_key) {
72
+ var key = _key;
73
+ delete oldInstance_1[key];
74
+ });
75
+ Object.setPrototypeOf(oldInstance_1, latestInstance);
76
+ instanceRef.current = latestInstance;
77
+ refreshState();
78
+ (_a = latestInstance._onHmrUpdate) === null || _a === void 0 ? void 0 : _a.call(latestInstance, oldInstance_1);
79
+ }
80
+ else
81
+ refreshState();
82
+ return instanceRef.current;
83
+ };
84
+ exports.useMethods = useMethods;
85
+ /** /type_testing: {
86
+ let a = async () => {
87
+ const a: object = {b: ''};
88
+
89
+ type t = keyof typeof a;
90
+
91
+ class MyMethods extends ComponentMethods<EmptyObject, null> {
92
+ // static getInitialState = () => ({});
93
+ };
94
+
95
+ const { useCleanState } = (await import('./state.js'));
96
+
97
+ const self = useMethods(MyMethods, {});
98
+ self.state;
99
+ }
100
+ }/**/
@@ -0,0 +1,20 @@
1
+ import { CleanStateBase } from './class';
2
+ import { TCleanState, TStateData } from './hook-types';
3
+ export type TCleanStateBase = typeof CleanStateBase;
4
+ export type TCleanStateBaseKeys = keyof TCleanStateBase;
5
+ export type PutState<TState extends TStateData> = {
6
+ [Key in keyof TState]: React.Dispatch<React.SetStateAction<TState[Key]>>;
7
+ };
8
+ export type PutManyPayload<TState extends TStateData> = {
9
+ [Key in keyof TState]?: React.SetStateAction<TState[Key]>;
10
+ };
11
+ export type StateFragment<TComponent extends {
12
+ getInitialState: (...args: any[]) => TStateData;
13
+ }> = PutManyPayload<ReturnType<TComponent['getInitialState']>>;
14
+ export type { StateFragment as SF };
15
+ export interface ICleanStateConstructor {
16
+ new <TState extends object>(...args: ConstructorParameters<typeof CleanStateBase>): TCleanState<TState>;
17
+ }
18
+ export type ICleanStateClass = ICleanStateConstructor & {
19
+ [Key in TCleanStateBaseKeys]: (typeof CleanStateBase)[Key];
20
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,16 @@
1
+ import { ICleanStateClass, ICleanStateConstructor, PutManyPayload, PutState } from './class-types';
2
+ /** @internal */
3
+ export declare class CleanStateBase<TState extends Record<string, any>> {
4
+ readonly reservedKeys: string[];
5
+ readonly valueKeys: string[];
6
+ private _values_;
7
+ private _initialValues_;
8
+ private _setters_;
9
+ constructor(initialState: TState);
10
+ static update: <TState_1 extends object>(this: CleanStateBase<TState_1>) => void;
11
+ get put(): PutState<TState>;
12
+ get initialState(): TState;
13
+ readonly putMany: (newValues: PutManyPayload<TState>) => void;
14
+ }
15
+ /** @internal */
16
+ export declare const CleanState: (ICleanStateConstructor & ICleanStateClass);