All files / src/collections reactiveArray.ts

100% Statements 79/79
100% Branches 49/49
100% Functions 17/17
100% Lines 78/78

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              18x                                               55x                                                     87x           87x   87x                                 21x 21x 21x 16x 16x   21x       10x 4x 4x         4x 3x 3x   4x       68x 68x 68x       4x 2x 2x 2x         4x 2x 2x 2x         4x 4x 4x           11x 11x 10x   11x       3x 2x 2x   3x       4x 3x 3x   4x       4x 3x 3x   4x                 7x 7x 7x 17x   7x 7x 7x       10x 8x 6x   2x   8x 6x 6x 14x   6x 5x 5x 5x     8x                           114x 2x 2x 1x     114x                                                                                                                                                                       18x 73x 73x 54x   73x    
import { batchFlush, batchStart, batchTasks } from "../batch";
import { type RemoveListener } from "../event";
import { type ReadableProvider, type OwnedWritable, type Readable } from "../interface";
import { writable } from "../readable";
import { strictEqual } from "../utils";
import { onDisposeValue, type OnDisposeValue } from "./utils";
 
const nonEnumerable = { enumerable: false };
 
/**
 * OwnedReactiveArray extends the standard Array interface with reactive capabilities.
 *
 * @category ReactiveArray
 */
export class OwnedReactiveArray<V> extends Array<V> implements ReadableProvider<ReadonlyReactiveArray<V>> {
  readonly [n: number]: V;
 
  /**
   * Gets the length of the array.
   * This is a number one higher than the highest index in the array.
   *
   * Use `.setLength(length)` to change the length of the array.
   */
  declare public readonly length: number;
 
  /**
   * A Readable that emits the Array itself whenever it changes.
   *
   * @group Readable
   */
  public get $(): Readable<ReadonlyReactiveArray<V>> {
    return (this._$ ??= writable(this, { equal: false }));
  }
 
  /**
   * Subscribe to events when a value is needed to be disposed.
   *
   * A value is considered for disposal when:
   * - it is deleted from the array.
   * - it is replaced by another value (the old value is removed).
   * - it is cleared from the array.
   * - the array is disposed.
   *
   * @group Events
   * @function
   * @param fn - The function to call when a value is needed to be disposed.
   * @returns A disposer function to unsubscribe from the event.
   *
   * @example
   * ```ts
   * import { reactiveArray } from "@embra/reactivity";
   *
   * const arr = reactiveArray<number>();
   * const disposer = arr.onDisposeValue((value) => {
   *   console.log("Value disposed:", value);
   * });
   * ```
   */
  public readonly onDisposeValue: (fn: (value: V) => void) => RemoveListener = onDisposeValue;
 
  public constructor(arrayLength?: number);
  public constructor(arrayLength: number);
  public constructor(...items: V[]);
  public constructor(...args: V[]) {
    super(...args);
 
    Object.defineProperties(this, {
      onDisposeValue: nonEnumerable,
      onDisposeValue_: nonEnumerable,
      set: { ...nonEnumerable, value: this.set },
      _$: nonEnumerable,
      _disposed_: nonEnumerable,
    });
  }
 
  /**
   * Overwrites the value at the provided index with the given value.
   * If the index is negative, then it replaces from the end of the array.
   * @param index The index of the value to overwrite. If the index is
   * negative, then it replaces from the end of the array.
   * @param value The value to write into the array.
   */
  public set(index: number, value: V): this {
    index = Number(index);
    index = index < 0 ? this.length + index : index;
    if (index >= 0 && Number.isFinite(index) && !strictEqual(this[index], value)) {
      (this as any)[index] = value;
      this._notify_();
    }
    return this;
  }
 
  public setLength(value: number): void {
    if (value >= 0 && value !== this.length) {
      super.length = value;
      this._notify_();
    }
  }
 
  public override fill(value: V, start?: number, end?: number): this {
    if (this.length > 0) {
      super.fill(value, start, end);
      this._notify_();
    }
    return this;
  }
 
  public override push(...items: V[]): number {
    const length = super.push(...items);
    items.length > 0 && this._notify_();
    return length;
  }
 
  public override pop(): V | undefined {
    if (this.length > 0) {
      const value = super.pop();
      this._notify_();
      return value;
    }
  }
 
  public override shift(): V | undefined {
    if (this.length > 0) {
      const value = super.shift();
      this._notify_();
      return value;
    }
  }
 
  public override unshift(...items: V[]): number {
    const length = super.unshift(...items);
    items.length > 0 && this._notify_();
    return length;
  }
 
  public override splice(start: number, deleteCount?: number): V[];
  public override splice(start: number, deleteCount: number, ...items: V[]): V[];
  public override splice(...args: [number, number, ...V[]]): V[] {
    const removed = super.splice(...args);
    if (removed.length > 0 || args.length > 2) {
      this._notify_();
    }
    return removed;
  }
 
