All files / lib/core/reactive scopeProxy.js

96.74% Statements 327/338
84.9% Branches 45/53
95.65% Functions 22/23
96.74% Lines 327/338

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 339505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 524x 524x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 524x 1x 1x 524x 474x 474x 49x 524x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 3520x 3520x 3520x 3520x 3520x 3520x 3520x 20753x 3520x 3520x 3520x 3520x 3520x 3520x 1596x 3520x 3520x 3520x 3520x 3520x 3520x 3520x     3520x 3520x 3520x 3520x 3520x 10x 3520x 3520x 3520x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 610x 610x 610x 610x 610x 610x 610x 6733x 442x 442x 6733x 610x 610x 610x 610x 610x 610x 2164x 610x 610x 610x 610x 610x 610x 610x 1x 1x 610x 610x 610x 610x 610x 2x 2x 2x 2x 610x 610x 610x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 610x 610x 610x 610x 610x 610x 610x 7396x 610x 610x 610x 610x 610x 610x 21x 610x 610x 610x 610x 610x 2x 610x 610x 610x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 505x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 9493x 36190x 9434x 9434x 36190x 59x 9493x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 3774x 3774x 3774x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 4736x 4736x 474x 474x 4736x 3787x 4736x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 1x 1x 1x 1x 1x                   1084x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 2x 2x 16x 16x 16x 16x 2x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 1084x 1931x 1931x 1901x 1084x 1084x 1084x 1084x 1084x  
/**
 * @file scopeProxy.js
 * @description The evaluation scope handed to template expressions, computed
 * values and action bodies.
 *
 * ## What was wrong with building it as an object
 *
 * The scope used to be assembled with a spread:
 *
 * ```js
 * const scope = { state: this.state, ...this.bridges, ...this.state, ...methods, … };
 * ```
 *
 * `...this.state` reads every key on the reactive proxy, eagerly, every time a
 * scope is built — which is once per render, per action call and per computed
 * evaluation. Three separate defects followed from that one line.
 *
 * **Bare identifiers were not reactive.** The documented computed form
 * `<computed value="count * 2" />` reads `count` out of the *snapshot* the
 * spread produced, not out of the proxy, so no dependency was registered for
 * the expression itself. `state.count * 2` worked; the form in the README,
 * quickstart and state-management guide did not, and failed silently — the
 * first render was correct and the value then never changed again.
 *
 * **Computed values reported false cycles.** Spreading the state proxy reads
 * the computed key currently being evaluated. That re-entered the computed's
 * own watcher mid-collection, tripping the re-entrancy guard: every app using
 * computed properties logged `AVX_R04 Circular dependency detected` on every
 * re-render, for a cycle that did not exist. Worse, the re-entrant
 * `watcher.evaluate()` reset the watcher's dependency set part-way through
 * collection, which is what actually lost the `count` dependency above. The
 * bogus warning and the missing dependency were the same event.
 *
 * **Reactivity was component-granular.** Because the spread touched every key,
 * the render watcher depended on all of them. Changing a key no expression
 * mentioned still re-rendered the component, so the per-key precision the Proxy
 * layer computes was discarded one level above it.
 *
 * ## What this does instead
 *
 * Nothing is read until an expression actually names it. The scope is a Proxy
 * over ordered layers; a `get` resolves through them and, for a state or
 * computed key, reads the live reactive proxy — inside whichever watcher is
 * currently evaluating. So `count` in `count * 2` registers a dependency on
 * `count` and on nothing else.
 *
 * ## Derivation instead of spreading
 *
 * Several call sites layer extra names onto a scope — a `<@for>` loop variable,
 * an `event`, an action's `args`. Written as `{ ...scope, index }` that would
 * reintroduce the eager read this module exists to remove, so scopes derive
 * instead: {@link deriveScope} pushes another layer without materialising
 * anything. It falls back to a spread for plain objects, so external code that
 * passes an ordinary object still works.
 * @module lib/core/reactive/scopeProxy
 */
 
