All files / src/RuneHub RuneHub.ts

100% Statements 211/211
100% Branches 88/88
100% Functions 36/36
100% Lines 199/199

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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751  4x                                                                                                                                                                                                                 4x               251x     251x     251x     251x     251x     251x                 251x     251x     251x   251x 251x                           251x 251x 251x   251x 128x                               11x   11x   11x 11x 11x   11x   11x 4x                 392x 80x 80x                                   753x 240x   240x   240x 240x                     456x 456x   456x 15x     441x 441x 441x   441x       469x   215x       380x   380x 380x 377x     380x   380x                   242x 242x 242x 242x                               654x 654x   654x 2x     654x                               189x                             83x                                 346x   346x 317x     346x                                 211x 41x     211x 198x 189x     198x 198x                     318x 318x 318x   318x 107x 107x                                                                             158x 106x 103x   103x 99x 4x 2x     103x 19x     103x     106x 1x     106x 106x   106x 25x 24x   1x 1x       52x   52x 49x   3x     52x                           105x 89x 89x 89x   89x 46x   46x 42x   4x       89x 89x 89x 89x 89x 89x   89x     16x   16x   15x                   2380x   76x   76x 76x 76x 76x 77x                       331x   318x 318x                   139x 1x   1x   1x     138x 138x 138x 138x 138x 138x 138x   138x 153x 1x       138x 129x                     319x   319x 318x 318x     319x   319x 262x   262x 136x 149x   139x 58x   81x                       4x   4x                 7x     7x     7x     7x                   456x 456x 456x 456x   456x                     81x 81x 81x 81x   81x                 403x 217x   217x     186x 186x 186x                 187x   186x 20x   20x     166x       166x 396x 318x   78x       166x               1x 2x     1x 1x 1x 1x 1x      
import type { QueueItem } from '../Queue'
import { Queue } from '../Queue'
 
/**
 * Generic function type with configurable parameters and return type.
 * @template P - Array of parameter types
 * @template R - Return type
 * @example
 * ```typescript
 * const add: Fn<[number, number], number> = (a, b) => a + b
 * const log: Fn<[string], void> = (msg) => console.log(msg)
 * ```
 */
export type Fn<P extends any[] = any[], R = any> = (...args: P) => R
 
/**
 * A rune is a reactive computation function.
 * Can be a computed value or an effect (side-effect function).
 * Runes are the core building blocks of the reactive system.
 * @template R - The type of value returned by the rune (void for effects)
 * @example
 * ```typescript
 * const counter: Rune<number> = () => 42
 * const effect: Rune<void> = () => console.log('side effect')
 * ```
 */
export type Rune<R = any> = Fn<[], R>
 
/**
 * A function that performs cleanup when called.
 * Typically returned by subscription methods to allow unsubscribing.
 * @example
 * ```typescript
 * const unsubscribe: Destructor = on(count, 'change', () => {
 *   console.log('changed')
 * })
 *
 * // Later: unsubscribe()
 * ```
 */
export type Destructor = Fn<[], void>
 
/**
 * A listener function that responds to events.
 * Listeners are called when specific events occur on a slot.
 * @example
 * ```typescript
 * const listener: Listener = () => {
 *   console.log('Event triggered!')
 * }
 *
 * slot.on('change', listener)
 * ```
 */
export type Listener = Fn<[], void>
 
/**
 * An action is a side-effect function that performs work.
 * Actions are used in batching and context management.
 * @example
 * ```typescript
 * const action: Action = () => {
 *   set(count, raw(count) + 1)
 *   console.log('Action performed')
 * }
 *
 * batch(action)
 * ```
 */
export type Action = Fn<[], void>
 
