UNPKG

rvx

Version:

A signal based rendering library

80 lines 2.16 kB
let WINDOW = []; const _capture = (context) => { return { c: context, v: context.current, }; }; export class Context { constructor(defaultValue) { this.default = defaultValue; } #frame; #window; default; get current() { if (this.#window === WINDOW) { return this.#frame ?? this.default; } return this.default; } provide(value, fn, ...args) { const window = WINDOW; const parentValue = this.#frame; const parentWindow = this.#window; try { this.#window = window; window.push(this); this.#frame = value; return fn(...args); } finally { this.#frame = parentValue; window.pop(); this.#window = parentWindow; } } with(value) { return { c: this, v: value }; } static isolate(states, fn, ...args) { const parent = WINDOW; try { WINDOW = []; return Context.provide(states, fn, ...args); } finally { WINDOW = parent; } } static provide(states, fn, ...args) { const active = []; const window = WINDOW; for (let i = 0; i < states.length; i++) { const { c: context, v: value } = states[i]; active.push({ c: context, p: context.#window, v: context.#frame }); context.#window = window; context.#frame = value; window.push(context); } try { return fn(...args); } finally { for (let i = active.length - 1; i >= 0; i--) { const { c: context, p: parent, v: parentValue } = active[i]; context.#window = parent; context.#frame = parentValue; window.pop(); } } } static capture() { return WINDOW.map(_capture); } static bind(fn) { const states = Context.capture(); return ((...args) => Context.isolate(states, fn, ...args)); } } //# sourceMappingURL=context.js.map