/**
 * Marks a value as one of this module's scope proxies.
 * @type {symbol}
 */
export const IS_REACTIVE_SCOPE = Symbol.for('avenx.reactiveScope');
 
/**
 * Derives a child scope from a scope proxy.
 * @type {symbol}
 */
export const SCOPE_DERIVE = Symbol.for('avenx.scopeDerive');
 
/**
 * Reports whether a value is a scope proxy created here.
 * @param {any} value - The value to test.
 * @returns {boolean} True for a reactive scope proxy.
 */
export function isReactiveScope(value) {
  return !!(value && typeof value === 'object' && value[IS_REACTIVE_SCOPE]);
}
 
/**
 * Layers extra bindings on top of an existing scope.
 *
 * Prefer this over `{ ...scope, extra }` anywhere a scope gains names. A spread
 * of a scope proxy reads every key it can enumerate, which is exactly the eager
 * read this module removes.
 * @param {object} scope - The scope to extend. May be a scope proxy or a plain object.
 * @param {object} extras - The bindings to layer on top.
 * @returns {object} A scope with the extras applied.
 */
export function deriveScope(scope, extras) {
  if (!extras) {
    return scope;
  }
  if (isReactiveScope(scope)) {
    return scope[SCOPE_DERIVE](extras);
  }
  return { ...scope, ...extras };
}
 
/**
 * @typedef {object} ScopeLayer
 * @property {function(string): boolean} has - Whether the layer binds a name.
 * @property {function(string): any} get - The value bound to a name.
 * @property {function(string, any): boolean} [set] - Assigns to a bound name.
 * @property {function(): string[]} keys - The names the layer binds.
 */
 
/**
 * Builds a layer over a plain object.
 * @param {object} source - The object to expose.
 * @returns {ScopeLayer} The layer.
 */
export function objectLayer(source) {
  const target = source || {};
  return {
    /**
     * @param {string} key - The name to test.
     * @returns {boolean} Whether the object binds it.
     */
    has(key) {
      return Object.prototype.hasOwnProperty.call(target, key);
    },
    /**
     * @param {string} key - The name to read.
     * @returns {any} The bound value.
     */
    get(key) {
      return target[key];
    },
    /**
     * @param {string} key - The name to write.
     * @param {any} value - The value to assign.
     * @returns {boolean} Always true.
     */
    set(key, value) {
      target[key] = value;
      return true;
    },
    /**
     * @returns {string[]} The names bound.
     */
    keys() {
      return Object.keys(target);
    },
  };
}
 
/**
 * Builds a layer over the component's reactive state.
 *
 * The names are known without reading anything: they come from the raw target
 * and the compiler's computed list. A value is read from the proxy only when an
 * expression asks for it, which is what makes the read land inside the watcher
 * that is currently evaluating.
 * @param {object} state - The reactive state proxy.
 * @param {function(): string[]} listKeys - Returns the bound names.
 * @returns {ScopeLayer} The layer.
 */
export function stateLayer(state, listKeys) {
  let cached = null;
  return {
    /**
     * @param {string} key - The name to test.
     * @returns {boolean} Whether state binds it.
     */
    has(key) {
      if (!cached) {
        cached = new Set(listKeys());
      }
      return cached.has(key);
    },
    /**
     * @param {string} key - The name to read.
     * @returns {any} The value, read through the reactive proxy.
     */
    get(key) {
      return state[key];
    },
    /**
     * @param {string} key - The name to write.
     * @param {any} value - The value to assign.
     * @returns {boolean} Always true.
     */
    set(key, value) {
      state[key] = value;
      return true;
    },
    /**
     * @returns {string[]} The names bound.
     */
    keys() {
      if (!cached) {
        cached = new Set(listKeys());
      }
      return [...cached];
    },
  };
}
 