/**
 * Events that can be emitted by a slot during its lifecycle.
 * - `init`: Slot has been initialized
 * - `update`: Slot value is being updated
 * - `call`: Rune function is being called
 * - `change`: Slot value has changed
 * - `clear`: Slot dependencies are being cleared
 * - `destroy`: Slot is being destroyed
 * - `up`: Slot has gained subscribers
 * - `down`: Slot has lost all subscribers
 * - `get`: Fired when a rune's value is accessed
 * @example
 * ```typescript
 * const count = () => 0
 * on(count, 'change', () => console.log('Count changed!'))
 * on(count, 'init', () => console.log('Count initialized'))
 * ```
 */
export type Event = 'init' | 'update' | 'call' | 'change' | 'clear' | 'destroy' | 'up' | 'down' | 'get'
 
/**
 * A Slot manages the reactive state and dependencies for a rune.
 * It tracks subscribers, dependencies, and handles updates in the reactive graph.
 * @template T - The type of value managed by this slot
 * @example
 * ```typescript
 * const count = new Slot(() => 0)
 *
 * // Subscribe to changes
 * count.on('change', () => console.log('Changed to:', count.raw))
 *
 * // Set new value
 * count.set(5)
 * ```
 */
export class Slot<T = unknown> {
  /** Current value of the slot */
  cur?: T
 
  /** Previous value of the slot (before last update) */
  prev?: T
 
  /** Whether the slot has active subscribers */
  up: boolean = false
 
  /** Whether the slot has been initialized */
  inited: boolean = false
 
  /** Whether the slot is currently being prepared/initialized */
  prep: boolean = false
 
  /** The slot is a simple state */
  state: boolean = false
 
  /** Whether a set operation occurred during the current computation */
  sets: boolean = false
 
  /** Whether the slot has any subscribers */
  hasSub: boolean = false
 
  /** Queue item indicating this slot is scheduled for recomputation (needs to call force()) */
  queue: QueueItem<Slot> | undefined
 
  /** Queue item indicating this slot is scheduled for update notification (needs to call forceUpdate()) */
  updateQueue: QueueItem<Slot> | undefined
 
  /** Set of slots that depend on this slot (subscribers) */
  subs: Set<Slot> = new Set<Slot>()
 
  /** Set of slots this slot depends on (dependencies) */
  deps: Set<Slot> = new Set<Slot>()
 
  /** Event listeners registered for various slot lifecycle events */
  events: Partial<Record<Event, Listener[]>> = {}
 
  private activity = 0
  private onId = {}
 
  /**
   * Creates a new Slot for managing a rune's reactive state.
   * @param rune - The rune function to manage
   * @param hub - The hub that owns this slot (defaults to root hub)
   * @param anon - Whether this is an anonymous slot (not registered in hub)
   * @example
   * ```typescript
   * const count = () => 0
   * const slot = new Slot(count, Hub.root, false)
   * ```
   */
  constructor (
    readonly rune: Rune<T>,
    readonly hub: Hub = Hub.root,
    readonly anon: boolean = hub === Hub.root,
  ) {
    if (!anon) {
      hub.slots.set(rune, this)
    }
  }
 
  /**
   * Destroys the slot, cleaning up all subscriptions and removing it from the hub.
   * Emits 'clear' and 'destroy' events before cleanup.
   * @example
   * ```typescript
   * const slot = new Slot(() => 0)
   *
   * slot.on('change', () => console.log('changed'))
   * slot.destroy() // Cleans up all subscriptions and remove from hub
   * ```
   */
  destroy (): void {
    this.event(this.events.destroy)
 
    this.off()
 
    this.up = false
    this.prep = false
    this.inited = false
 
    this.clearQueue()
 
    if (!this.anon) {
      this.hub.slots.delete(this.rune)
    }
  }
 
  /**
   * Clears any pending recomputation from the queue.
   * @internal
   */
  private clearQueue () {
    if (this.queue) {
      this.queue.abort()
      this.queue = undefined
    }
  }
 
