@maverick-js/signals
Version:
A lightweight (~1kB) library for creating reactive observables via functions.
365 lines (360 loc) • 10.3 kB
JavaScript
import { SCOPE } from './symbols.js';
let scheduledEffects = false, runningEffects = false, currentScope = null, currentObserver = null, currentObservers = null, currentObserversIndex = 0, effects = [], defaultContext = {};
const NOOP = () => {
}, STATE_CLEAN = 0, STATE_CHECK = 1, STATE_DIRTY = 2, STATE_DISPOSED = 3;
function flushEffects() {
scheduledEffects = true;
queueMicrotask(runEffects);
}
function runEffects() {
if (!effects.length) {
scheduledEffects = false;
return;
}
runningEffects = true;
for (let i = 0; i < effects.length; i++) {
if (effects[i]._state !== STATE_CLEAN)
runTop(effects[i]);
}
effects = [];
scheduledEffects = false;
runningEffects = false;
}
function runTop(node) {
let ancestors = [node];
while (node = node[SCOPE]) {
if (node._effect && node._state !== STATE_CLEAN)
ancestors.push(node);
}
for (let i = ancestors.length - 1; i >= 0; i--) {
updateCheck(ancestors[i]);
}
}
function root(init) {
const scope = createScope();
return compute(scope, !init.length ? init : init.bind(null, dispose.bind(scope)), null);
}
function peek(fn) {
return compute(currentScope, fn, null);
}
function untrack(fn) {
return compute(null, fn, null);
}
function tick() {
if (!runningEffects)
runEffects();
}
function getScope() {
return currentScope;
}
function scoped(run, scope) {
try {
return compute(scope, run, null);
} catch (error) {
handleError(scope, error);
return;
}
}
function getContext(key, scope = currentScope) {
return scope?._context[key];
}
function setContext(key, value, scope = currentScope) {
if (scope)
scope._context = { ...scope._context, [key]: value };
}
function onError(handler) {
if (!currentScope)
return;
currentScope._handlers = currentScope._handlers ? [handler, ...currentScope._handlers] : [handler];
}
function onDispose(disposable) {
if (!disposable || !currentScope)
return disposable || NOOP;
const node = currentScope;
if (!node._disposal) {
node._disposal = disposable;
} else if (Array.isArray(node._disposal)) {
node._disposal.push(disposable);
} else {
node._disposal = [node._disposal, disposable];
}
return function removeDispose() {
if (node._state === STATE_DISPOSED)
return;
disposable.call(null);
if (isFunction(node._disposal)) {
node._disposal = null;
} else if (Array.isArray(node._disposal)) {
node._disposal.splice(node._disposal.indexOf(disposable), 1);
}
};
}
function dispose(self = true) {
if (this._state === STATE_DISPOSED)
return;
if (this._children) {
if (Array.isArray(this._children)) {
for (let i = this._children.length - 1; i >= 0; i--) {
dispose.call(this._children[i]);
}
} else {
dispose.call(this._children);
}
}
if (self) {
const parent = this[SCOPE];
if (parent) {
if (Array.isArray(parent._children)) {
parent._children.splice(parent._children.indexOf(this), 1);
} else {
parent._children = null;
}
}
disposeNode(this);
}
}
function disposeNode(node) {
node._state = STATE_DISPOSED;
if (node._disposal)
emptyDisposal(node);
if (node._sources)
removeSourceObservers(node, 0);
node[SCOPE] = null;
node._sources = null;
node._observers = null;
node._children = null;
node._context = defaultContext;
node._handlers = null;
}
function emptyDisposal(scope) {
try {
if (Array.isArray(scope._disposal)) {
for (let i = scope._disposal.length - 1; i >= 0; i--) {
const callable = scope._disposal[i];
callable.call(callable);
}
} else {
scope._disposal.call(scope._disposal);
}
scope._disposal = null;
} catch (error) {
handleError(scope, error);
}
}
function compute(scope, compute2, observer) {
const prevScope = currentScope, prevObserver = currentObserver;
currentScope = scope;
currentObserver = observer;
try {
return compute2.call(scope);
} finally {
currentScope = prevScope;
currentObserver = prevObserver;
}
}
function handleError(scope, error) {
if (!scope || !scope._handlers)
throw error;
let i = 0, len = scope._handlers.length, currentError = error;
for (i = 0; i < len; i++) {
try {
scope._handlers[i](currentError);
break;
} catch (error2) {
currentError = error2;
}
}
if (i === len)
throw currentError;
}
function read() {
if (this._state === STATE_DISPOSED)
return this._value;
if (currentObserver && !this._effect) {
if (!currentObservers && currentObserver._sources && currentObserver._sources[currentObserversIndex] == this) {
currentObserversIndex++;
} else if (!currentObservers)
currentObservers = [this];
else
currentObservers.push(this);
}
if (this._compute)
updateCheck(this);
return this._value;
}
function write(newValue) {
const value = isFunction(newValue) ? newValue(this._value) : newValue;
if (this._changed(this._value, value)) {
this._value = value;
if (this._observers) {
for (let i = 0; i < this._observers.length; i++) {
notify(this._observers[i], STATE_DIRTY);
}
}
}
return this._value;
}
const ScopeNode = function Scope() {
this[SCOPE] = null;
this._children = null;
if (currentScope)
currentScope.append(this);
};
const ScopeProto = ScopeNode.prototype;
ScopeProto._context = defaultContext;
ScopeProto._handlers = null;
ScopeProto._compute = null;
ScopeProto._disposal = null;
ScopeProto.append = function(child) {
child[SCOPE] = this;
if (!this._children) {
this._children = child;
} else if (Array.isArray(this._children)) {
this._children.push(child);
} else {
this._children = [this._children, child];
}
child._context = child._context === defaultContext ? this._context : { ...this._context, ...child._context };
if (this._handlers) {
child._handlers = !child._handlers ? this._handlers : [...child._handlers, ...this._handlers];
}
};
ScopeProto.dispose = function() {
dispose.call(this);
};
function createScope() {
return new ScopeNode();
}
const ComputeNode = function Computation(initialValue, compute2, options) {
ScopeNode.call(this);
this._state = compute2 ? STATE_DIRTY : STATE_CLEAN;
this._init = false;
this._effect = false;
this._sources = null;
this._observers = null;
this._value = initialValue;
this.id = options?.id ?? (this._compute ? "computed" : "signal");
if (compute2)
this._compute = compute2;
if (options && options.dirty)
this._changed = options.dirty;
};
const ComputeProto = ComputeNode.prototype;
Object.setPrototypeOf(ComputeProto, ScopeProto);
ComputeProto._changed = isNotEqual;
ComputeProto.call = read;
function createComputation(initialValue, compute2, options) {
return new ComputeNode(initialValue, compute2, options);
}
function isNotEqual(a, b) {
return a !== b;
}
function isFunction(value) {
return typeof value === "function";
}
function updateCheck(node) {
if (node._state === STATE_CHECK) {
for (let i = 0; i < node._sources.length; i++) {
updateCheck(node._sources[i]);
if (node._state === STATE_DIRTY) {
break;
}
}
}
if (node._state === STATE_DIRTY)
update(node);
else
node._state = STATE_CLEAN;
}
function cleanup(node) {
if (node._children)
dispose.call(node, false);
if (node._disposal)
emptyDisposal(node);
node._handlers = node[SCOPE] ? node[SCOPE]._handlers : null;
}
function update(node) {
let prevObservers = currentObservers, prevObserversIndex = currentObserversIndex;
currentObservers = null;
currentObserversIndex = 0;
try {
cleanup(node);
const result = compute(node, node._compute, node);
updateObservers(node);
if (!node._effect && node._init) {
write.call(node, result);
} else {
node._value = result;
node._init = true;
}
} catch (error) {
if (!node._init && typeof node._value === "undefined") {
console.error(
`computed \`${node.id}\` threw error during first run, this can be fatal.
Solutions:
1. Set the \`initial\` option to silence this error`,
"\n2. Or, use an `effect` if the return value is not being used",
"\n\n",
error
);
}
updateObservers(node);
handleError(node, error);
} finally {
currentObservers = prevObservers;
currentObserversIndex = prevObserversIndex;
node._state = STATE_CLEAN;
}
}
function updateObservers(node) {
if (currentObservers) {
if (node._sources)
removeSourceObservers(node, currentObserversIndex);
if (node._sources && currentObserversIndex > 0) {
node._sources.length = currentObserversIndex + currentObservers.length;
for (let i = 0; i < currentObservers.length; i++) {
node._sources[currentObserversIndex + i] = currentObservers[i];
}
} else {
node._sources = currentObservers;
}
let source;
for (let i = currentObserversIndex; i < node._sources.length; i++) {
source = node._sources[i];
if (!source._observers)
source._observers = [node];
else
source._observers.push(node);
}
} else if (node._sources && currentObserversIndex < node._sources.length) {
removeSourceObservers(node, currentObserversIndex);
node._sources.length = currentObserversIndex;
}
}
function notify(node, state) {
if (node._state >= state)
return;
if (node._effect && node._state === STATE_CLEAN) {
effects.push(node);
if (!scheduledEffects)
flushEffects();
}
node._state = state;
if (node._observers) {
for (let i = 0; i < node._observers.length; i++) {
notify(node._observers[i], STATE_CHECK);
}
}
}
function removeSourceObservers(node, index) {
let source, swap;
for (let i = index; i < node._sources.length; i++) {
source = node._sources[i];
if (source._observers) {
swap = source._observers.indexOf(node);
source._observers[swap] = source._observers[source._observers.length - 1];
source._observers.pop();
}
}
}
export { compute, createComputation, createScope, dispose, getContext, getScope, isFunction, isNotEqual, onDispose, onError, peek, read, root, scoped, setContext, tick, untrack, update, write };