All files / src/Compute Compute.ts

94.73% Statements 72/76
90.32% Branches 28/31
78.57% Functions 11/14
95.89% Lines 70/73

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 2349x 9x 9x 9x 9x 9x   9x               9x 9x   9x 163x 139x   139x 133x 39x 39x     94x   94x     139x     9x 171x 171x   171x   171x 95x   95x 39x       171x   171x 157x           9x     9x 49x 49x   49x   49x 79x 51x   51x                                                                                       9x   61x     61x                 61x       61x     61x     61x                                             61x 61x   61x 59x     61x 6x           49x   49x     49x 30x 28x     2x         94x 94x   94x 94x 94x   94x 78x 78x                                       86x 58x     86x         4x      
import { scope } from '../constants'
import { bindObserver } from '../helpers/bindObserver'
import { clearWatcher } from '../helpers/clearWatcher'
import { destroyWatchers } from '../helpers/destroyWatchers'
import { watchWithScope } from '../helpers/watchWithScope'
import { Observable } from '../Observable'
import type { Destructor, Observer, Reaction, Watcher } from '../types'
import { shiftSet } from '../utils/shiftSet'
 
/* queue */
 
let currentCompute: Compute
let currentObserver: Observer
let forcedQueue: boolean
 
const computeStack = new Set<Compute>()
const observersStack = new Set<Observer>()
 
export function forceQueueWatchers () {
  if (forcedQueue) return
  forcedQueue = true
 
  while ((currentCompute = shiftSet(computeStack)) || (currentObserver = shiftSet(observersStack))) {
    if (currentCompute) {
      currentCompute.invalid = true
      continue
    }
 
    clearWatcher(currentObserver)
 
    currentObserver.update()
  }
 
  forcedQueue = false
}
 
export function queueWatchers (observers: Set<Observer>) {
  const useLoop = !scope.eventDeep && !observersStack.size && !computeStack.size
  const oldObserversStack = [...observersStack]
 
  observersStack.clear()
 
  observers.forEach(watcher => {
    observersStack.add(watcher)
 
    if (watcher instanceof Compute) {
      computeStack.add(watcher)
    }
  })
 
  oldObserversStack.forEach(observer => observersStack.add(observer))
 
  if (useLoop) {
    forceQueueWatchers()
  }
}
 
/* invalidateCompute */
 
const invalidateStack: Observer[] = []
let currentInvalidateObserver: Observer | undefined
 
export function invalidateCompute (observer: Observer) {
  const skipLoop = invalidateStack.length
  invalidateStack.push(observer)
 
  Iif (skipLoop) return
 
  while ((currentInvalidateObserver = invalidateStack.shift())) {
    if (currentInvalidateObserver instanceof Compute) {
      invalidateStack.push(...currentInvalidateObserver.observers)
 
      currentInvalidateObserver.invalid = true
    }
  }
}
 
/* Compute */
 
/**
 * Cached reactive computation with memoization.
 * Recalculates value only when dependencies change and when it is actively consumed
 * by a Watcher or another Compute that is itself consumed by a Watcher.
 *
 * This ensures that computations are only evaluated when their output is actually needed,
 * enabling efficient lazy evaluation and automatic subscription management.
 *
 * @class Compute
 * @extends Observable<V>
 * @implements {Observer}
 * @template V - computed value type
 *
 * @example
 * const fullName = new State('Mighty Mike')
 * const name = new Compute(() => fullName.value.split(' ')[1])
 *
 * // Only when accessed inside an `Observer`, `Compute` becomes active:
 *
 * const nameWatcher = new Watch(() => console.log(name.value))
 * // Triggers computation and subscribes to `name`
 *
 * // This does NOT trigger recomputation:
 * console.log(name.value)
 *
 * // If used inside another `Compute` that is watched, it triggers:
 * const greeting = new Compute(() => `${name.value} How are you?`)
 *
 * const greetingWatcher new Watch(() => console.log(greeting.value))
 * // Triggers greeting
 *
 * fullName.value = 'Mighty Michael'
 * // Triggers full chain: fullName → name → greeting → greetingWatcher
 *
 * fullName.value = 'Deight Michael'
 * // Triggers part of chain: fullName → name
 */
export class Compute<V = unknown> extends Observable<V> implements Observer {
  /** Indicates if computed value is stale and needs recalculation. */
  invalid = true
 
  /** Tracks if the computation has run at least once. */
  updated = false
 
  // @ts-expect-error This is intentional — accessing destroyed observers is rare and shouldn't require undefined checks in normal code.
  raw: V
 
  /**
   * Indicates if observer has been destroyed.
   * Prevents accidental use after cleanup.
   */
  destroyed = false
 
  // TODO: remove in major release
  /** @deprecated Use `observer instanceof Compute` */
  isCache = true
 
  /** Cleanup functions to run on destroy (e.g., unsubscribes). */
  readonly destructors = new Set<Destructor>()
 
  /** Child watchers created within this watcher's scope */
  readonly children = new Set<Observer>()
 
  // TODO: remove in major release
  /** @deprecated Use `children` */
  get childrenObservers () {
    return this.children
  }
 
  // TODO: remove in major release
  /** @deprecated Use `childrenObservers` */
  get childWatchers () {
    return this.children
  }
 
  // TODO: remove in major release
  /** @deprecated Use `reaction` */
  get watcher () {
    return this.reaction
  }
 
  constructor (reaction: Reaction<V>, freeParent?: boolean, fireImmediately?: boolean)
  /** @deprecated `update` argument is deprecated, use `Reaction` */
  constructor (reaction: Watcher<V>, freeParent?: boolean, fireImmediately?: boolean)
  constructor (readonly reaction: Watcher<V> | Reaction<V>, freeParent?: boolean, fireImmediately?: boolean) {
    super()
 
    if (!freeParent) {
      bindObserver(this)
    }
 
    if (fireImmediately) {
      this.forceUpdate()
    }
  }
 
  /** Mark computation as invalid and trigger propagation to parent observers. */
  update () {
    invalidateCompute(this)
 
    const parents = [...this.observers]
    let parent: Observer | undefined
 
    while ((parent = parents.pop())) {
      if (!(parent instanceof Compute)) {
        return this.forceUpdate()
      }
 
      parents.push(...parent.observers)
    }
  }
 
  forceUpdate () {
    Eif (!this.destroyed) {
      this.invalid = false
 
      watchWithScope(this, () => {
        const newValue = this.reaction(this.updated) // TODO: remove `this.updated` in major release
        this.updated = true
 
        if (newValue !== this.raw) {
          this.raw = newValue
          queueWatchers(this.observers)
        }
      })
    }
  }
 
  /**
   * Current value with automatic subscription.
   *
   * Accessing `value` inside an `Observer` automatically subscribes the watcher.
   *
   * @example
   * const count = new State(0)
   * const text = new Compute(() => `Count: ${count.value}`)
   *
   * new Watch(() => console.log(text.value)) // Count: 0
   *
   * count.value++ // Count: 1
   */
  get value () {
    if (this.invalid) {
      this.forceUpdate()
    }
 
    return this.destroyed ? this.raw : super.value
  }
 
  /** Stop observation and remove all dependencies. */
  destroy () {
    destroyWatchers(this)
  }
}