Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 | 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 10124x 10124x 3x 79x 79x 79x 79x 122x 1x 1x 1x 1x 1x 121x 121x 121x 109x 109x 108x 108x 108x 121x 121x 121x 14x 14x 14x 14x 14x 14x 12x 12x 14x 14x 79x 190x 79x 6x 6x 6x 6x 6x 11077x 11077x 11077x 11077x 11077x 12071x 12071x 124x 300x 10x 191x 191x 7x 184x 184x 184x 184x 14x 184x 110x 184x 20021x 10001x 11x 10022x 1x 10021x 10021x 10021x 10021x 10002x 10021x 2x 11014x 11014x 11014x 11014x 11014x 11014x 11014x 11014x 1013x 1013x 1013x 31042x 11032x 11032x 11037x 2x 11035x 4x 2x 11033x 2x 2x 2x 11033x 11033x 11033x 11033x 11033x 11033x 11033x 5x 5x 5x 11033x 11033x 11028x 10023x 16x 10023x 10026x 11028x 11028x 11028x 11026x 11026x 14x 14x 14x 14x 14x 10009x 10009x 10010x 10000x 10000x 10010x 10010x 10010x 10010x 10010x 1x 10009x 10010x 10009x 10000x 10000x 4x 184x 14x 14x 15x 14x 13x 6x 6x 6x 6x 6x 2x 2x 2x 2x 2x 1x 1x 2x 17x 17x 17x 17x 17x 17x 17x 17x 43x 78x 78x 45x 45x 78x 65x 65x 184x 22x 22x 108x 108x 11x 97x 108x 51x 51x 64x 64x 64x 64x 64x 64x 64x 64x 5x 5x 4x 5x 5x 59x 11x 59x 59x 65x 4x 4x 3x 3x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 2x 6x 6x 2x 4x 2x 4x 4x 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 2x 2x 1x 64x 64x 64x 19x 18x 18x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 10x 10x 17x 18x 11009x 4x | /**
* Reactive State Management System for Coherent.js
* Provides computed properties, watchers, and reactive updates
*
* Design:
*
* - Reading an Observable or Computed inside a computed getter records it as a
* dependency. A Computed recomputes lazily, on read, and only when a
* dependency actually changed (version check).
* - A Computed that is watched, or that a watched Computed depends on, is
* "live": it subscribes to its dependencies so a change marks it dirty and
* schedules its watchers. When it stops being watched it unsubscribes, so
* nothing keeps a discarded computed reachable.
* - Watchers do not run inside the setter: changes are queued and flushed in
* a loop once the outermost batch() ends (every write outside a batch is its
* own batch). A watcher that writes queues further work instead of
* recursing; a loop that never settles is stopped and reported.
* - Each watcher runs in isolation: an error is reported through the
* `onError` option, or `globalErrorHandler`, and the other watchers still run.
* - Reading a computed that (indirectly) reads itself throws a StateError.
*/
// Simple error handling for this module
export class StateError extends Error {
constructor(message, options = {}) {
super(message);
this.name = 'StateError';
this.type = options.type || 'state';
this.component = options.component;
this.context = options.context;
this.timestamp = Date.now();
}
}
export const globalErrorHandler = {
handle(error, context = {}) {
console.error('State Error:', error.message, context);
}
};
/** Flush iterations after which a watcher loop is considered runaway. */
const MAX_FLUSH_ITERATIONS = 100;
/** The computed currently collecting dependencies. */
let activeComputed = null;
/** Nesting depth of batch(). */
let batchDepth = 0;
/** Whether the notification queue is being flushed. */
let flushing = false;
/** Observables with watchers that changed: observable -> value before the change. */
const pendingObservables = new Map();
/** Watched computeds whose dependencies changed. */
const pendingComputeds = new Set();
/** Bumped on every write, so an unobserved computed can skip validation. */
let globalVersion = 0;
function reportError(source, error, type, context = {}) {
const onError = source?._options?.onError;
if (typeof onError === 'function') {
try {
onError(error, { type, ...context });
return;
} catch (handlerError) {
error = handlerError;
}
}
globalErrorHandler.handle(error, { type, context });
}
function runObserver(source, observer, newValue, oldValue) {
try {
observer.callback(newValue, oldValue, observer.unwatch);
} catch (error) {
reportError(source, error, 'watcher-error', { newValue, oldValue });
}
}
function flush() {
flushing = true;
let iterations = 0;
try {
while (pendingObservables.size > 0 || pendingComputeds.size > 0) {
if (++iterations > MAX_FLUSH_ITERATIONS) {
const culprits = [...pendingObservables.keys(), ...pendingComputeds];
pendingObservables.clear();
pendingComputeds.clear();
reportError(
culprits[0],
new StateError(
`Watchers kept changing state after ${MAX_FLUSH_ITERATIONS} rounds; ` +
'a watcher probably writes a new value to a state it (indirectly) watches.',
{ type: 'update-depth' }
),
'update-depth'
);
return;
}
const observables = [...pendingObservables];
pendingObservables.clear();
for (const [source, oldValue] of observables) {
const newValue = source._value;
// Changed and changed back within one batch
if (!source._changed(oldValue, newValue)) continue;
for (const observer of [...source._observers]) {
Eif (source._observers.has(observer)) {
runObserver(source, observer, newValue, oldValue);
}
}
}
const computeds = [...pendingComputeds];
pendingComputeds.clear();
for (const source of computeds) {
Iif (source._observers.size === 0) continue;
try {
source._refresh();
} catch (error) {
reportError(source, error, 'computed-error');
continue;
}
const newValue = source._value;
const oldValue = source._lastNotified;
if (Object.is(newValue, oldValue)) continue;
source._lastNotified = newValue;
for (const observer of [...source._observers]) {
Eif (source._observers.has(observer)) {
runObserver(source, observer, newValue, oldValue);
}
}
}
}
} finally {
flushing = false;
}
}
function scheduleFlush() {
if (batchDepth === 0 && !flushing) {
flush();
}
}
/**
* Run `fn` with watcher notifications deferred until it returns; every
* watcher then runs once, with the final value. Nested batches flush when the
* outermost one ends. `fn` must be synchronous.
*
* @template T
* @param {() => T} fn
* @returns {T}
*/
export function batch(fn) {
batchDepth++;
try {
return fn();
} finally {
batchDepth--;
scheduleFlush();
}
}
/**
* Observable wrapper for tracking state changes
*/
export class Observable {
constructor(value, options = {}) {
this._value = value;
this._version = 0;
/** @type {Set<{callback: Function, unwatch: Function}>} */
this._observers = new Set();
/** Live computeds depending on this value */
this._subscribers = new Set();
this._options = {
deep: options.deep !== false,
immediate: options.immediate !== false,
...options
};
}
get value() {
activeComputed?._track(this);
return this._value;
}
set value(newValue) {
this._write(newValue);
}
/** Read without registering a dependency. */
peek() {
return this._value;
}
/**
* Whether a write from `oldValue` to `newValue` is a change. Identical
* primitives never are; with `deep` (the default) re-assigning the same
* object is, since it may have been mutated in place.
* @private
*/
_changed(oldValue, newValue) {
if (!Object.is(oldValue, newValue)) return true;
return this._options.deep && newValue !== null && typeof newValue === 'object';
}
/** @private */
_write(newValue) {
const oldValue = this._value;
if (!this._changed(oldValue, newValue)) {
return;
}
this._value = newValue;
this._version++;
globalVersion++;
for (const subscriber of [...this._subscribers]) {
subscriber._markDirty();
}
if (this._observers.size > 0 && !pendingObservables.has(this)) {
pendingObservables.set(this, oldValue);
}
scheduleFlush();
}
/** @private */
_addSubscriber(computed) {
this._subscribers.add(computed);
}
/** @private */
_removeSubscriber(computed) {
this._subscribers.delete(computed);
}
/** @private */
_addObserver(observer) {
this._observers.add(observer);
}
/** @private */
_removeObserver(observer) {
this._observers.delete(observer);
}
watch(callback, options = {}) {
if (typeof callback !== 'function') {
throw new StateError('Watch callback must be a function');
}
const observer = { callback, unwatch: null };
observer.unwatch = () => this._removeObserver(observer);
this._addObserver(observer);
// Call immediately if requested
if (options.immediate !== false) {
runObserver(this, observer, this._value, undefined);
}
// Return unwatch function
return observer.unwatch;
}
/**
* Remove a watcher, by the callback passed to watch()
* @param {Function} callback
*/
unwatch(callback) {
for (const observer of [...this._observers]) {
if (observer.callback === callback || observer.unwatch === callback) {
this._removeObserver(observer);
}
}
}
/** Remove every watcher. */
unwatchAll() {
for (const observer of [...this._observers]) {
this._removeObserver(observer);
}
}
}
/**
* Computed property implementation
*/
class Computed extends Observable {
constructor(getter, options = {}) {
Iif (typeof getter !== 'function') {
throw new StateError('Computed getter must be a function');
}
super(undefined, options);
this._getter = getter;
/** Dependencies read by the last computation: source -> its version then */
this._deps = new Map();
this._dirty = true;
this._computing = false;
this._globalVersionSeen = -1;
this._lastNotified = undefined;
}
get value() {
this._refresh();
activeComputed?._track(this);
return this._value;
}
set value(_newValue) {
throw new StateError('Cannot set value on computed property');
}
peek() {
this._refresh();
return this._value;
}
/** Watched, or a dependency of a live computed. @private */
get _live() {
return this._observers.size > 0 || this._subscribers.size > 0;
}
/** @private */
_track(source) {
Eif (!this._deps.has(source)) {
this._deps.set(source, source._version);
}
}
/** Bring the cached value up to date. @private */
_refresh() {
if (this._computing) {
throw new StateError('Circular dependency between computed properties', {
type: 'computed-cycle',
context: { getter: this._getter.name || 'anonymous' }
});
}
if (!this._dirty) {
// A live computed is marked dirty by its dependencies
if (this._live || this._globalVersionSeen === globalVersion) return;
Iif (!this._dependenciesChanged()) {
this._globalVersionSeen = globalVersion;
return;
}
}
this._recompute();
}
/** @private */
_dependenciesChanged() {
for (const [source, version] of this._deps) {
Iif (source instanceof Computed) {
source._refresh();
}
Eif (source._version !== version) return true;
}
return false;
}
/** @private */
_recompute() {
const previousDeps = this._deps;
const previousActive = activeComputed;
this._deps = new Map();
this._computing = true;
activeComputed = this;
let newValue;
try {
newValue = this._getter();
} catch (error) {
// Stay dirty so the next read retries
this._deps = previousDeps;
this._dirty = true;
throw error;
} finally {
this._computing = false;
activeComputed = previousActive;
}
if (this._live) {
for (const source of previousDeps.keys()) {
if (!this._deps.has(source)) source._removeSubscriber(this);
}
for (const source of this._deps.keys()) {
if (!previousDeps.has(source)) source._addSubscriber(this);
}
}
this._dirty = false;
this._globalVersionSeen = globalVersion;
if (!Object.is(newValue, this._value)) {
this._value = newValue;
this._version++;
}
}
/** A dependency changed. @private */
_markDirty() {
Iif (this._dirty) return;
this._dirty = true;
Eif (this._observers.size > 0) {
pendingComputeds.add(this);
}
for (const subscriber of [...this._subscribers]) {
subscriber._markDirty();
}
}
/** Subscribe to dependencies. @private */
_goLive() {
this._refresh();
for (const source of this._deps.keys()) {
source._addSubscriber(this);
}
}
/** Unsubscribe from dependencies. @private */
_goLazy() {
for (const source of this._deps.keys()) {
source._removeSubscriber(this);
}
}
/** @private */
_addSubscriber(computed) {
const wasLive = this._live;
this._subscribers.add(computed);
if (!wasLive) this._goLive();
}
/** @private */
_removeSubscriber(computed) {
this._subscribers.delete(computed);
if (!this._live) this._goLazy();
}
/** @private */
_addObserver(observer) {
const hadObservers = this._observers.size > 0;
const wasLive = this._live;
this._observers.add(observer);
try {
if (wasLive) {
this._refresh();
} else {
this._goLive();
}
} catch (error) {
this._observers.delete(observer);
throw error;
}
if (!hadObservers) {
// Baseline for the next notification's oldValue
this._lastNotified = this._value;
}
}
/** @private */
_removeObserver(observer) {
Iif (!this._observers.delete(observer)) return;
Eif (!this._live) this._goLazy();
}
}
/** Placeholder observables for keys read before they exist or after delete(). */
const ABSENT = Symbol('absent');
function isPath(key) {
return typeof key === 'string' && key.includes('.');
}
function readPath(value, segments) {
let current = value;
for (const segment of segments) {
if (current === null || current === undefined) return undefined;
current = current[segment];
}
return current;
}
/** A copy of `target` with `segments` set to `value`, creating objects as needed. */
function writePath(target, segments, value) {
const [head, ...rest] = segments;
const base = target !== null && typeof target === 'object'
? (Array.isArray(target) ? [...target] : { ...target })
: {};
const next = rest.length === 0 ? value : writePath(base[head], rest, value);
Object.defineProperty(base, head, { value: next, enumerable: true, writable: true, configurable: true });
return base;
}
/** A copy of `target` without the property at `segments`. */
function deletePath(target, segments) {
Iif (target === null || typeof target !== 'object') return target;
const [head, ...rest] = segments;
Iif (!Object.prototype.hasOwnProperty.call(target, head)) return target;
const base = Array.isArray(target) ? [...target] : { ...target };
if (rest.length === 0) {
delete base[head];
} else {
base[head] = deletePath(base[head], rest);
}
return base;
}
/**
* Reactive state container with advanced features
*
* Keys may be dot paths into object values: `set('user.name', 'Ada')` writes
* a copy of `user` with the new name (notifying watchers of `user` and of
* `user.name`), and `get`/`has`/`watch`/`delete` accept paths too.
*/
export class ReactiveState {
constructor(initialState = {}, options = {}) {
/** @type {Map<string, Observable>} */
this._state = new Map();
this._computed = new Map();
this._watchers = new Map();
this._expressionWatchers = new Set();
this._middleware = [];
this._history = [];
this._options = {
enableHistory: options.enableHistory !== false,
maxHistorySize: options.maxHistorySize || 50,
enableMiddleware: options.enableMiddleware !== false,
deep: options.deep !== false,
...options
};
// Initialize state
Object.entries(initialState).forEach(([key, value]) => {
this.set(key, value);
});
}
/** Observable for a key, created as an absent placeholder if needed. @private */
_observable(key) {
let observable = this._state.get(key);
if (!observable) {
observable = new Observable(ABSENT, this._options);
this._state.set(key, observable);
}
return observable;
}
/** Whether a key is stored under its full name. @private */
_hasOwnKey(key) {
const observable = this._state.get(key);
return Boolean(observable) && observable._value !== ABSENT;
}
/** [rootKey, pathSegments] for a dot path, or null for a plain key. @private */
_splitPath(key) {
if (!isPath(key)) return null;
const [root, ...segments] = key.split('.');
return [root, segments];
}
/**
* Get reactive state value
*/
get(key) {
const path = this._splitPath(key);
if (path) {
return readPath(this.get(path[0]), path[1]);
}
// Reading a missing key inside a computed still records the
// dependency, so the computed updates once the key is set.
const observable = activeComputed ? this._observable(key) : this._state.get(key);
if (!observable) return undefined;
const value = observable.value;
return value === ABSENT ? undefined : value;
}
/**
* Set reactive state value
*/
set(key, value, options = {}) {
const config = { ...this._options, ...options };
const oldValue = this.get(key);
// Run middleware
Eif (config.enableMiddleware) {
const middlewareResult = this._runMiddleware('set', { key, value, oldValue });
Iif (middlewareResult.cancelled) {
return false;
}
value = middlewareResult.value !== undefined ? middlewareResult.value : value;
}
const path = this._splitPath(key);
if (path) {
const [root, segments] = path;
if (config.enableHistory) {
this._addToHistory('set', key, oldValue, value);
}
this._writeKey(root, writePath(this.get(root), segments, value));
return true;
}
// Record history
if (config.enableHistory && this._hasOwnKey(key)) {
this._addToHistory('set', key, oldValue, value);
}
this._writeKey(key, value);
return true;
}
/** @private */
_writeKey(key, value) {
this._observable(key)._write(value);
}
/**
* Check if state has a key
*/
has(key) {
const path = this._splitPath(key);
if (path) {
const parent = readPath(this.get(path[0]), path[1].slice(0, -1));
return parent !== null && typeof parent === 'object' &&
Object.prototype.hasOwnProperty.call(parent, path[1][path[1].length - 1]);
}
return this._hasOwnKey(key);
}
/**
* Delete state key. Its watchers are removed; computed properties that
* read it update.
*/
delete(key) {
const path = this._splitPath(key);
if (path) {
Iif (!this.has(key)) return false;
Eif (this._options.enableHistory) {
this._addToHistory('delete', key, this.get(key), undefined);
}
this._writeKey(path[0], deletePath(this.get(path[0]), path[1]));
return true;
}
Iif (!this._hasOwnKey(key)) {
return false;
}
const observable = this._state.get(key);
// Record history
Eif (this._options.enableHistory) {
this._addToHistory('delete', key, observable._value, undefined);
}
observable.unwatchAll();
this._releaseKeyWatchers(key);
observable._write(ABSENT);
return true;
}
/** @private */
_releaseKeyWatchers(key) {
const unwatchers = this._watchers.get(key);
Iif (unwatchers) {
for (const unwatch of unwatchers) unwatch();
this._watchers.delete(key);
}
}
/**
* Clear all state
*/
clear() {
// Record history
Eif (this._options.enableHistory) {
this._addToHistory('clear', null, this.toObject(), {});
}
batch(() => {
for (const [key, observable] of this._state) {
observable.unwatchAll();
this._releaseKeyWatchers(key);
observable._write(ABSENT);
}
});
this._computed.clear();
this._watchers.clear();
}
/**
* Create computed property
*/
computed(key, getter, options = {}) {
Iif (typeof getter !== 'function') {
throw new StateError(`Computed property '${key}' getter must be a function`);
}
const computed = new Computed(getter, { ...this._options, ...options });
this._computed.set(key, computed);
return computed;
}
/**
* Get computed property value
*/
getComputed(key) {
const computed = this._computed.get(key);
return computed ? computed.value : undefined;
}
/**
* Watch state changes: a key, a dot path into a key, or a getter
* expression (re-evaluated whenever what it reads changes).
*/
watch(key, callback, options = {}) {
if (typeof key === 'function') {
// Watch computed expression
return this._watchComputed(key, callback, options);
}
const path = this._splitPath(key);
if (path) {
Iif (!this._hasOwnKey(path[0])) {
throw new StateError(`Cannot watch undefined state key: ${path[0]}`);
}
const computed = new Computed(() => this.get(key), { ...this._options, ...options });
return this._track(key, computed.watch(callback, options));
}
Iif (!this._hasOwnKey(key)) {
throw new StateError(`Cannot watch undefined state key: ${key}`);
}
return this._track(key, this._state.get(key).watch(callback, options));
}
/** Remember an unwatch function for cleanup. @private */
_track(key, unwatch) {
Eif (!this._watchers.has(key)) {
this._watchers.set(key, new Set());
}
const unwatchers = this._watchers.get(key);
const release = () => {
unwatch();
unwatchers.delete(release);
};
unwatchers.add(release);
return release;
}
/**
* Watch computed expression
*/
_watchComputed(expression, callback, options = {}) {
const computed = new Computed(expression, { ...this._options, ...options });
const unwatch = computed.watch(callback, options);
const release = () => {
unwatch();
this._expressionWatchers.delete(release);
};
this._expressionWatchers.add(release);
return release;
}
/**
* Batch state updates: watchers run once, after every update, with the
* final values.
*/
batch(updates) {
if (typeof updates === 'function') {
// Batch function updates
const oldEnableHistory = this._options.enableHistory;
this._options.enableHistory = false;
try {
const result = batch(() => updates(this));
// Record batch in history
Eif (oldEnableHistory) {
this._addToHistory('batch', null, null, this.toObject());
}
return result;
} finally {
this._options.enableHistory = oldEnableHistory;
}
} else Eif (typeof updates === 'object') {
// Batch object updates
return this.batch(() => {
Object.entries(updates).forEach(([key, value]) => {
this.set(key, value);
});
});
}
}
/**
* Subscribe to multiple state changes
*/
subscribe(keys, callback, options = {}) {
Iif (!Array.isArray(keys)) {
keys = [keys];
}
const unwatchers = keys.map(key => {
return this.watch(key, (newValue, oldValue) => {
callback({
key,
newValue,
oldValue,
state: this.toObject()
});
}, options);
});
// Return unsubscribe function
return () => {
unwatchers.forEach(unwatch => unwatch());
};
}
/**
* Add middleware for state changes
*/
use(middleware) {
if (typeof middleware !== 'function') {
throw new StateError('Middleware must be a function');
}
this._middleware.push(middleware);
}
/**
* Run middleware chain
*/
_runMiddleware(action, context) {
let result = { ...context, cancelled: false };
for (const middleware of this._middleware) {
try {
const middlewareResult = middleware(action, result);
if (middlewareResult) {
result = { ...result, ...middlewareResult };
if (result.cancelled) {
break;
}
}
} catch (error) {
reportError(this, error, 'middleware-error', { action });
}
}
return result;
}
/**
* Add action to history
*/
_addToHistory(action, key, oldValue, newValue) {
if (!this._options.enableHistory) return;
this._history.unshift({
action,
key,
oldValue,
newValue,
timestamp: Date.now()
});
// Limit history size
Iif (this._history.length > this._options.maxHistorySize) {
this._history = this._history.slice(0, this._options.maxHistorySize);
}
}
/**
* Get state history
*/
getHistory(limit = 10) {
return this._history.slice(0, limit);
}
/**
* Undo last action
*/
undo() {
const lastAction = this._history.shift();
Iif (!lastAction) return false;
const { action, key, oldValue } = lastAction;
// Temporarily disable history
const oldEnableHistory = this._options.enableHistory;
this._options.enableHistory = false;
try {
switch (action) {
case 'set':
Iif (oldValue === undefined) {
this.delete(key);
} else {
this.set(key, oldValue);
}
break;
case 'delete':
this.set(key, oldValue);
break;
case 'clear':
this.clear();
Object.entries(oldValue || {}).forEach(([k, v]) => {
this.set(k, v);
});
break;
}
return true;
} finally {
this._options.enableHistory = oldEnableHistory;
}
}
/**
* Convert state to plain object
*/
toObject() {
// Object.fromEntries defines own properties, so a "__proto__" key
// stays a key instead of replacing the result's prototype.
return Object.fromEntries(
[...this._state]
.filter(([, observable]) => observable._value !== ABSENT)
.map(([key, observable]) => [key, observable._value])
);
}
/**
* Convert computed properties to object
*/
getComputedValues() {
return Object.fromEntries(
[...this._computed].map(([key, computed]) => [key, computed.value])
);
}
/**
* Get state statistics
*/
getStats() {
let stateKeys = 0;
for (const observable of this._state.values()) {
if (observable._value !== ABSENT) stateKeys++;
}
return {
stateKeys,
computedKeys: this._computed.size,
watcherKeys: this._watchers.size,
historyLength: this._history.length,
middlewareCount: this._middleware.length
};
}
/**
* Cleanup and destroy
*/
destroy() {
// Clear all watchers
for (const key of [...this._watchers.keys()]) {
this._releaseKeyWatchers(key);
}
for (const release of [...this._expressionWatchers]) {
release();
}
for (const observable of this._state.values()) {
observable.unwatchAll();
}
for (const computed of this._computed.values()) {
computed.unwatchAll();
}
// Clear collections
this._state.clear();
this._computed.clear();
this._watchers.clear();
this._middleware.length = 0;
this._history.length = 0;
}
}
/**
* Create reactive state store
*/
export function createReactiveState(initialState, options = {}) {
return new ReactiveState(initialState, options);
}
/**
* Create observable value
*/
export function observable(value, options = {}) {
return new Observable(value, options);
}
/**
* Create computed property
*/
export function computed(getter, options = {}) {
return new Computed(getter, options);
}
/**
* Utility functions for common state patterns
*/
export const stateUtils = {
/**
* Create a toggle state
*/
toggle(initialValue = false) {
const obs = observable(initialValue);
obs.toggle = () => {
obs.value = !obs.value;
};
return obs;
},
/**
* Create a counter state
*/
counter(initialValue = 0) {
const obs = observable(initialValue);
obs.increment = (by = 1) => {
obs.value += by;
};
obs.decrement = (by = 1) => {
obs.value -= by;
};
obs.reset = () => {
obs.value = initialValue;
};
return obs;
},
/**
* Create an array state with utilities
*/
array(initialArray = []) {
const obs = observable([...initialArray]);
obs.push = (...items) => {
obs.value = [...obs.value, ...items];
};
obs.pop = () => {
const newArray = [...obs.value];
const result = newArray.pop();
obs.value = newArray;
return result;
};
obs.filter = (predicate) => {
obs.value = obs.value.filter(predicate);
};
obs.clear = () => {
obs.value = [];
};
return obs;
},
/**
* Create object state with deep reactivity
*/
object(initialObject = {}) {
const state = createReactiveState(initialObject, { deep: true });
return state;
}
};
export default ReactiveState;
|