All files / src/collections reactiveArray.ts

100% Statements 134/134
100% Branches 43/43
100% Functions 17/17
100% Lines 134/134

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 2352x   2x   2x 2x   2x   2x                           79x 48x 48x                           79x         79x 79x   79x 79x 79x 79x 79x 79x 79x 79x                 79x 4x 4x 4x 3x 3x 3x 4x 4x   79x 3x 2x 2x 2x 3x   79x 4x 3x 3x 3x 4x 4x   79x 61x 61x 61x 61x   79x 4x 2x 2x 2x 2x 4x   79x 4x 2x 2x 2x 2x 4x   79x 4x 4x 4x 4x       79x 11x 11x 10x 10x 11x 11x   79x 3x 2x 2x 2x 3x 3x   79x 4x 3x 3x 3x 4x 4x   79x 4x 3x 3x 3x 4x 4x   79x 9x 9x 5x 9x 2x 2x 9x 5x 5x 14x 14x 5x 5x 5x 5x 5x 5x 7x 9x     79x     79x     79x     79x 93x 2x 2x 1x 1x 2x 93x 93x 79x                                                                         2x 65x 65x 47x 47x 65x 65x  
import { batchFlush, batchStart, tasks } from "../batch";
import { type RemoveListener } from "../event";
import { writable } from "../readable";
import { type ReadableProvider, type OwnedWritable, type Readable } from "../typings";
import { strictEqual } from "../utils";
import { onDisposeValue, type OnDisposeValue } from "./utils";
 
const nonEnumerable = { enumerable: false };
 
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 set itself whenever it changes.
   */
  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.
   *
   * @param fn - The function to call when a value is needed to be disposed.
   * @returns A disposer function to unsubscribe from the event.
   */
  public readonly onDisposeValue = 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;
  }
 
  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();
        tasks.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(new Error("disposed"));
      if (process.env.NODE_ENV !== "production") {
        console.error(this._disposed_);
      }
    }
    this._$?.set(this);
  }
}
 
export type ReactiveArray<V> = Omit<OwnedReactiveArray<V>, "dispose">;
 
export interface ReadonlyReactiveArray<V> extends ReadonlyArray<V> {
  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;
  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.
   *
   * @param fn - The function to call when a value is needed to be disposed.
   * @returns A disposer function to unsubscribe from the event.
   */
  onDisposeValue(fn: (value: V) => void): RemoveListener;
}
 
export const reactiveArray = <V>(values?: Iterable<V> | null): OwnedReactiveArray<V> => {
  const arr = new OwnedReactiveArray<V>();
  if (values) {
    arr.push(...values);
  }
  return arr;
};