react-smart-state
Version:
Next generation local and global state management
190 lines (189 loc) • 6.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.valid = exports.isArray = exports.getValueByPath = exports.keys = exports.toObject = exports.sleep = exports.newId = exports.isSame = exports.clone = exports.reactState = exports.reactRef = exports.reactEffect = void 0;
exports.updater = updater;
exports.SmartStateError = SmartStateError;
exports.isPromise = isPromise;
exports.getItem = getItem;
exports.refCondition = refCondition;
exports.getPrototypeChain = getPrototypeChain;
const react_1 = require("react");
const objects_1 = require("./objects");
exports.reactEffect = react_1.useEffect;
exports.reactRef = react_1.useRef;
exports.reactState = react_1.useState;
function updater() {
const [value, setValue] = (0, exports.reactState)(0);
return ({
value,
refresh: () => {
setValue(prev => (prev < 1000 ? prev + 1 : 1));
}
});
}
function SmartStateError(err, extraInfo) {
const message = err instanceof Error ? err.message : typeof err === 'string' ? err : 'Unknown error';
const item = new objects_1.CustomError(message, {
originalError: err,
code: extraInfo === null || extraInfo === void 0 ? void 0 : extraInfo.code,
details: extraInfo === null || extraInfo === void 0 ? void 0 : extraInfo.details,
});
console.error(item);
return item;
}
const clone = (o) => {
var _a, _b;
if (!(0, exports.valid)(o, true))
return o;
let item = o;
if (((_a = item.getInstanceType) === null || _a === void 0 ? void 0 : _a.call(item)) === "react-smart-state-item")
return Object.assign({}, item);
if (((_b = item.getInstanceType) === null || _b === void 0 ? void 0 : _b.call(item)) === "react-smart-state-array")
return [...o];
return o;
};
exports.clone = clone;
const isSame = (a, b) => {
if ((0, exports.valid)(a, true) && (0, exports.valid)(b, true)) {
return a === b;
}
return false;
};
exports.isSame = isSame;
let ids = new Map();
let lastDate = new Date();
const newId = (inc) => {
if ((Date.now() - lastDate.getTime()) > 60 * 1000) {
ids = new Map();
lastDate = new Date();
}
let id = (inc !== null && inc !== void 0 ? inc : "") + Date.now().toString(36) + Math.floor(1e12 + Math.random() * 9e12).toString(36);
if (ids.has(id)) {
// Retry without prefix to avoid exponential growth
return (0, exports.newId)();
}
if (ids.size >= 1000)
ids.clear();
ids.set(id, id);
return id;
};
exports.newId = newId;
function isPromise(obj) {
return !!obj && typeof obj.then === 'function';
}
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
exports.sleep = sleep;
function getItem(item) {
if (!item)
throw "item cannot be undefined or null";
if (typeof item === "function")
return getItem(item());
return item;
}
function refCondition(fn) {
const ref = (0, exports.reactRef)(undefined);
if (ref.current == undefined)
ref.current = fn();
return { value: ref.current, setValue: (value) => ref.current = value };
}
const toObject = (nested = false, ...keys) => {
if (keys.length === 0)
return { AllKeys: true, _keys: keys };
let item = keys.reduce((c, v) => {
c[v] = true;
if (nested) {
let parts = v.split(".");
if (parts.length > 1) {
let fullKey = "";
for (let p of parts) {
fullKey += p + ".";
c[fullKey] = true;
}
}
}
return c;
}, { _keys: keys });
return item;
};
exports.toObject = toObject;
function getPrototypeChain(obj) {
let prototypeChain = [];
(function innerRecursiveFunction(obj) {
let currentPrototype = obj != null ? Object.getPrototypeOf(obj) : null;
prototypeChain.push(currentPrototype);
if (currentPrototype != null) {
innerRecursiveFunction(currentPrototype);
}
})(obj);
return prototypeChain.filter(x => x !== null);
}
const keys = (item, prototype) => {
let prototypes = getPrototypeChain(item);
let ks = [
...Object.keys(item),
...prototypes.flatMap(x => Object.getOwnPropertyNames(x))
];
let obp = Object.getOwnPropertyNames(Object.prototype);
let cbp = Object.getOwnPropertyNames(prototype);
ks = ks
.filter(x => !obp.includes(x) && !cbp.includes(x))
.filter((value, index, array) => array.indexOf(value) === index);
// alert(JSON.stringify(ks, undefined, 4));
return ks;
};
exports.keys = keys;
const getValueByPath = (value, path) => {
if (!path)
return value;
const segments = path.split(".");
let current = value;
for (const key of segments) {
if (current == null || current == undefined)
return undefined; // handles null and undefined
current = current[key];
}
return current;
};
exports.getValueByPath = getValueByPath;
const isArray = (item) => {
var _a, _b;
if (item == undefined || item === null)
return false;
if (Array.isArray(item) || ((_b = (_a = item).getInstanceType) === null || _b === void 0 ? void 0 : _b.call(_a)) === "react-smart-state-array")
return true;
return false;
};
exports.isArray = isArray;
const valid = (item, validArray) => {
if (item === undefined || item === null)
return false;
if (typeof item === "string")
return false;
if (typeof item === "function")
return false;
if (item instanceof Set)
return false;
if (item instanceof Map)
return false;
if (item instanceof WeakSet)
return false;
if (item instanceof WeakMap)
return false;
if (item instanceof Date)
return false;
if (item instanceof RegExp)
return false;
if (item instanceof ArrayBuffer)
return false;
if (ArrayBuffer.isView(item))
return false; // covers Uint8Array, Float32Array, etc.
if (item instanceof Promise)
return false;
if ((0, exports.isArray)(item) && item.length > 0) {
if (validArray)
return (0, exports.valid)(item[0], validArray);
return false;
}
return typeof item === "object";
};
exports.valid = valid;