kiss-for-react 1.1.0 → 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/README.md +699 -156
- package/lib/cjs/ClassPersistor.js +177 -112
- package/lib/cjs/Esserializer/DeserializationOptions.js +4 -4
- package/lib/cjs/Esserializer/SerializeOptions.js +4 -4
- package/lib/cjs/Esserializer/builtins.js +258 -0
- package/lib/cjs/Esserializer/constant.js +39 -131
- package/lib/cjs/Esserializer/deserializer.js +226 -313
- package/lib/cjs/Esserializer/general.js +91 -39
- package/lib/cjs/Esserializer/index.js +47 -43
- package/lib/cjs/Esserializer/serializer.js +168 -133
- package/lib/cjs/Evt.js +132 -0
- package/lib/cjs/Hooks.js +1472 -969
- package/lib/cjs/KissAction.js +4635 -1333
- package/lib/cjs/LoadPages.js +336 -0
- package/lib/cjs/Persistor.js +189 -120
- package/lib/cjs/ProcessPersistence.js +579 -262
- package/lib/cjs/Store.js +4278 -1534
- package/lib/cjs/StoreException.js +162 -75
- package/lib/cjs/StoreProvider.js +88 -0
- package/lib/cjs/UserException.js +212 -218
- package/lib/cjs/Wait.js +309 -309
- package/lib/cjs/index.js +69 -42
- package/lib/cjs/server.js +54 -0
- package/lib/cjs/types/ClassPersistor.d.ts +143 -112
- package/lib/cjs/types/ClassPersistor.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts +13 -6
- package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/SerializeOptions.d.ts +11 -5
- package/lib/cjs/types/Esserializer/SerializeOptions.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/builtins.d.ts +36 -0
- package/lib/cjs/types/Esserializer/builtins.d.ts.map +1 -0
- package/lib/cjs/types/Esserializer/constant.d.ts +25 -49
- package/lib/cjs/types/Esserializer/constant.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/deserializer.d.ts +27 -17
- package/lib/cjs/types/Esserializer/deserializer.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/general.d.ts +28 -4
- package/lib/cjs/types/Esserializer/general.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/index.d.ts +33 -29
- package/lib/cjs/types/Esserializer/index.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/serializer.d.ts +14 -3
- package/lib/cjs/types/Esserializer/serializer.d.ts.map +1 -1
- package/lib/cjs/types/Evt.d.ts +124 -0
- package/lib/cjs/types/Evt.d.ts.map +1 -0
- package/lib/cjs/types/Hooks.d.ts +1174 -837
- package/lib/cjs/types/Hooks.d.ts.map +1 -1
- package/lib/cjs/types/KissAction.d.ts +5199 -1398
- package/lib/cjs/types/KissAction.d.ts.map +1 -1
- package/lib/cjs/types/LoadPages.d.ts +287 -0
- package/lib/cjs/types/LoadPages.d.ts.map +1 -0
- package/lib/cjs/types/Persistor.d.ts +187 -118
- package/lib/cjs/types/Persistor.d.ts.map +1 -1
- package/lib/cjs/types/ProcessPersistence.d.ts +197 -99
- package/lib/cjs/types/ProcessPersistence.d.ts.map +1 -1
- package/lib/cjs/types/Store.d.ts +2253 -1042
- package/lib/cjs/types/Store.d.ts.map +1 -1
- package/lib/cjs/types/StoreException.d.ts +97 -28
- package/lib/cjs/types/StoreException.d.ts.map +1 -1
- package/lib/cjs/types/StoreProvider.d.ts +80 -0
- package/lib/cjs/types/StoreProvider.d.ts.map +1 -0
- package/lib/cjs/types/UserException.d.ts +178 -169
- package/lib/cjs/types/UserException.d.ts.map +1 -1
- package/lib/cjs/types/index.d.ts +12 -9
- package/lib/cjs/types/index.d.ts.map +1 -1
- package/lib/cjs/types/server.d.ts +12 -0
- package/lib/cjs/types/server.d.ts.map +1 -0
- package/lib/cjs/types/utils.d.ts +15 -1
- package/lib/cjs/types/utils.d.ts.map +1 -1
- package/lib/cjs/utils.js +45 -7
- package/lib/esm/ClassPersistor.mjs +177 -0
- package/lib/esm/Esserializer/{DeserializationOptions.js → DeserializationOptions.mjs} +3 -3
- package/lib/esm/Esserializer/{SerializeOptions.js → SerializeOptions.mjs} +3 -3
- package/lib/esm/Esserializer/builtins.mjs +254 -0
- package/lib/esm/Esserializer/constant.mjs +28 -0
- package/lib/esm/Esserializer/deserializer.mjs +221 -0
- package/lib/esm/Esserializer/general.mjs +81 -0
- package/lib/esm/Esserializer/index.mjs +43 -0
- package/lib/esm/Esserializer/serializer.mjs +164 -0
- package/lib/esm/Evt.mjs +151 -0
- package/lib/esm/Hooks.mjs +1446 -0
- package/lib/esm/KissAction.mjs +4689 -0
- package/lib/esm/LoadPages.mjs +340 -0
- package/lib/esm/Persistor.mjs +180 -0
- package/lib/esm/ProcessPersistence.mjs +581 -0
- package/lib/esm/Store.mjs +4400 -0
- package/lib/esm/StoreException.mjs +153 -0
- package/lib/esm/StoreProvider.mjs +80 -0
- package/lib/esm/{UserException.js → UserException.mjs} +240 -246
- package/lib/esm/{Wait.js → Wait.mjs} +309 -309
- package/lib/esm/index.mjs +12 -9
- package/lib/esm/server.mjs +23 -0
- package/lib/esm/types/ClassPersistor.d.ts +143 -112
- package/lib/esm/types/ClassPersistor.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/DeserializationOptions.d.ts +13 -6
- package/lib/esm/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/SerializeOptions.d.ts +11 -5
- package/lib/esm/types/Esserializer/SerializeOptions.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/builtins.d.ts +36 -0
- package/lib/esm/types/Esserializer/builtins.d.ts.map +1 -0
- package/lib/esm/types/Esserializer/constant.d.ts +25 -49
- package/lib/esm/types/Esserializer/constant.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/deserializer.d.ts +27 -17
- package/lib/esm/types/Esserializer/deserializer.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/general.d.ts +28 -4
- package/lib/esm/types/Esserializer/general.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/index.d.ts +33 -29
- package/lib/esm/types/Esserializer/index.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/serializer.d.ts +14 -3
- package/lib/esm/types/Esserializer/serializer.d.ts.map +1 -1
- package/lib/esm/types/Evt.d.ts +124 -0
- package/lib/esm/types/Evt.d.ts.map +1 -0
- package/lib/esm/types/Hooks.d.ts +1174 -837
- package/lib/esm/types/Hooks.d.ts.map +1 -1
- package/lib/esm/types/KissAction.d.ts +5199 -1398
- package/lib/esm/types/KissAction.d.ts.map +1 -1
- package/lib/esm/types/LoadPages.d.ts +287 -0
- package/lib/esm/types/LoadPages.d.ts.map +1 -0
- package/lib/esm/types/Persistor.d.ts +187 -118
- package/lib/esm/types/Persistor.d.ts.map +1 -1
- package/lib/esm/types/ProcessPersistence.d.ts +197 -99
- package/lib/esm/types/ProcessPersistence.d.ts.map +1 -1
- package/lib/esm/types/Store.d.ts +2253 -1042
- package/lib/esm/types/Store.d.ts.map +1 -1
- package/lib/esm/types/StoreException.d.ts +97 -28
- package/lib/esm/types/StoreException.d.ts.map +1 -1
- package/lib/esm/types/StoreProvider.d.ts +80 -0
- package/lib/esm/types/StoreProvider.d.ts.map +1 -0
- package/lib/esm/types/UserException.d.ts +178 -169
- package/lib/esm/types/UserException.d.ts.map +1 -1
- package/lib/esm/types/index.d.ts +12 -9
- package/lib/esm/types/index.d.ts.map +1 -1
- package/lib/esm/types/server.d.ts +12 -0
- package/lib/esm/types/server.d.ts.map +1 -0
- package/lib/esm/types/utils.d.ts +15 -1
- package/lib/esm/types/utils.d.ts.map +1 -1
- package/lib/esm/utils.mjs +38 -0
- package/package.json +54 -30
- package/lib/cjs/UnmodifiableSetView.js +0 -53
- package/lib/cjs/types/UnmodifiableSetView.d.ts +0 -24
- package/lib/cjs/types/UnmodifiableSetView.d.ts.map +0 -1
- package/lib/esm/ClassPersistor.js +0 -112
- package/lib/esm/Esserializer/constant.js +0 -81
- package/lib/esm/Esserializer/deserializer.js +0 -307
- package/lib/esm/Esserializer/general.js +0 -34
- package/lib/esm/Esserializer/index.js +0 -39
- package/lib/esm/Esserializer/serializer.js +0 -130
- package/lib/esm/Hooks.js +0 -955
- package/lib/esm/KissAction.js +0 -1459
- package/lib/esm/Persistor.js +0 -113
- package/lib/esm/ProcessPersistence.js +0 -262
- package/lib/esm/Store.js +0 -1606
- package/lib/esm/StoreException.js +0 -69
- package/lib/esm/UnmodifiableSetView.js +0 -50
- package/lib/esm/types/UnmodifiableSetView.d.ts +0 -24
- package/lib/esm/types/UnmodifiableSetView.d.ts.map +0 -1
- package/lib/esm/utils.js +0 -3
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// The Esserializer code was copied and adapted from the original copyrighted work, MIT licensed, by cshao.
|
|
2
|
+
// All credit goes to him. See: https://www.npmjs.com/package/esserializer
|
|
3
|
+
import { escapeKey, getClassKey, getValueFromToStringResult, isClass, notObject, setOwnProperty, unescapeKey, } from './general.mjs';
|
|
4
|
+
import { BUILTIN_PREFIX, TYPE_BIGINT, TYPE_FIELD, TYPE_HOLE, TYPE_NULL_PROTOTYPE, TYPE_NUMBER, TYPE_UNDEFINED, VALUE_FIELD, } from './constant.mjs';
|
|
5
|
+
import { findInheritedBuiltinType, getBuiltinTypeBySavedType } from './builtins.mjs';
|
|
6
|
+
const REGEXP_BEGIN_WITH_CLASS = /^\s*class\s+/;
|
|
7
|
+
/**
|
|
8
|
+
* Values tried, in order, for the constructor parameters that have no saved value.
|
|
9
|
+
* Some constructors throw for some values (for example, `{}` where a string is expected),
|
|
10
|
+
* so we try each one until the constructor works.
|
|
11
|
+
*/
|
|
12
|
+
const FALLBACK_CONSTRUCTOR_PARAMETERS = [{}, 0, '', null];
|
|
13
|
+
/**
|
|
14
|
+
* Turns a parsed JSON value back into the original value, creating instances of the
|
|
15
|
+
* given `classes` where the JSON has their names in the `*type` field.
|
|
16
|
+
*/
|
|
17
|
+
function deserializeFromParsedObj(parsedObj, classes, options) {
|
|
18
|
+
//
|
|
19
|
+
return deserializeFromParsedObjWithClassMapping(parsedObj, getClassMappingFromClassArray(classes), options);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Same as `deserializeFromParsedObj`, but with the classes already mapped by name.
|
|
23
|
+
* The `options` apply only to the top-level object, not to nested ones.
|
|
24
|
+
*/
|
|
25
|
+
function deserializeFromParsedObjWithClassMapping(parsedObj, classMapping, options = {}) {
|
|
26
|
+
if (notObject(parsedObj)) {
|
|
27
|
+
return parsedObj;
|
|
28
|
+
}
|
|
29
|
+
const deserializeNested = (value) => deserializeFromParsedObjWithClassMapping(value, classMapping);
|
|
30
|
+
if (Array.isArray(parsedObj)) {
|
|
31
|
+
return _deserializeArray(parsedObj, deserializeNested);
|
|
32
|
+
}
|
|
33
|
+
const type = parsedObj[TYPE_FIELD];
|
|
34
|
+
// A plain object.
|
|
35
|
+
if (type === undefined) {
|
|
36
|
+
return _copyDeserializedValues({}, parsedObj, classMapping, options);
|
|
37
|
+
}
|
|
38
|
+
// A built-in type.
|
|
39
|
+
if (type.startsWith(BUILTIN_PREFIX)) {
|
|
40
|
+
const value = parsedObj[VALUE_FIELD];
|
|
41
|
+
switch (type) {
|
|
42
|
+
case TYPE_UNDEFINED:
|
|
43
|
+
return undefined;
|
|
44
|
+
case TYPE_NUMBER:
|
|
45
|
+
return getValueFromToStringResult(value);
|
|
46
|
+
case TYPE_BIGINT:
|
|
47
|
+
return BigInt(value);
|
|
48
|
+
case TYPE_NULL_PROTOTYPE:
|
|
49
|
+
return _copyDeserializedValues(Object.create(null), parsedObj, classMapping, options);
|
|
50
|
+
}
|
|
51
|
+
const builtinType = getBuiltinTypeBySavedType(type);
|
|
52
|
+
if (!builtinType) {
|
|
53
|
+
throw new Error(`Unknown built-in type "${type}" found during deserialization.`);
|
|
54
|
+
}
|
|
55
|
+
const instance = builtinType.decode(value, deserializeNested);
|
|
56
|
+
return _copyDeserializedValues(instance, parsedObj, classMapping, options);
|
|
57
|
+
}
|
|
58
|
+
// A user class.
|
|
59
|
+
const classObj = Object.prototype.hasOwnProperty.call(classMapping, type) ? classMapping[type] : undefined;
|
|
60
|
+
if (!classObj) {
|
|
61
|
+
throw new Error(`Class "${type}" not found during deserialization. You must register it with: "ESSerializer.registerClass(${type});"`);
|
|
62
|
+
}
|
|
63
|
+
const constructorParameters = (options.fieldsForConstructorParameters ?? []).map((field) => {
|
|
64
|
+
const savedKey = escapeKey(field);
|
|
65
|
+
// Pass `{}` for missing fields, instead of undefined.
|
|
66
|
+
return savedKey in parsedObj ? parsedObj[savedKey] : {};
|
|
67
|
+
});
|
|
68
|
+
const instance = _createInstance(classObj, constructorParameters);
|
|
69
|
+
// A user class that extends a built-in class also has the built-in data, like the entries of a Map.
|
|
70
|
+
if (VALUE_FIELD in parsedObj) {
|
|
71
|
+
findInheritedBuiltinType(instance)?.fill?.(instance, parsedObj[VALUE_FIELD], deserializeNested);
|
|
72
|
+
}
|
|
73
|
+
return _copyDeserializedValues(instance, parsedObj, classMapping, options);
|
|
74
|
+
}
|
|
75
|
+
/** Deserializes the items of an array. Holes saved as `{"*type": "@hole"}` are kept as holes. */
|
|
76
|
+
function _deserializeArray(parsedArray, deserializeNested) {
|
|
77
|
+
const result = new Array(parsedArray.length);
|
|
78
|
+
parsedArray.forEach((item, index) => {
|
|
79
|
+
if (item?.[TYPE_FIELD] !== TYPE_HOLE) {
|
|
80
|
+
result[index] = deserializeNested(item);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Creates an instance of `classObj`, to receive the
|
|
87
|
+
* saved values. Constructor parameters not given in `constructorParameters` are filled with
|
|
88
|
+
* fallback values. If the constructor throws for all of them, the instance is created without
|
|
89
|
+
* calling the constructor.
|
|
90
|
+
*/
|
|
91
|
+
function _createInstance(classObj, constructorParameters) {
|
|
92
|
+
// Not `classObj.toString()`, which may be a static method of the class.
|
|
93
|
+
const isEs6Class = REGEXP_BEGIN_WITH_CLASS.test(Function.prototype.toString.call(classObj));
|
|
94
|
+
const missingParameterCount = Math.max(classObj.length - constructorParameters.length, 0);
|
|
95
|
+
// When no parameter is missing, the fallback values are not used, so we try only once.
|
|
96
|
+
const fallbacks = missingParameterCount === 0
|
|
97
|
+
? FALLBACK_CONSTRUCTOR_PARAMETERS.slice(0, 1)
|
|
98
|
+
: FALLBACK_CONSTRUCTOR_PARAMETERS;
|
|
99
|
+
for (const fallback of fallbacks) {
|
|
100
|
+
const parameters = constructorParameters.concat(new Array(missingParameterCount).fill(fallback));
|
|
101
|
+
const instance = _tryToConstruct(classObj, isEs6Class, parameters);
|
|
102
|
+
if (instance) {
|
|
103
|
+
return instance;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return Object.create(classObj.prototype);
|
|
107
|
+
}
|
|
108
|
+
/** Calls the constructor. Returns `null` if it throws. */
|
|
109
|
+
function _tryToConstruct(classObj, isEs6Class, parameters) {
|
|
110
|
+
try {
|
|
111
|
+
if (isEs6Class) {
|
|
112
|
+
return new classObj(...parameters);
|
|
113
|
+
}
|
|
114
|
+
// A function-style class.
|
|
115
|
+
let constructor = classObj.prototype.constructor;
|
|
116
|
+
if (constructor === Object) {
|
|
117
|
+
// In case the constructor is not in the prototype, such as Big in big.js.
|
|
118
|
+
constructor = classObj;
|
|
119
|
+
}
|
|
120
|
+
const instance = Object.create(constructor.prototype);
|
|
121
|
+
constructor.apply(instance, parameters);
|
|
122
|
+
return instance;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Copies the deserialized values of `parsedObj` into `instance`.
|
|
130
|
+
* Properties with a getter or a setter (own or inherited from the class), and read-only
|
|
131
|
+
* properties with primitive values, keep the value the constructor gave them. Own read-only
|
|
132
|
+
* properties with object values are updated in place (see `_copyInPlace`).
|
|
133
|
+
*/
|
|
134
|
+
function _copyDeserializedValues(instance, parsedObj, classMapping, options) {
|
|
135
|
+
const { ignoreProperties, rawProperties } = options;
|
|
136
|
+
for (const savedKey in parsedObj) {
|
|
137
|
+
if (savedKey === TYPE_FIELD || savedKey === VALUE_FIELD) {
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
const key = unescapeKey(savedKey);
|
|
141
|
+
if (ignoreProperties?.includes(key)) {
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const value = parsedObj[savedKey];
|
|
145
|
+
if (rawProperties?.includes(key)) {
|
|
146
|
+
setOwnProperty(instance, key, JSON.stringify(value));
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const descriptor = _findPropertyDescriptor(instance, key);
|
|
150
|
+
if (descriptor) {
|
|
151
|
+
// A getter or a setter. Setting a getter-only property would throw.
|
|
152
|
+
if (descriptor.get || descriptor.set) {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (descriptor.writable === false) {
|
|
156
|
+
// An inherited object is shared by all instances, so it's not changed.
|
|
157
|
+
if (!notObject(value) && Object.prototype.hasOwnProperty.call(instance, key)) {
|
|
158
|
+
_copyInPlace(instance[key], value, classMapping);
|
|
159
|
+
}
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
setOwnProperty(instance, key, deserializeFromParsedObjWithClassMapping(value, classMapping));
|
|
164
|
+
}
|
|
165
|
+
return instance;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Copies the saved `source` into the existing `target`, in place: the built-in data (like the
|
|
169
|
+
* entries of a Map), and the fields, like `_copyDeserializedValues` does.
|
|
170
|
+
* If `target` is a primitive, it's kept as is.
|
|
171
|
+
*/
|
|
172
|
+
function _copyInPlace(target, source, classMapping) {
|
|
173
|
+
if (notObject(target)) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (VALUE_FIELD in source) {
|
|
177
|
+
const deserializeNested = (value) => deserializeFromParsedObjWithClassMapping(value, classMapping);
|
|
178
|
+
findInheritedBuiltinType(target)?.fill?.(target, source[VALUE_FIELD], deserializeNested);
|
|
179
|
+
}
|
|
180
|
+
_copyDeserializedValues(target, source, classMapping, {});
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Returns the descriptor of the property `key` of `obj`, which may be its own, or inherited
|
|
184
|
+
* from its class. `Object.prototype` is not searched, so that its `__proto__` accessor doesn't
|
|
185
|
+
* hide a saved `__proto__` key.
|
|
186
|
+
*/
|
|
187
|
+
function _findPropertyDescriptor(obj, key) {
|
|
188
|
+
for (let current = obj; current !== null && current !== Object.prototype; current = Object.getPrototypeOf(current)) {
|
|
189
|
+
const descriptor = Object.getOwnPropertyDescriptor(current, key);
|
|
190
|
+
if (descriptor) {
|
|
191
|
+
return descriptor;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Maps each class to the name it's saved under. Items that are not classes (like enums) are
|
|
198
|
+
* ignored. Warns if two different classes are saved under the same name.
|
|
199
|
+
*
|
|
200
|
+
* @param classes Class definitions. They are typed as `any` because TypeScript has no type for classes.
|
|
201
|
+
*/
|
|
202
|
+
function getClassMappingFromClassArray(classes = []) {
|
|
203
|
+
const classMapping = {};
|
|
204
|
+
for (const classObj of classes) {
|
|
205
|
+
if (!isClass(classObj)) {
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const className = getClassKey(classObj);
|
|
209
|
+
const previousClass = classMapping[className];
|
|
210
|
+
if (previousClass && previousClass !== classObj) {
|
|
211
|
+
console.warn('WARNING: Found class definition with the same name: ' + className);
|
|
212
|
+
}
|
|
213
|
+
classMapping[className] = classObj;
|
|
214
|
+
}
|
|
215
|
+
return classMapping;
|
|
216
|
+
}
|
|
217
|
+
/** Returns the name of the parent class of `classObj` (or `Object`, if it has none). */
|
|
218
|
+
function getParentClassName(classObj) {
|
|
219
|
+
return Object.getPrototypeOf(classObj.prototype).constructor.name;
|
|
220
|
+
}
|
|
221
|
+
export { deserializeFromParsedObj, deserializeFromParsedObjWithClassMapping, getClassMappingFromClassArray, getParentClassName };
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// The Esserializer code was copied and adapted from the original copyrighted work, MIT licensed, by cshao.
|
|
2
|
+
// All credit goes to him. See: https://www.npmjs.com/package/esserializer
|
|
3
|
+
import { KEY_ESCAPE } from './constant.mjs';
|
|
4
|
+
/** Returns true for primitives (including `null`), and for functions. */
|
|
5
|
+
function notObject(target) {
|
|
6
|
+
return target === null || typeof target !== 'object';
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Converts the text form of a number JSON can't represent back into the number.
|
|
10
|
+
* Returns `null` for any other text.
|
|
11
|
+
*/
|
|
12
|
+
function getValueFromToStringResult(text) {
|
|
13
|
+
switch (text) {
|
|
14
|
+
case 'Infinity':
|
|
15
|
+
return Infinity;
|
|
16
|
+
case '-Infinity':
|
|
17
|
+
return -Infinity;
|
|
18
|
+
case 'NaN':
|
|
19
|
+
return NaN;
|
|
20
|
+
case '-0':
|
|
21
|
+
return -0;
|
|
22
|
+
default:
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Returns the name a class is saved under: its own static `typeName`, if it has one,
|
|
28
|
+
* or else its class name. A `typeName` inherited from a parent class is ignored.
|
|
29
|
+
*/
|
|
30
|
+
function getClassKey(classObj) {
|
|
31
|
+
if (Object.prototype.hasOwnProperty.call(classObj, 'typeName')) {
|
|
32
|
+
return classObj.typeName;
|
|
33
|
+
}
|
|
34
|
+
return classObj.name;
|
|
35
|
+
}
|
|
36
|
+
/** Built-in classes that may be registered for deserialization, as if they were user classes. */
|
|
37
|
+
const SUPPORTED_BUILTIN_CLASSES = new Set([Date]);
|
|
38
|
+
/** Returns true if `target` can be called with `new` (a class, or a function-style class). */
|
|
39
|
+
function isClass(target) {
|
|
40
|
+
if (SUPPORTED_BUILTIN_CLASSES.has(target)) {
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
// `Reflect.construct` throws if `target` can't be used as a constructor.
|
|
44
|
+
// See https://stackoverflow.com/a/46759625/707451
|
|
45
|
+
try {
|
|
46
|
+
Reflect.construct(String, [], target);
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Returns true if `fn` is implemented by the JavaScript engine, not by user code. */
|
|
54
|
+
function isNativeFunction(fn) {
|
|
55
|
+
return /\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(fn));
|
|
56
|
+
}
|
|
57
|
+
/** Escapes a user key, so that it's not confused with the metadata fields. */
|
|
58
|
+
function escapeKey(key) {
|
|
59
|
+
return key.startsWith(KEY_ESCAPE) ? KEY_ESCAPE + key : key;
|
|
60
|
+
}
|
|
61
|
+
/** Reverses `escapeKey`. */
|
|
62
|
+
function unescapeKey(savedKey) {
|
|
63
|
+
return savedKey.startsWith(KEY_ESCAPE) ? savedKey.substring(KEY_ESCAPE.length) : savedKey;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Sets an own property. Unlike `obj[key] = value`, this also works for the key `__proto__`,
|
|
67
|
+
* which would otherwise change the prototype of `obj`, instead of creating a property.
|
|
68
|
+
*/
|
|
69
|
+
function setOwnProperty(obj, key, value) {
|
|
70
|
+
if (key === '__proto__') {
|
|
71
|
+
Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
obj[key] = value;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Sets a non-enumerable own property, like the `message` of an error. */
|
|
78
|
+
function setHiddenProperty(obj, key, value) {
|
|
79
|
+
Object.defineProperty(obj, key, { value, writable: true, enumerable: false, configurable: true });
|
|
80
|
+
}
|
|
81
|
+
export { getValueFromToStringResult, notObject, isClass, isNativeFunction, getClassKey, escapeKey, unescapeKey, setOwnProperty, setHiddenProperty, };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// The Esserializer code was copied and adapted from the original copyrighted work, MIT licensed, by cshao.
|
|
2
|
+
// All credit goes to him. See: https://www.npmjs.com/package/esserializer
|
|
3
|
+
import { getSerializeValueWithClassName } from './serializer.mjs';
|
|
4
|
+
import { deserializeFromParsedObj } from './deserializer.mjs';
|
|
5
|
+
/**
|
|
6
|
+
* Serializes values into JSON text, keeping their classes, and deserializes them back
|
|
7
|
+
* into instances of those classes. Also supports built-in types JSON doesn't, like
|
|
8
|
+
* `undefined`, `NaN`, BigInt, Date, Map, Set, typed arrays, errors and Intl objects.
|
|
9
|
+
*/
|
|
10
|
+
export class ESSerializer {
|
|
11
|
+
/** Classes available to every `deserialize` call, in addition to the ones passed to it. */
|
|
12
|
+
static registeredClasses = [];
|
|
13
|
+
/** Globally registers classes or enums. */
|
|
14
|
+
static registerClasses(classesOrEnums) {
|
|
15
|
+
this.registeredClasses.push(...classesOrEnums);
|
|
16
|
+
}
|
|
17
|
+
/** Globally registers a class or enum. */
|
|
18
|
+
static registerClass(classOrEnum) {
|
|
19
|
+
this.registeredClasses.push(classOrEnum);
|
|
20
|
+
}
|
|
21
|
+
/** Clears all globally registered classes. */
|
|
22
|
+
static clearRegisteredClasses() {
|
|
23
|
+
this.registeredClasses = [];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Converts `target` into JSON text. The `target` is not changed.
|
|
27
|
+
* @param target The value to serialize.
|
|
28
|
+
* @param options Serialization options.
|
|
29
|
+
*/
|
|
30
|
+
static serialize(target, options = {}) {
|
|
31
|
+
return JSON.stringify(getSerializeValueWithClassName(target, options));
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Converts JSON text created by `serialize` back into the original value.
|
|
35
|
+
* @param serializedText The JSON text.
|
|
36
|
+
* @param classes Classes needed to deserialize the text, in addition to the registered ones.
|
|
37
|
+
* @param options Deserialization options.
|
|
38
|
+
*/
|
|
39
|
+
static deserialize(serializedText, classes = [], options = {}) {
|
|
40
|
+
//
|
|
41
|
+
return deserializeFromParsedObj(JSON.parse(serializedText), this.registeredClasses.concat(classes), options);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// The Esserializer code was copied and adapted from the original copyrighted work, MIT licensed, by cshao.
|
|
2
|
+
// All credit goes to him. See: https://www.npmjs.com/package/esserializer
|
|
3
|
+
import { BUILTIN_PREFIX, TYPE_BIGINT, TYPE_FIELD, TYPE_HOLE, TYPE_NULL_PROTOTYPE, TYPE_NUMBER, TYPE_UNDEFINED, VALUE_FIELD, } from './constant.mjs';
|
|
4
|
+
import { escapeKey, getClassKey, isNativeFunction, setOwnProperty } from './general.mjs';
|
|
5
|
+
import { findInheritedBuiltinType, getBuiltinTypeByConstructor } from './builtins.mjs';
|
|
6
|
+
/**
|
|
7
|
+
* Converts `target` into a plain JSON-compatible value. Objects get a `*type` field with
|
|
8
|
+
* their class name, so that they can be deserialized back into instances of that class.
|
|
9
|
+
*
|
|
10
|
+
* The `options` apply only to the top-level object, not to nested ones.
|
|
11
|
+
* The `target` itself is never changed.
|
|
12
|
+
*
|
|
13
|
+
* Throws for values that can't be deserialized back: functions and symbols (except as
|
|
14
|
+
* object properties, which are skipped), circular references, and built-in classes that
|
|
15
|
+
* are not supported (like `WeakMap` or `Promise`).
|
|
16
|
+
*/
|
|
17
|
+
function getSerializeValueWithClassName(target, options = {}) {
|
|
18
|
+
return new Serializer().serialize(target, options);
|
|
19
|
+
}
|
|
20
|
+
class Serializer {
|
|
21
|
+
/** The objects being serialized, from the top-level one down to the current one. */
|
|
22
|
+
ancestors = new Set();
|
|
23
|
+
/** Serializes a value. Arrow function, so that it can be passed around as a callback. */
|
|
24
|
+
serializeNested = (target) => this.serialize(target);
|
|
25
|
+
serialize(target, options = {}) {
|
|
26
|
+
if (typeof target !== 'object' || target === null) {
|
|
27
|
+
return _serializePrimitive(target);
|
|
28
|
+
}
|
|
29
|
+
if (this.ancestors.has(target)) {
|
|
30
|
+
throw new Error('Cannot serialize a circular reference.');
|
|
31
|
+
}
|
|
32
|
+
this.ancestors.add(target);
|
|
33
|
+
try {
|
|
34
|
+
return Array.isArray(target) && Object.getPrototypeOf(target) === Array.prototype
|
|
35
|
+
? this._serializeArray(target)
|
|
36
|
+
: this._serializeObject(target, options);
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
this.ancestors.delete(target);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Saves holes of sparse arrays as `{"*type": "@hole"}`, as JSON would turn them into null. */
|
|
43
|
+
_serializeArray(arr) {
|
|
44
|
+
const result = new Array(arr.length);
|
|
45
|
+
for (let index = 0; index < arr.length; index++) {
|
|
46
|
+
result[index] = index in arr ? this.serialize(arr[index]) : { [TYPE_FIELD]: TYPE_HOLE };
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
_serializeObject(target, options) {
|
|
51
|
+
// An object with no prototype.
|
|
52
|
+
if (Object.getPrototypeOf(target) === null) {
|
|
53
|
+
const serializedObj = this._serializeProperties(target, options);
|
|
54
|
+
serializedObj[TYPE_FIELD] = TYPE_NULL_PROTOTYPE;
|
|
55
|
+
return serializedObj;
|
|
56
|
+
}
|
|
57
|
+
const constructor = _getConstructor(target);
|
|
58
|
+
// A plain object (or one whose prototype has no constructor).
|
|
59
|
+
if (constructor === undefined || constructor === Object) {
|
|
60
|
+
return this._serializeProperties(target, options);
|
|
61
|
+
}
|
|
62
|
+
// A built-in class.
|
|
63
|
+
const builtinType = getBuiltinTypeByConstructor(constructor);
|
|
64
|
+
if (builtinType) {
|
|
65
|
+
const serializedObj = builtinType.hasItemProperties
|
|
66
|
+
? {}
|
|
67
|
+
: this._serializeProperties(target, options, builtinType.keysSavedInValue);
|
|
68
|
+
serializedObj[TYPE_FIELD] = BUILTIN_PREFIX + builtinType.name;
|
|
69
|
+
serializedObj[VALUE_FIELD] = builtinType.encode(target, this.serializeNested);
|
|
70
|
+
return serializedObj;
|
|
71
|
+
}
|
|
72
|
+
if (isNativeFunction(constructor)) {
|
|
73
|
+
throw new Error(`Cannot serialize a ${constructor.name}: this class is not supported.`);
|
|
74
|
+
}
|
|
75
|
+
// A user class.
|
|
76
|
+
const className = getClassKey(constructor);
|
|
77
|
+
if (className.startsWith(BUILTIN_PREFIX)) {
|
|
78
|
+
throw new Error(`Cannot serialize class "${className}": class names can't start with "${BUILTIN_PREFIX}".`);
|
|
79
|
+
}
|
|
80
|
+
// A user class that extends a built-in class also saves the built-in data, like the entries of a Map.
|
|
81
|
+
const inheritedType = findInheritedBuiltinType(target);
|
|
82
|
+
if (inheritedType && !inheritedType.fill) {
|
|
83
|
+
throw new Error(`Cannot serialize class "${className}": subclasses of ${inheritedType.name} are not supported.`);
|
|
84
|
+
}
|
|
85
|
+
const serializedObj = this._serializeProperties(target, options, inheritedType?.keysSavedInValue);
|
|
86
|
+
serializedObj[TYPE_FIELD] = className;
|
|
87
|
+
if (inheritedType) {
|
|
88
|
+
serializedObj[VALUE_FIELD] = inheritedType.encode(target, this.serializeNested);
|
|
89
|
+
}
|
|
90
|
+
return serializedObj;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Serializes the enumerable properties of `source`, skipping functions and symbols.
|
|
94
|
+
* Properties in `options.ignoreProperties` are skipped, and properties in
|
|
95
|
+
* `options.interceptProperties` are replaced by the result of their interceptor.
|
|
96
|
+
* The `keysSavedInValue` are skipped, as they are saved in `*value`.
|
|
97
|
+
*/
|
|
98
|
+
_serializeProperties(source, options, keysSavedInValue = []) {
|
|
99
|
+
const ignored = options.ignoreProperties;
|
|
100
|
+
const interceptors = options.interceptProperties;
|
|
101
|
+
const serializedObj = {};
|
|
102
|
+
const copy = (key, value) => {
|
|
103
|
+
if (typeof value !== 'function' && typeof value !== 'symbol') {
|
|
104
|
+
setOwnProperty(serializedObj, escapeKey(key), this.serialize(value));
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
// The items of an array subclass are saved apart, in `*value`.
|
|
108
|
+
const isArray = Array.isArray(source);
|
|
109
|
+
for (const key in source) {
|
|
110
|
+
if (ignored?.includes(key) || keysSavedInValue.includes(key) || (isArray && _isArrayIndex(key))) {
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const hasInterceptor = interceptors !== undefined && Object.prototype.hasOwnProperty.call(interceptors, key);
|
|
114
|
+
copy(key, hasInterceptor ? interceptors[key].call(source, source[key]) : source[key]);
|
|
115
|
+
}
|
|
116
|
+
// Interceptors may also add properties the object doesn't have.
|
|
117
|
+
if (interceptors) {
|
|
118
|
+
for (const key in interceptors) {
|
|
119
|
+
if (!(key in source) && !ignored?.includes(key)) {
|
|
120
|
+
copy(key, interceptors[key].call(source, undefined));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return serializedObj;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Returns the class of `target`, which must have a prototype. Returns undefined if the
|
|
129
|
+
* prototype has no constructor.
|
|
130
|
+
* Usually it's the constructor of the prototype, but when that is `Object`, it's the
|
|
131
|
+
* `constructor` property of the object itself, as in Big from big.js. That property is used
|
|
132
|
+
* only if it's a function, as a plain object may have a `constructor` key with any value.
|
|
133
|
+
*/
|
|
134
|
+
function _getConstructor(target) {
|
|
135
|
+
const constructor = Object.getPrototypeOf(target).constructor;
|
|
136
|
+
if (constructor === Object) {
|
|
137
|
+
const ownConstructor = target.constructor;
|
|
138
|
+
return typeof ownConstructor === 'function' ? ownConstructor : Object;
|
|
139
|
+
}
|
|
140
|
+
return constructor;
|
|
141
|
+
}
|
|
142
|
+
function _isArrayIndex(key) {
|
|
143
|
+
return /^(0|[1-9]\d*)$/.test(key);
|
|
144
|
+
}
|
|
145
|
+
/** Serializes primitives. Values JSON can't represent become objects with a special `*type`. */
|
|
146
|
+
function _serializePrimitive(target) {
|
|
147
|
+
switch (typeof target) {
|
|
148
|
+
case 'undefined':
|
|
149
|
+
return { [TYPE_FIELD]: TYPE_UNDEFINED };
|
|
150
|
+
case 'number':
|
|
151
|
+
if (!Number.isFinite(target) || Object.is(target, -0)) {
|
|
152
|
+
return { [TYPE_FIELD]: TYPE_NUMBER, [VALUE_FIELD]: Object.is(target, -0) ? '-0' : target.toString() };
|
|
153
|
+
}
|
|
154
|
+
return target;
|
|
155
|
+
case 'bigint':
|
|
156
|
+
return { [TYPE_FIELD]: TYPE_BIGINT, [VALUE_FIELD]: target.toString() };
|
|
157
|
+
case 'function':
|
|
158
|
+
case 'symbol':
|
|
159
|
+
throw new Error(`Cannot serialize a ${typeof target}.`);
|
|
160
|
+
default:
|
|
161
|
+
return target; // string, boolean or null.
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
export { getSerializeValueWithClassName };
|
package/lib/esm/Evt.mjs
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An event: a one-time notification kept in the store state, for an action to ask the UI to
|
|
3
|
+
* do something once, that is not a state change: scroll a list to the top, clear or focus an
|
|
4
|
+
* input, open a dialog. The UI keeps these things itself (DOM elements, refs, scroll
|
|
5
|
+
* positions), so the reducer can't reach them.
|
|
6
|
+
*
|
|
7
|
+
* Name event fields with the `Evt` suffix, like `scrollToTopEvt`. In the initial state, use
|
|
8
|
+
* `Evt.spent()`, an event that was already used, so that nothing fires when the app starts.
|
|
9
|
+
* Actions then put a new event in the state:
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* class State {
|
|
13
|
+
* constructor(
|
|
14
|
+
* readonly messages: readonly Message[],
|
|
15
|
+
* readonly scrollToTopEvt: Evt, // A boolean event.
|
|
16
|
+
* readonly changeTextEvt: Evt<string>, // An event with a value.
|
|
17
|
+
* ) {}
|
|
18
|
+
*
|
|
19
|
+
* static initialState = new State([], Evt.spent(), Evt.spent());
|
|
20
|
+
* }
|
|
21
|
+
*
|
|
22
|
+
* class ScrollFeedToTop extends Action {
|
|
23
|
+
* reduce() { return this.state.copy({ scrollToTopEvt: new Evt() }); }
|
|
24
|
+
* }
|
|
25
|
+
*
|
|
26
|
+
* class ChangeText extends Action {
|
|
27
|
+
* async reduce() {
|
|
28
|
+
* const text = await api.fetchText();
|
|
29
|
+
* return (state: State) => state.copy({ changeTextEvt: new Evt(text) });
|
|
30
|
+
* }
|
|
31
|
+
* }
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* Components handle the event with the `useEvent` hook (or `useLayoutEvent`), which calls the
|
|
35
|
+
* callback once per event, with its value, and then marks the event as **spent**:
|
|
36
|
+
*
|
|
37
|
+
* ```tsx
|
|
38
|
+
* useEvent((state: State) => state.scrollToTopEvt, () => listRef.current?.scrollTo({ top: 0 }));
|
|
39
|
+
* useEvent((state: State) => state.changeTextEvt, (text) => { inputRef.current!.value = text; });
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* `new Evt()` is a boolean event, whose `value` is `true`. `new Evt(value)` holds a value of
|
|
43
|
+
* any type. Each new event is a new object, so a new event always fires, even if its value is
|
|
44
|
+
* the same as the previous one. Reading `value` doesn't spend the event.
|
|
45
|
+
*
|
|
46
|
+
* The event object itself is immutable: the store keeps which events were spent (see
|
|
47
|
+
* `store.isEventSpent`). So the state stays immutable, and two stores that share the same
|
|
48
|
+
* state (in two tests, for example) each spend the event on their own.
|
|
49
|
+
*
|
|
50
|
+
* Each event is handled by one component only: the first one whose effect runs. For two
|
|
51
|
+
* components to react, create two events in the state. Or use `EvtState`, when it's fine to
|
|
52
|
+
* miss events that happen while the component is not mounted.
|
|
53
|
+
*
|
|
54
|
+
* Persistence: the `ClassPersistor` saves events as spent, and restores them as `Evt.spent()`,
|
|
55
|
+
* so an old event doesn't fire when the app starts. A custom persistor must do the same: never
|
|
56
|
+
* save events, or restore them as `Evt.spent()`.
|
|
57
|
+
*
|
|
58
|
+
* You don't need events when:
|
|
59
|
+
* - The component dispatched the action itself. It can wait for the action, and then act:
|
|
60
|
+
* `await dispatchAndWait(new SendMessage(text)); inputRef.current!.value = '';`
|
|
61
|
+
* - There's already a state change to react to. Do it in an effect: for example, scroll to
|
|
62
|
+
* the end when a message arrives: `useEffect(() => scrollToEnd(), [messages.length])`.
|
|
63
|
+
*/
|
|
64
|
+
export class Evt {
|
|
65
|
+
/**
|
|
66
|
+
* The value of the event: `true` for a boolean event (`new Evt()`), or the value given to
|
|
67
|
+
* the constructor. Reading it doesn't spend the event. It's `undefined` for `Evt.spent()`,
|
|
68
|
+
* and for a restored (persisted) event. Components should get the value from `useEvent`,
|
|
69
|
+
* which also spends the event.
|
|
70
|
+
*/
|
|
71
|
+
value;
|
|
72
|
+
/**
|
|
73
|
+
* Internal: `true` for `Evt.spent()`, and for a restored (persisted) event. Such an event is
|
|
74
|
+
* spent in every store. Use `store.isEventSpent(evt)` instead.
|
|
75
|
+
* @internal
|
|
76
|
+
*/
|
|
77
|
+
_spentAtCreation;
|
|
78
|
+
/**
|
|
79
|
+
* Creates a new, unspent event. `new Evt()` is a boolean event, whose `value` is `true`.
|
|
80
|
+
* `new Evt(value)` holds a value of any type.
|
|
81
|
+
*/
|
|
82
|
+
constructor(value) {
|
|
83
|
+
this.value = (value === undefined ? true : value);
|
|
84
|
+
this._spentAtCreation = false;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* An event that was already used, for the initial state. It never fires, in any store, and
|
|
88
|
+
* has no value (`undefined`).
|
|
89
|
+
*/
|
|
90
|
+
static spent() {
|
|
91
|
+
const evt = new Evt();
|
|
92
|
+
return Object.assign(evt, { value: undefined, _spentAtCreation: true });
|
|
93
|
+
}
|
|
94
|
+
toString() {
|
|
95
|
+
return this._spentAtCreation ? 'Evt.spent()' : `Evt(${String(this.value)})`;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* An event that is never spent, so that all the mounted components that use it react to it,
|
|
100
|
+
* but only while they are mounted. It's an alternative to `Evt`, which fires once, in one
|
|
101
|
+
* component only, even if the component mounts later.
|
|
102
|
+
*
|
|
103
|
+
* Each `new EvtState(value)` is a new object. A component that uses it with `useEvent` (or
|
|
104
|
+
* `useLayoutEvent`) is called when the state has a different `EvtState` than the last one the
|
|
105
|
+
* component saw. So it doesn't fire when the component mounts (or remounts), nor on unrelated
|
|
106
|
+
* re-renders, and it fires in every mounted component that uses it, even if the value is the
|
|
107
|
+
* same as the previous one.
|
|
108
|
+
*
|
|
109
|
+
* In the initial state, use `EvtState.spent()`, which never fires, so that nothing fires after
|
|
110
|
+
* a `logOut` puts the initial state back. The `ClassPersistor` also restores an `EvtState` as
|
|
111
|
+
* `EvtState.spent()`.
|
|
112
|
+
*
|
|
113
|
+
* ```ts
|
|
114
|
+
* class State {
|
|
115
|
+
* constructor(readonly highlightEvt: EvtState<string>) {}
|
|
116
|
+
* static initialState = new State(EvtState.spent());
|
|
117
|
+
* }
|
|
118
|
+
*
|
|
119
|
+
* // In an action:
|
|
120
|
+
* reduce() { return this.state.copy({ highlightEvt: new EvtState(this.itemId) }); }
|
|
121
|
+
*
|
|
122
|
+
* // In any number of components:
|
|
123
|
+
* useEvent((state: State) => state.highlightEvt, (itemId) => highlight(itemId));
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
export class EvtState {
|
|
127
|
+
/**
|
|
128
|
+
* The value of the event: `true` for `new EvtState()`, or the value given to the constructor.
|
|
129
|
+
* It's `undefined` for `EvtState.spent()`, and for a restored (persisted) event.
|
|
130
|
+
*/
|
|
131
|
+
value;
|
|
132
|
+
/**
|
|
133
|
+
* Internal: `true` for `EvtState.spent()`, and for a restored (persisted) event, which never
|
|
134
|
+
* fire. Use `store.isEventSpent(evt)` instead.
|
|
135
|
+
* @internal
|
|
136
|
+
*/
|
|
137
|
+
_spentAtCreation;
|
|
138
|
+
/** Creates a new event. `new EvtState()` has the value `true`. `new EvtState(value)` holds a value. */
|
|
139
|
+
constructor(value) {
|
|
140
|
+
this.value = (value === undefined ? true : value);
|
|
141
|
+
this._spentAtCreation = false;
|
|
142
|
+
}
|
|
143
|
+
/** An event that never fires, for the initial state. It has no value (`undefined`). */
|
|
144
|
+
static spent() {
|
|
145
|
+
const evt = new EvtState();
|
|
146
|
+
return Object.assign(evt, { value: undefined, _spentAtCreation: true });
|
|
147
|
+
}
|
|
148
|
+
toString() {
|
|
149
|
+
return this._spentAtCreation ? 'EvtState.spent()' : `EvtState(${String(this.value)})`;
|
|
150
|
+
}
|
|
151
|
+
}
|