@mintjamsinc/ichigojs 0.1.69 → 0.1.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8393,6 +8393,31 @@ class VBindings {
8393
8393
  * is replaced, the binding is set to null/undefined, or the bindings are destroyed.
8394
8394
  */
8395
8395
  #externalSubscriptions = new Map();
8396
+ /**
8397
+ * Recompute callbacks for computed properties registered on these bindings.
8398
+ * Maps a computed property name to a function that recomputes and caches its value.
8399
+ * Only the bindings instance that owns the computed (typically the root) holds an entry;
8400
+ * child bindings resolve computed reads by delegating to their parent through the proxy.
8401
+ */
8402
+ #computedRecomputers = new Map();
8403
+ /**
8404
+ * The set of computed properties whose cached value is stale and must be recomputed on next
8405
+ * access (pull-based evaluation). Populated by markComputedDirty when a dependency changes,
8406
+ * and cleared as each computed is resolved.
8407
+ */
8408
+ #dirtyComputeds = new Set();
8409
+ /**
8410
+ * Guard set used to detect re-entrant (circular) computed resolution. While a computed is
8411
+ * being recomputed its name is held here; a nested read of the same computed returns the
8412
+ * currently cached (stale) value instead of recursing infinitely.
8413
+ */
8414
+ #resolvingComputeds = new Set();
8415
+ /**
8416
+ * The plain backing object behind the #local proxy. Kept as a direct reference so the cached
8417
+ * value of a computed property can be read without triggering pull-based re-evaluation
8418
+ * (see peekComputed).
8419
+ */
8420
+ #store = {};
8396
8421
  /**
8397
8422
  * Creates a new instance of VBindings.
8398
8423
  * @param parent The parent bindings, if any.
@@ -8404,8 +8429,13 @@ class VBindings {
8404
8429
  if (this.#logger?.isDebugEnabled) {
8405
8430
  this.#logger.debug(`VBindings created. Parent: ${this.#parent ? 'yes' : 'no'}`);
8406
8431
  }
8407
- this.#local = new Proxy({}, {
8432
+ this.#local = new Proxy(this.#store, {
8408
8433
  get: (obj, key) => {
8434
+ // Pull-based evaluation: if this key is a dirty computed property, recompute it now
8435
+ // so the read returns a fresh value (synchronously, even before the update microtask).
8436
+ if (typeof key === 'string') {
8437
+ this.#resolveComputedIfDirty(key);
8438
+ }
8409
8439
  if (Reflect.has(obj, key)) {
8410
8440
  return Reflect.get(obj, key);
8411
8441
  }
@@ -8663,6 +8693,79 @@ class VBindings {
8663
8693
  registerWritableComputed(key, setter) {
8664
8694
  this.#writableComputeds.set(key, setter);
8665
8695
  }
8696
+ /**
8697
+ * Registers a computed property for pull-based (lazy) evaluation. The provided recompute
8698
+ * callback is invoked the first time the property is read after it has been marked dirty
8699
+ * (or during the pre-render flush), and is expected to update the cached value (typically
8700
+ * via setSilent).
8701
+ * @param key The computed property name.
8702
+ * @param recompute The callback that recomputes and caches the property's value.
8703
+ */
8704
+ registerComputed(key, recompute) {
8705
+ this.#computedRecomputers.set(key, recompute);
8706
+ }
8707
+ /**
8708
+ * Marks a computed property as dirty so it will be recomputed on next access.
8709
+ * @param key The computed property name.
8710
+ */
8711
+ markComputedDirty(key) {
8712
+ this.#dirtyComputeds.add(key);
8713
+ }
8714
+ /**
8715
+ * Reads the currently cached value of a computed property without triggering pull-based
8716
+ * re-evaluation. Used by the recompute routine to obtain the previous value for change
8717
+ * detection. Falls back to the parent bindings when the key is not stored locally.
8718
+ * @param key The computed property name.
8719
+ * @returns The cached value, or undefined if not cached.
8720
+ */
8721
+ peekComputed(key) {
8722
+ if (Object.prototype.hasOwnProperty.call(this.#store, key)) {
8723
+ return this.#store[key];
8724
+ }
8725
+ return this.#parent?.peekComputed(key);
8726
+ }
8727
+ /**
8728
+ * Forces resolution of every computed property currently marked dirty. Called before the DOM
8729
+ * diff and watcher notification so that the set of changed identifiers is complete.
8730
+ */
8731
+ flushDirtyComputeds() {
8732
+ for (const key of [...this.#dirtyComputeds]) {
8733
+ this.#resolveComputedIfDirty(key);
8734
+ }
8735
+ }
8736
+ /**
8737
+ * Resolves a computed property if its cached value is dirty (pull-based evaluation), by
8738
+ * invoking its registered recompute callback. Computed→computed chains resolve naturally:
8739
+ * reading another computed inside the getter re-enters this method for that key. Re-entrant
8740
+ * resolution of the same key (a circular dependency) is detected and short-circuited, leaving
8741
+ * the previously cached value in place.
8742
+ * @param key The property name to resolve.
8743
+ */
8744
+ #resolveComputedIfDirty(key) {
8745
+ const recompute = this.#computedRecomputers.get(key);
8746
+ if (!recompute) {
8747
+ // Not a computed owned by these bindings; a parent (if any) resolves it when the value
8748
+ // is read through the proxy delegation in the get trap.
8749
+ return;
8750
+ }
8751
+ if (!this.#dirtyComputeds.has(key)) {
8752
+ return;
8753
+ }
8754
+ if (this.#resolvingComputeds.has(key)) {
8755
+ this.#logger?.warn(`Circular dependency detected while resolving computed property '${key}'.`);
8756
+ return;
8757
+ }
8758
+ this.#resolvingComputeds.add(key);
8759
+ try {
8760
+ // Clear the dirty flag before recomputing so reads of this same key during recomputation
8761
+ // (other than a true cycle) do not attempt to resolve it again.
8762
+ this.#dirtyComputeds.delete(key);
8763
+ recompute();
8764
+ }
8765
+ finally {
8766
+ this.#resolvingComputeds.delete(key);
8767
+ }
8768
+ }
8666
8769
  /**
8667
8770
  * Manually adds an identifier to the set of changed identifiers.
8668
8771
  * This is useful for computed properties that need to mark themselves as changed
@@ -13648,7 +13751,8 @@ class VApplication {
13648
13751
  this.#logManager = new VLogManager(options.logLevel);
13649
13752
  this.#logger = this.#logManager.getLogger('VApplication');
13650
13753
  // Analyze function dependencies
13651
- this.#functionDependencies = ExpressionUtils.analyzeFunctionDependencies(options.methods || {});
13754
+ const methods = (options.methods || {});
13755
+ this.#functionDependencies = ExpressionUtils.analyzeFunctionDependencies(methods);
13652
13756
  // Analyze computed dependencies based on getter functions only.
13653
13757
  // Writable computeds (defined as { get, set }) contribute their getter for dependency analysis.
13654
13758
  const computedGetters = {};
@@ -13657,7 +13761,23 @@ class VApplication {
13657
13761
  computedGetters[key] = VApplication.#getComputedGetter(def);
13658
13762
  }
13659
13763
  }
13660
- this.#computedDependencies = ExpressionUtils.analyzeFunctionDependencies(computedGetters);
13764
+ // Resolve computed dependencies against BOTH the computed getters AND the methods, so a
13765
+ // computed that delegates to a method inherits that method's reactive dependencies. A
13766
+ // computed whose only reactive reads happen inside a called method (e.g. a reactive i18n
13767
+ // `t()` helper that reads `this.localization`) would otherwise never be invalidated, leaving
13768
+ // its binding stale on a dependency change. Analyzing the combined set flattens every
13769
+ // computed→method (and computed→computed, method→method) edge down to the underlying
13770
+ // reactive paths — the same expansion that template-expression analysis already performs for
13771
+ // method calls (see ExpressionUtils.extractIdentifiers). We then keep only the computed
13772
+ // entries, since #computedDependencies must be keyed by computed name alone.
13773
+ const combinedDependencies = ExpressionUtils.analyzeFunctionDependencies({
13774
+ ...methods,
13775
+ ...computedGetters,
13776
+ });
13777
+ this.#computedDependencies = {};
13778
+ for (const key of Object.keys(computedGetters)) {
13779
+ this.#computedDependencies[key] = combinedDependencies[key] || [];
13780
+ }
13661
13781
  // Initialize watcher manager
13662
13782
  this.#watcher = new VWatcher(this.#logger);
13663
13783
  // Initialize bindings from data, computed, and methods
@@ -13848,7 +13968,11 @@ class VApplication {
13848
13968
  #initializeBindings() {
13849
13969
  // Create bindings with change tracking
13850
13970
  this.#bindings = new VBindings({
13851
- onChange: () => {
13971
+ onChange: (identifier) => {
13972
+ // Pull-based invalidation: mark dependent computed properties dirty synchronously
13973
+ // so a subsequent synchronous read returns a fresh value, then schedule the
13974
+ // batched DOM update for the next microtask.
13975
+ this.#markDirtyComputeds(identifier);
13852
13976
  this.#scheduleUpdate();
13853
13977
  },
13854
13978
  vApplication: this
@@ -13898,8 +14022,17 @@ class VApplication {
13898
14022
  }
13899
14023
  }
13900
14024
  }
13901
- // Add computed properties (initialization mode)
13902
- this.#recomputeProperties(true);
14025
+ // Register computed properties for pull-based (lazy) evaluation. Each computed is
14026
+ // recomputed on first access after being marked dirty, rather than eagerly in the update
14027
+ // microtask. We mark them all dirty and resolve once here so that initial values are
14028
+ // cached and recorded as changes for the first render.
14029
+ if (this.#options.computed) {
14030
+ for (const key of Object.keys(this.#options.computed)) {
14031
+ this.#bindings.registerComputed(key, () => this.#recomputeOne(key));
14032
+ this.#bindings.markComputedDirty(key);
14033
+ }
14034
+ }
14035
+ this.#flushDirtyComputeds();
13903
14036
  }
13904
14037
  /**
13905
14038
  * Initializes watchers from the watch option.
@@ -13950,8 +14083,9 @@ class VApplication {
13950
14083
  * Executes an immediate DOM update.
13951
14084
  */
13952
14085
  #update() {
13953
- // Re-evaluate computed properties that depend on changed values
13954
- this.#recomputeProperties();
14086
+ // Resolve any computed properties still marked dirty (those not already pulled by a
14087
+ // synchronous read) so that the set of changed identifiers is complete before the DOM diff.
14088
+ this.#flushDirtyComputeds();
13955
14089
  // Apply computed source path mappings to changes
13956
14090
  // This converts paths like "model.elements[0].executionListeners"
13957
14091
  // to "selectedElement.executionListeners" when selectedElement points to model.elements[0]
@@ -13996,110 +14130,116 @@ class VApplication {
13996
14130
  }
13997
14131
  }
13998
14132
  /**
13999
- * Recursively recomputes computed properties based on changed identifiers.
14000
- * @param isInitialization - If true, computes all computed properties regardless of dependencies
14133
+ * Marks computed properties as dirty (pull-based invalidation) when a dependency changes.
14134
+ * Uses the statically analyzed dependency graph; because computed→computed and computed→method
14135
+ * dependencies are flattened to their underlying reactive paths during analysis, a single change
14136
+ * marks every transitively dependent computed dirty in one pass. The actual recomputation is
14137
+ * deferred until the value is read (see #recomputeOne).
14138
+ * @param identifier The changed identifier reported by the bindings change tracker.
14001
14139
  */
14002
- #recomputeProperties(isInitialization = false) {
14003
- if (!this.#options.computed) {
14140
+ #markDirtyComputeds(identifier) {
14141
+ if (!this.#options.computed || !this.#bindings) {
14004
14142
  return;
14005
14143
  }
14006
- const computed = new Set();
14007
- const processing = new Set();
14008
- // Gather all changed identifiers, including all parent paths
14009
- // e.g., for "model.elements[0].messageRef", also add:
14010
- // "model.elements[0]", "model.elements", "model"
14011
- const allChanges = new Set();
14012
- this.#bindings?.changes.forEach(id => {
14013
- allChanges.add(id);
14014
- // Add all parent paths by progressively stripping from the end
14015
- let path = id;
14016
- while (path.length > 0) {
14017
- // Find last separator (either '[' or '.')
14018
- const bracketIdx = path.lastIndexOf('[');
14019
- const dotIdx = path.lastIndexOf('.');
14020
- const lastSep = Math.max(bracketIdx, dotIdx);
14021
- if (lastSep === -1) {
14022
- break;
14023
- }
14024
- path = path.substring(0, lastSep);
14025
- if (path.length > 0) {
14026
- allChanges.add(path);
14027
- }
14028
- }
14029
- });
14030
- // Helper function to recursively compute a property
14031
- const compute = (key) => {
14032
- // Skip if already computed in this update cycle
14033
- if (computed.has(key)) {
14034
- return;
14035
- }
14036
- // Detect circular dependency
14037
- if (processing.has(key)) {
14038
- this.#logger.error(`Circular dependency detected for computed property '${key}'`);
14039
- return;
14040
- }
14041
- processing.add(key);
14042
- // Get the dependencies for this computed property
14144
+ for (const key of Object.keys(this.#computedDependencies)) {
14043
14145
  const deps = this.#computedDependencies[key] || [];
14044
- // First, recursively compute any dependent computed properties.
14045
- // This must happen before the change check so that computed→computed
14046
- // dependency chains are resolved and allChanges is up-to-date.
14047
- for (const dep of deps) {
14048
- if (this.#options.computed[dep]) {
14049
- compute(dep);
14050
- }
14146
+ if (deps.some(dep => this.#dependencyAffectedBy(dep, identifier))) {
14147
+ this.#bindings.markComputedDirty(key);
14051
14148
  }
14052
- // If none of the dependencies have changed, skip recomputation (unless it's initialization).
14053
- // Checked after recursive computation to detect transitive changes through computed properties.
14054
- if (!isInitialization && !deps.some(dep => allChanges.has(dep))) {
14055
- computed.add(key);
14056
- return;
14057
- }
14058
- // Now compute this property
14059
- const computedFn = VApplication.#getComputedGetter(this.#options.computed[key]);
14060
- try {
14061
- const oldValue = this.#bindings?.get(key);
14062
- const newValue = computedFn.call(this.#bindings?.raw);
14063
- // Check if the value actually changed
14064
- let hasChanged = oldValue !== newValue;
14065
- // For arrays, always update (VBindings will detect length changes via its length cache)
14066
- if (!hasChanged && Array.isArray(newValue)) {
14067
- hasChanged = true;
14068
- }
14069
- if (hasChanged) {
14070
- // Use setSilent to avoid triggering onChange during computed property updates
14071
- // Then mark the computed property as changed so UI depending on it will update
14072
- this.#bindings?.setSilent(key, newValue);
14073
- this.#bindings?.markChanged(key);
14074
- allChanges.add(key);
14075
- // Track source path mapping for computed property values
14076
- // This allows changes like "model.elements[0].x" to be mapped to "selectedElement.x"
14077
- if (typeof newValue === 'object' && newValue !== null) {
14078
- const sourcePath = ReactiveProxy.getPath(newValue);
14079
- if (sourcePath) {
14080
- // Remove old mapping for this computed property
14081
- for (const [path, name] of this.#computedSourcePaths) {
14082
- if (name === key) {
14083
- this.#computedSourcePaths.delete(path);
14084
- break;
14085
- }
14149
+ }
14150
+ }
14151
+ /**
14152
+ * Determines whether a change to `changePath` affects a computed dependency `dep`, taking both
14153
+ * path directions into account:
14154
+ * - an exact match;
14155
+ * - `changePath` is a descendant of `dep` (e.g. dep "cartItems", change "cartItems.0.quantity")
14156
+ * — a nested mutation of the dependency;
14157
+ * - `dep` is a descendant of `changePath` (e.g. dep "user.name", change "user") — the container
14158
+ * holding the dependency was replaced wholesale.
14159
+ * Local and global path aliases (e.g. computed source paths) are also honored via the bindings'
14160
+ * own alias-aware matcher.
14161
+ * @param dep The dependency path declared by a computed property.
14162
+ * @param changePath The identifier reported by the bindings change tracker.
14163
+ */
14164
+ #dependencyAffectedBy(dep, changePath) {
14165
+ if (changePath === dep) {
14166
+ return true;
14167
+ }
14168
+ if (changePath.startsWith(dep + '.') || changePath.startsWith(dep + '[')) {
14169
+ return true;
14170
+ }
14171
+ if (dep.startsWith(changePath + '.') || dep.startsWith(changePath + '[')) {
14172
+ return true;
14173
+ }
14174
+ // Fall back to alias-aware matching for aliased paths (computed source paths, props, etc.).
14175
+ return this.#bindings.doesChangeMatchIdentifier(changePath, dep);
14176
+ }
14177
+ /**
14178
+ * Forces resolution of all computed properties currently marked dirty so that the set of
14179
+ * changed identifiers is complete before watcher notification and the DOM diff. Computeds that
14180
+ * were already pulled by a synchronous read earlier in the cycle are no longer dirty and are
14181
+ * skipped, so each computed is recomputed at most once per update cycle.
14182
+ */
14183
+ #flushDirtyComputeds() {
14184
+ this.#bindings?.flushDirtyComputeds();
14185
+ }
14186
+ /**
14187
+ * Recomputes a single computed property and updates its cached value. Registered with the
14188
+ * bindings as the pull-based recompute callback, so it runs lazily the first time the property
14189
+ * is read after being marked dirty (or during the pre-render flush). Computed→computed chains
14190
+ * resolve naturally and order-independently: reading a dependent computed inside the getter
14191
+ * triggers its own lazy resolution through the bindings proxy.
14192
+ *
14193
+ * When the value actually changes, the computed name is recorded as a change so that
14194
+ * dependency-precise DOM updates and watcher notifications still fire, and the source-path
14195
+ * mapping is refreshed so nested changes to the underlying object map back to the computed.
14196
+ * @param key The computed property name.
14197
+ */
14198
+ #recomputeOne(key) {
14199
+ if (!this.#options.computed || !this.#bindings) {
14200
+ return;
14201
+ }
14202
+ const def = this.#options.computed[key];
14203
+ if (!def) {
14204
+ return;
14205
+ }
14206
+ const computedFn = VApplication.#getComputedGetter(def);
14207
+ try {
14208
+ // Read the previous value without triggering re-resolution, for change detection.
14209
+ const oldValue = this.#bindings.peekComputed(key);
14210
+ const newValue = computedFn.call(this.#bindings.raw);
14211
+ // Check if the value actually changed.
14212
+ let hasChanged = oldValue !== newValue;
14213
+ // For arrays, always treat as changed (VBindings detects length changes via its length
14214
+ // cache). This preserves the precise-update behavior of the previous eager implementation.
14215
+ if (!hasChanged && Array.isArray(newValue)) {
14216
+ hasChanged = true;
14217
+ }
14218
+ // Cache the value silently so the read returns it without re-triggering reactivity.
14219
+ this.#bindings.setSilent(key, newValue);
14220
+ if (hasChanged) {
14221
+ // Mark the computed property as changed so UI and watchers depending on it update.
14222
+ this.#bindings.markChanged(key);
14223
+ // Track source path mapping for computed property values.
14224
+ // This allows changes like "model.elements[0].x" to be mapped to "selectedElement.x".
14225
+ if (typeof newValue === 'object' && newValue !== null) {
14226
+ const sourcePath = ReactiveProxy.getPath(newValue);
14227
+ if (sourcePath) {
14228
+ // Remove old mapping for this computed property
14229
+ for (const [path, name] of this.#computedSourcePaths) {
14230
+ if (name === key) {
14231
+ this.#computedSourcePaths.delete(path);
14232
+ break;
14086
14233
  }
14087
- // Add new mapping
14088
- this.#computedSourcePaths.set(sourcePath, key);
14089
14234
  }
14235
+ // Add new mapping
14236
+ this.#computedSourcePaths.set(sourcePath, key);
14090
14237
  }
14091
14238
  }
14092
14239
  }
14093
- catch (error) {
14094
- this.#logger.error(`Error evaluating computed property '${key}': ${error}`);
14095
- }
14096
- computed.add(key);
14097
- processing.delete(key);
14098
- };
14099
- // Compute all properties; the recursive logic inside compute() handles
14100
- // dependency ordering and skips properties whose dependencies did not change.
14101
- for (const key of Object.keys(this.#computedDependencies)) {
14102
- compute(key);
14240
+ }
14241
+ catch (error) {
14242
+ this.#logger.error(`Error evaluating computed property '${key}': ${error}`);
14103
14243
  }
14104
14244
  }
14105
14245
  /**