/**
 * Builds a layer of lazily evaluated bindings.
 *
 * Used for resources, whose value is produced by calling `read()` and must not
 * be produced merely because a scope was built.
 * @param {Object<string, function(): any>} getters - Name to getter.
 * @returns {ScopeLayer} The layer.
 */
export function getterLayer(getters) {
  const source = getters || {};
  return {
    /**
     * @param {string} key - The name to test.
     * @returns {boolean} Whether a getter is bound.
     */
    has(key) {
      return Object.prototype.hasOwnProperty.call(source, key);
    },
    /**
     * @param {string} key - The name to read.
     * @returns {any} The getter's result.
     */
    get(key) {
      return source[key]();
    },
    /**
     * @returns {string[]} The names bound.
     */
    keys() {
      return Object.keys(source);
    },
  };
}
 
/**
 * Creates the evaluation scope.
 *
 * Layers are given in precedence order, highest first: the first layer that
 * binds a name wins. That mirrors the object-literal precedence the previous
 * implementation had, where later spreads overwrote earlier ones.
 * @param {ScopeLayer[]} layers - The layers, highest precedence first.
 * @returns {object} A scope proxy.
 */
export function createReactiveScope(layers) {
  const active = layers.filter(Boolean);
 
  /**
   * Finds the layer that binds a name.
   * @param {string} key - The name to resolve.
   * @returns {ScopeLayer|null} The binding layer, or null.
   */
  function resolve(key) {
    for (const layer of active) {
      if (layer.has(key)) {
        return layer;
      }
    }
    return null;
  }
 
  const handler = {
    /**
     * @param {object} target - Unused backing object.
     * @param {string|symbol} key - The name to test.
     * @returns {boolean} Whether the scope binds it.
     */
    has(target, key) {
      if (key === IS_REACTIVE_SCOPE || key === SCOPE_DERIVE) return true;
      if (typeof key === 'symbol') return false;
      return resolve(key) !== null;
    },
 
    /**
     * @param {object} target - Unused backing object.
     * @param {string|symbol} key - The name to read.
     * @returns {any} The bound value, or undefined.
     */
    get(target, key) {
      if (key === IS_REACTIVE_SCOPE) return true;
      if (key === SCOPE_DERIVE) {
        return (extras) => createReactiveScope([objectLayer(extras), ...active]);
      }
      if (typeof key === 'symbol') return undefined;
      const layer = resolve(key);
      return layer ? layer.get(key) : undefined;
    },
 
    /**
     * @param {object} target - Unused backing object.
     * @param {string|symbol} key - The name to write.
     * @param {any} value - The value to assign.
     * @returns {boolean} Whether the write was accepted.
     */
    set(target, key, value) {
      if (typeof key === 'symbol') return false;
      const layer = resolve(key);
      if (layer && typeof layer.set === 'function') {
        return layer.set(key, value);
      }
      // An undeclared name assigned from an action lands on the highest layer
      // that can hold it, matching the previous behaviour where
      // `scope[key] = value` created a key on the scope object.
      for (const candidate of active) {
        if (typeof candidate.set === 'function') {
          return candidate.set(key, value);
        }
      }
      return false;
    },
 
    /**
     * Enumerating a scope materialises it, which is what spreading one does.
     * Present so that external code holding a scope still behaves; internal
     * call sites use {@link deriveScope} instead.
     * @returns {string[]} Every bound name.
     */
    ownKeys() {
      const names = new Set();
      for (const layer of active) {
        for (const key of layer.keys()) {
          names.add(key);
        }
      }
      return [...names];
    },
 
    /**
     * @param {object} target - Unused backing object.
     * @param {string|symbol} key - The name to describe.
     * @returns {object|undefined} A descriptor for a bound name.
     */
    getOwnPropertyDescriptor(target, key) {
      if (typeof key === 'symbol') return undefined;
      if (!resolve(key)) return undefined;
      return { configurable: true, enumerable: true, writable: true, value: this.get(target, key) };
    },
  };
 
  return new Proxy(Object.create(null), handler);
}