nucleux
Version:
Simple, atomic hub for all your React application's state management needs. No providers, no boilerplate, just state that works.
79 lines (78 loc) • 2.81 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Store = void 0;
const auto_bind_1 = __importDefault(require("auto-bind"));
const Atom_1 = require("./Atom");
const debug_utils_1 = require("./debug-utils");
const Injectable_1 = require("./Injectable");
const utils_1 = require("./utils");
class Store extends Injectable_1.Injectable {
subscriptions = new Map();
storage;
constructor() {
super();
(0, auto_bind_1.default)(this);
}
atom(initialValue, options) {
let atomOptions = options;
if (options?.persistence && !options.persistence.storage && this.storage) {
atomOptions = {
...options,
persistence: {
...options.persistence,
storage: this.storage,
},
};
}
return new Atom_1.Atom(initialValue, atomOptions);
}
watchAtom(atom, callback, immediate = false) {
const subId = atom.subscribe(callback, immediate);
this.subscriptions.set(subId, atom.unsubscribe);
}
deriveAtom(sourceAtoms, transformer, memoization) {
function getDerivedValue() {
const values = sourceAtoms.map((atom) => {
return atom.value;
});
return transformer(...values);
}
const derivedAtom = new Atom_1.Atom(getDerivedValue(), { memoization });
function computedValueCallback() {
const newComputedValue = getDerivedValue();
derivedAtom.value = newComputedValue;
}
sourceAtoms.forEach((atom) => {
this.watchAtom(atom, computedValueCallback);
});
return derivedAtom;
}
enableDebug() {
console.log(`Nucleux debugging enabled for store: ${this.constructor.name}`);
for (const key in this) {
const potentialAtom = this[key];
if ((0, utils_1.isAtom)(potentialAtom) && potentialAtom instanceof Atom_1.Atom) {
this.watchAtom(potentialAtom, (newValue, previousValue) => {
(0, debug_utils_1.logAtomChange)({
storeName: this.constructor.name,
atomName: key,
newValue,
previousValue,
timestamp: Date.now(),
});
});
}
}
}
destroy() {
for (const [subId, unsubscribe] of this.subscriptions) {
unsubscribe(subId);
this.subscriptions.delete(subId);
}
super.destroy();
}
}
exports.Store = Store;