  /**
   * Initializes the slot by computing its initial value.
   * Runs the rune function and tracks dependencies.
   * Emits 'init' event when complete.
   * @example
   * ```typescript
   * const slot = new Slot(() => 42)
   *
   * console.log(slot.cur) // undefined
   * slot.init() // Computes initial value and emits 'init'
   * console.log(slot.cur) // 42
   * ```
   */
  init (): void {
    if (this.prep) return
    this.prep = true
 
    this.call()
 
    this.inited = true
    this.event(this.events.init)
  }
 
  /**
   * Executes an action within this slot's context.
   * Sets this slot as the current context for dependency tracking.
   * @template A - The action function type
   * @param action - The action to execute
   * @returns The result of the action
   */
  use <A extends Fn<[]>> (action: A): ReturnType<A> {
    const hub = this.hub
    const prevSlot = hub.ctx
 
    if (prevSlot === this) {
      return hub.use(action)
    }
 
    hub.ctx = this
    const result = hub.use(action)
    hub.ctx = prevSlot
 
    return result
  }
 
  clear () {
    if (!this.inited) return
 
    this.event(this.events.clear)
  }
 
  rawCall (): void {
    this.sets = false
 
    this.use(() => {
      if (!this.updateQueue) {
        this.prev = this.cur
      }
 
      this.cur = this.rune()
 
      this.event(this.events.call)
    })
  }
 
  /**
   * Calls the rune function to compute a new value.
   * Tracks dependencies and emits 'clear' and 'call' events.
   * @internal
   */
  call () {
    do {
      this.clear()
      this.clearQueue()
      this.rawCall()
    } while (this.queue)
  }
 
  /**
   * Gets the current value without tracking dependencies.
   * Initializes the slot if needed and forces any pending updates.
   * @returns The current value
   * @example
   * ```typescript
   * const slot = new Slot(() => 42)
   *
   * console.log(slot.raw) // 42, no dependency tracking
   * ```
   */
  get raw (): T {
    this.event(this.events.get)
    this.init()
 
    if (this.queue) {
      this.force()
    }
 
    return this.cur!
  }
 
  /**
   * Gets the current value with dependency tracking.
   * Alias for the get() method.
   * @example
   * ```typescript
   * const slot = new Slot(() => 0)
   *
   * on(() => {
   *   console.log(slot.value) // Tracks dependency
   * })
   * ```
   */
  get value (): T {
    return this.get()
  }
 
  /**
   * Sets a new value for the slot.
   * Alias for the set() method.
   * @example
   * ```typescript
   * const slot = new Slot(() => 0)
   *
   * slot.value = 42 // Sets new value
   * console.log(slot.value) // 42
   * ```
   */
  set value (value: T) {
    this.set(value)
  }
 
  /**
   * Gets the current value and tracks this slot as a dependency.
   * If called within another slot's context, creates a dependency relationship.
   * @returns The current value
   * @example
   * ```typescript
   * const count = new Slot(() => 0)
   *
   * on(() => {
   *   console.log(count.get())
   * })
   * ```
   */
  get (): T {
    const result = this.raw
 
    if (this.hub.ctx && !this.hub.unwatching) {
      this.hub.ctx.bind(this)
    }
 
    return result
  }
 
  /**
   * Sets a new value for the slot.
   * If the value differs from the current value, schedules an update.
   * @param value - The new value to set
   * @example
   * ```typescript
   * const count = new Slot(() => 0)
   * count.on('change', () => console.log('Changed to:', count.raw))
   *
   * slot.set(42) // Logs: Changed to: 42
   * slot.set(42) // No change, no log
   * ```
   */
  set (value: T): void {
    if (this.hub.ctx) {
      this.hub.ctx.sets = true
    }
 
    if (this.raw !== value) {
      if (!this.updateQueue) {
        this.prev = this.cur
      }
 
      this.cur = value
      this.update()
    }
  }
 
