All files / solid/src reactive.ts

100% Statements 70/70
100% Branches 28/28
100% Functions 2/2
100% Lines 70/70

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  1x 1x                       1x 1x 1x   1x   1x   1x   1x                       1x 12x 12x   3x 3x   3x 1x 1x   1x   1x 1x 1x 1x   1x 1x 1x 1x 1x   2x   3x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   2x 2x     2x     2x 2x 2x   2x 2x     2x 2x 2x 2x 1x   1x 4x 3x 3x   1x 1x 1x                   6x 6x 6x 6x                   1x 2x 1x 1x   2x 2x  
import type { StateObserver } from '@anchorlib/core';
import { createObserver, microbatch, onGlobalCleanup, setCleanUpHandler, setTracker } from '@anchorlib/core';
import { createSignal, getOwner, onCleanup, type Owner } from 'solid-js';
import type { ConstantRef, VariableRef } from './types.js';
 
type ElementRef = {
  version: () => number;
  observer: StateObserver;
};
 
type InternalOwner = Owner & {
  comparator?: (a: unknown, b: unknown) => boolean;
};
 
export const REF_REGISTRY = new WeakSet<VariableRef<unknown> | ConstantRef<unknown>>();
export const COMPONENT_REGISTRY = new WeakMap<Owner, Map<Owner, ElementRef>>();
export const ELEMENT_OBSERVER_REGISTRY = new WeakMap<Owner, StateObserver>();
 
const [batch] = microbatch(0);
 
let bindingInitialized = false;
 
if (!bindingInitialized) {
  // Make sure to initialize binding only once.
  bindingInitialized = true;
 
  /**
   * Setup global tracker to bind observer with component.
   * This tracker is responsible for synchronizing state changes with Solid component instances.
   * When a reactive state is accessed, this tracker captures the current component instance
   * and ensures that any observers associated with that component are notified of changes.
   *
   * @param init - The initial state value
   * @param observers - Array of observer functions to be notified of changes
   * @param key - The property key being accessed
   */
  setTracker((init, observers, key) => {
    const element = getOwner();
    if (!element) return;
 
    const component = getPureOwner(element as InternalOwner);
    if (!component) return;
 
    if (!COMPONENT_REGISTRY.has(component)) {
      const elements = new Map();
      COMPONENT_REGISTRY.set(component, elements);
 
      attachCleanup(component, () => {
        // Batch the cleanup to unblock the component destruction.
        batch(() => {
          for (const [, { observer }] of elements) {
            observer.destroy();
          }
 
          elements.clear();
          COMPONENT_REGISTRY.delete(component);
        });
      });
    }
 
    const registry = COMPONENT_REGISTRY.get(component)!;
 
    if (!registry.has(element)) {
      const [version, setVersion] = createSignal(0);
      const observer = createObserver(
        () => {
          observer.reset();
          setVersion(version() + 1);
        },
        undefined,
        true
      );
 
      registry.set(element, { version, observer });
    }
 
    if (!ELEMENT_OBSERVER_REGISTRY.has(element)) {
      const { version, observer } = registry.get(element)!;
 
      // Trigger signal read to observe.
      version();
 
      // Register cleanup to properly handle element re-creation on state change.
      onCleanup(() => {
        ELEMENT_OBSERVER_REGISTRY.delete(element);
      });
 
      ELEMENT_OBSERVER_REGISTRY.set(element, observer);
    }
 
    // Batch the tracking to unblock the property reads.
    const observer = ELEMENT_OBSERVER_REGISTRY.get(element);
    batch(() => {
      observer?.assign(init, observers)(key);
    });
  });
 
  setCleanUpHandler((handler) => {
    if (getOwner()) {
      return onCleanup(handler);
    }
 
    return onGlobalCleanup(handler);
  });
}
 
/**
 * Recursively finds the nearest owner in the component tree that has owned components.
 * This function traverses up the owner chain to find the closest parent owner that
 * actually owns child components, filtering out intermediate owners that don't own anything.
 *
 * @param node - Optional Owner node to start the search from. If not provided, uses the current owner.
 * @returns The first Owner that has owned components, or undefined if no such owner exists
 */
function getPureOwner(node?: InternalOwner | null): InternalOwner | undefined {
  if (!node) return;
  return node.owned && !node.comparator ? node : getPureOwner(node?.owner as InternalOwner);
}
 
/**
 * Attaches a cleanup function to the given owner node.
 * This function ensures that the cleanup array exists on the node
 * and adds the provided cleanup function to that array.
 *
 * @param node - The Owner node to attach the cleanup function to
 * @param cleanup - A function to be called when the node is cleaned up
 */
export function attachCleanup(node: Owner, cleanup: () => void) {
  if (!Array.isArray(node.cleanups)) {
    node.cleanups = [];
  }
 
  node.cleanups.push(cleanup);
}