  public override reverse(): this {
    if (this.length > 1) {
      super.reverse();
      this._notify_();
    }
    return this;
  }
 
  public override sort(compareFn?: (a: V, b: V) => number): this {
    if (this.length > 1) {
      super.sort(compareFn);
      this._notify_();
    }
    return this;
  }
 
  public override copyWithin(target: number, start: number, end?: number): this {
    if (this.length > 0) {
      super.copyWithin(target, start, end);
      this._notify_();
    }
    return this;
  }
 
  /**
   * Replaces the contents of the array with the provided items.
   * @param items The new items to replace the contents of the array with.
   * @returns The array itself.
   */
  public replace(items: Iterable<V>): this {
    const isBatchTop = batchStart();
    let i = 0;
    for (const item of items) {
      this.set(i++, item);
    }
    this.setLength(i);
    isBatchTop && batchFlush();
    return this;
  }
 
  public dispose(): void {
    if (this._disposed_) return;
    if (process.env.NODE_ENV !== "production") {
      this._disposed_ = new Error("[embra] ReactiveArray disposed at:");
    } else {
      this._disposed_ = true;
    }
    if (this.onDisposeValue_) {
      const { delete_ } = this.onDisposeValue_;
      for (const value of this.values()) {
        delete_.add(value);
      }
      if (delete_.size) {
        const isBatchTop = batchStart();
        batchTasks.add(this.onDisposeValue_!);
        isBatchTop && batchFlush();
      }
    }
    this._$ = this.onDisposeValue_ = null;
  }
 
  /** @internal */
  private _disposed_?: Error | true;
 
  /** @internal */
  private _$?: OwnedWritable<this> | null;
 
  /** @internal */
  public onDisposeValue_?: null | OnDisposeValue<V>;
 
  /** @internal */
  private _notify_() {
    if (this._disposed_) {
      console.error(this, new Error("disposed"));
      if (process.env.NODE_ENV !== "production") {
        console.error(this._disposed_);
      }
    }
    this._$?.set(this);
  }
}
 
/**
 * ReactiveArray is {@link OwnedReactiveArray} without the `dispose` method.
 *
 * @category ReactiveArray
 */
export type ReactiveArray<V> = Omit<OwnedReactiveArray<V>, "dispose">;
 
/**
 * ReadonlyReactiveArray is a readonly interface for {@link ReactiveArray}.
 *
 * @category ReactiveArray
 */
export interface ReadonlyReactiveArray<V> extends ReadonlyArray<V> {
  /**
   * A Readable that emits the Array itself whenever it changes.
   *
   * @group Readable
   */
  readonly $: Readable<readonly V[]>;
  /**
   * Gets the length of the array.
   * This is a number one higher than the highest index in the array.
   *
   * Use `.setLength(length)` to change the length of the array.
   */
  readonly length: number;
  /**
   * Overwrites the value at the provided index with the given value.
   * If the index is negative, then it replaces from the end of the array.
   * @param index The index of the value to overwrite. If the index is
   * negative, then it replaces from the end of the array.
   * @param value The value to write into the array.
   */
  set(index: number, value: V): this;
  /**
   * Updates the length of the array.
   * @param value The new length of the array.
   */
  setLength(value: number): void;
  /**
   * Subscribe to events when a value is needed to be disposed.
   *
   * A value is considered for disposal when:
   * - it is deleted from the array.
   * - it is replaced by another value (the old value is removed).
   * - it is cleared from the array.
   * - the array is disposed.
   *
   * @group Events
   * @function
   * @param fn - The function to call when a value is needed to be disposed.
   * @returns A disposer function to unsubscribe from the event.
   *
   * @example
   * ```ts
   * import { reactiveArray } from "@embra/reactivity";
   *
   * const arr = reactiveArray<number>();
   * const disposer = arr.onDisposeValue((value) => {
   *   console.log("Value disposed:", value);
   * });
   * ```
   */
  readonly onDisposeValue: (fn: (value: V) => void) => RemoveListener;
}
 
/**
 * Creates a new {@link OwnedReactiveArray}.
 *
 * @category ReactiveArray
 * @param values - Initial values for the reactive array.
 * @returns A new instance of {@link OwnedReactiveArray}.
 *
 * @example
 * ```ts
 * import { reactiveArray } from "@embra/reactivity";
 *
 * const arr$ = reactiveArray([1, 2, 3]);
 * ```
 */
export const reactiveArray = <V>(values?: Iterable<V> | null): OwnedReactiveArray<V> => {
  const arr = new OwnedReactiveArray<V>();
  if (values) {
    arr.push(...values);
  }
  return arr;
};