  /**
   * Creates a dependency relationship with another slot.
   * This slot will be notified when the other slot updates.
   * @param slot - The slot to depend on
   * @internal
   */
  bind (slot: Slot): void {
    this.deps.add(slot)
    slot.subs.add(this)
    slot.hasSub = true
 
    if (!slot.up) {
      slot.up = true
      slot.event(slot.events.up)
    }
  }
 
  /**
   * Activates the slot and keeps it active.
   * @returns A destructor function to deactivate
   * @example
   * ```typescript
   * const count = new Slot(() => 0)
   *
   * const log = new Slot(() => {
   *   console.log(count.value)
   * })
   *
   * log.on()
   * count.set(1) // logs: 1
   * ```
   */
  on (): Destructor
  /**
   * Subscribes to a specific slot event.
   * @param event - The event to listen for
   * @param listener - The listener function to call
   * @returns A destructor function to unsubscribe
   * @example
   * ```typescript
   * const count = new Slot(() => 0)
   *
   * const unsubscribe = count.on('change', () => {
   *   console.log('Value changed to:', count.raw)
   * })
   *
   * slot.set(42) // Logs: Value changed to: 42
   * unsubscribe() // Stop listening
   * ```
   */
  on (event: Event, listener: Listener): Destructor
  on (event?: Event, listener?: Listener) {
    if (!event) {
      if (!this.up) {
        this.up = true
 
        if (!this.inited) {
          this.init()
        } else if (!this.state) {
          this.call()
        }
 
        if (!this.deps.size) {
          this.state = true
        }
 
        this.event(this.events.up)
      }
 
      if (this.hub.ctx && !this.hub.unwatching) {
        this.hub.ctx.bind(this)
      }
 
      let onId: object = this.onId
      this.activity++
 
      return () => {
        if (this.onId !== onId) return
        if (this.activity === 1) return this.off()
 
        this.activity--
        onId = {}
      }
    }
 
    const events = this.events[event]
 
    if (!events) {
      this.events[event] = [listener!]
    } else {
      events.push(listener!)
    }
 
    return this.off.bind(this, event, listener!)
  }
 
  /**
   * Deactivates the slot and removes all its dependencies.
   */
  off (): void
  /**
   * Unsubscribes a specific listener from an event.
   * @param event - The event to unsubscribe from
   * @param listener - The listener to remove
   */
  off (event: Event, listener: Listener): void
  off (event?: Event, listener?: Listener) {
    if (!event) {
      this.clear()
      this.activity = 0
      this.onId = {}
 
      this.deps.forEach((source) => {
        const sourceListeners = source.subs
 
        if (sourceListeners.size === 1) {
          source.off()
        } else {
          sourceListeners.delete(this)
        }
      })
 
      this.deps.clear()
      this.subs.forEach(sub => sub.deps.delete(this))
      this.subs.clear()
      this.hasSub = false
      this.up = false
      this.event(this.events.down)
 
      return
    }
 
    const events = this.events[event]
 
    if (!events) return
 
    this.events[event] = events.filter((l) => l !== listener)
  }
 
  /**
   * Triggers a list of event listeners.
   * Executes listeners in a batched, unwatched context.
   * @param events - Array of listener functions to call
   * @internal
   */
  event (events?: Listener[]): void {
    if (!events || !events.length) return
 
    const hub = this.hub
 
    this.use(() => {
      hub.unwatch(() => {
        hub.batch(() => {
          for (let i = 0; i < events.length; i++) {
            events[i]()
          }
        })
      })
    })
  }
 
  /**
   * Schedules an update notification for this slot.
   * Queues the slot for update processing in the next batch.
   */
  update (): void {
    if (this.updateQueue) return
 
    this.hub.batch(() => {
      this.updateQueue = this.hub.queue.force(this)
    })
  }
 
  /**
   * Forces recomputation of the slot's value.
   * Recomputes dependencies and schedules updates.
   * @internal
   */
  force () {
    if (!this.deps.size) {
      this.clearQueue()
 
      this.update()
 
      return
    }
 
    do {
      this.clear()
      this.clearQueue()
      const deps = this.deps
      const newDeps = new Set<Slot>()
      this.deps = newDeps
      this.rawCall()
 
      for (const dep of deps) {
        if (!newDeps.has(dep)) {
          dep.off()
        }
      }
 
      if (this.inited) {
        this.update()
      }
    } while (this.queue)
  }
 
  /**
   * Forces immediate update notification to subscribers.
   * Emits 'update' and 'change' events and propagates to subscribers.
   * @internal
   */
  forceUpdate () {
    const updateQueue = this.updateQueue
 
    if (updateQueue) {
      updateQueue.abort()
      this.updateQueue = undefined
    }
 
    this.event(this.events.update)
 
    if (this.prev !== this.cur) {
      this.event(this.events.change)
 
      if (this.hasSub) {
        for (const sub of this.subs) {
          if (sub.queue) continue
 
          if (sub.hasSub || sub.sets) {
            sub.force()
          } else {
            sub.queue = this.hub.queue.push(sub)
          }
        }
      }
    }
  }
}
 
/**
 * Hub manages the reactive system's execution context and slot lifecycle.
 * It handles batching updates, tracking dependencies, and managing slot instances.
 */
export class Hub {
  /** The root hub instance used as the default hub */
  static root = new Hub()
 
  /** The currently active hub during execution */
  static cur: Hub | undefined
 
  /** The currently executing slot (for dependency tracking) */
  ctx: Slot | undefined
 
  /** Map of runes to their corresponding slots */
  readonly slots: Map<Rune, Slot> = new Map()
 
  /** Whether dependency tracking is currently disabled */
  unwatching: boolean = false
 
  /** Whether updates are currently being batched */
  batching = false
 
  /** Queue for managing slot updates */
  readonly queue: Queue<Slot> = new Queue()
 
  /**
   * Executes an action within this hub's context.
   * Sets this hub as the current hub during execution.
   * @template A - The action function type
   * @param action - The action to execute
   * @returns The result of the action
   */
  use <A extends Fn<[]>> (action: A): ReturnType<A> {
    const prevHub = Hub.cur
    Hub.cur = this
    const result = action()
    Hub.cur = prevHub
 
    return result
  }
 
  /**
   * Executes an action without tracking dependencies.
   * Temporarily disables dependency tracking during execution.
   * @template A - The action function type
   * @param action - The action to execute
   * @returns The result of the action
   */
  unwatch <A extends Fn<[]>> (action: A): ReturnType<A> {
    const prevUnwatch = this.unwatching
    this.unwatching = true
    const result = action()
    this.unwatching = prevUnwatch
 
    return result
  }
 
  /**
   * Batches multiple updates together for efficient processing.
   * Updates are queued and processed together after the action completes.
   * @param action - The action to execute in batch mode
   */
  batch (action: Action): void {
    if (this.batching) {
      action()
 
      return
    }
 
    this.batching = true
    action()
    this.endBatching()
  }
 
  /**
   * Processes all queued updates and ends batch mode.
   * Flushes the update queue and notifies all affected slots.
   * @internal
   */
  endBatching (): void {
    if (!this.batching) return
 
    if (!this.queue.size) {
      this.batching = false
 
      return
    }
 
    const queue = this.queue
 
    let item: QueueItem<Slot> | undefined
 
    while ((item = queue.start)) {
      if (item.forced) {
        item.value.forceUpdate()
      } else {
        item.value.force()
      }
    }
 
    this.batching = false
  }
 
  /**
   * Destroys the hub and all its slots.
   * Cleans up all resources and resets the hub state.
   */
  destroy () {
    this.slots.forEach((slot) => {
      slot.destroy()
    })
 
    this.slots.clear()
    this.queue.clear()
    this.batching = false
    this.unwatching = false
    this.ctx = undefined
  }
}