All files / src/collections reactiveMap.ts

100% Statements 152/152
100% Branches 45/45
100% Functions 13/13
100% Lines 152/152

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 2392x 2x 2x   2x 2x                       2x       39x 49x 49x               39x 21x 21x 21x 21x 21x 15x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 15x 2x 2x 15x 21x 21x 21x 21x                               39x   39x 39x   39x 1x 2x 2x 1x 39x   39x 9x 9x 5x 9x 2x 2x 9x 2x 2x 4x 4x 2x 2x 2x 2x 2x 2x 7x 9x   39x 55x 6x 6x 3x   3x 3x 3x 3x 55x 49x 49x 49x 49x 55x 55x   39x 16x 13x 13x 9x 9x 9x 13x 5x 5x 5x 5x 13x 13x 13x 16x 16x   39x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 3x   39x 4x 3x 3x 3x 3x 3x 3x 4x     39x     39x     39x     39x     39x 52x 52x 14x 14x 14x 14x 52x 52x 52x     39x 67x 3x 3x 2x 2x 3x 67x 67x 39x                                                           2x 39x  
import { batchFlush, batchStart, type BatchTask, tasks } from "../batch";
import { type EventObject, on, type RemoveListener, send, size } 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";
 
export interface ReactiveMapChanged<K, V> {
  readonly upsert: readonly [K, V][];
  readonly delete: readonly K[];
}
 
interface OnChanged<K, V> extends BatchTask<EventObject<ReactiveMapChanged<K, V>>> {
  readonly upsert_: Map<K, V>;
  readonly delete_: Set<K>;
}
 
export class OwnedReactiveMap<K, V> extends Map<K, V> implements ReadableProvider<ReadonlyReactiveMap<K, V>> {
  /**
   * A Readable that emits the map itself whenever it changes.
   */
  public get $(): Readable<ReadonlyReactiveMap<K, V>> {
    return (this._$ ??= writable(this, { equal: false }));
  }
 
  /**
   * Subscribe to changes in the map.
   *
   * @param fn - The function to call when the map is changed.
   * @returns A disposer function to unsubscribe from the event.
   */
  public onChanged(fn: (changed: ReactiveMapChanged<K, V>) => void): RemoveListener {
    return on(
      (this._onChanged_ ??= {
        delete_: new Set<K>(),
        upsert_: new Map<K, V>(),
        task_: () => {
          if (this._onChanged_ && size(this._onChanged_)) {
            const { upsert_, delete_ } = this._onChanged_;
            if (upsert_.size > 0 || delete_.size > 0) {
              const changedData = {
                upsert: [...upsert_],
                delete: [...delete_],
              };
              upsert_.clear();
              delete_.clear();
              send(this._onChanged_, changedData);
            }
          } else {
            this._onChanged_ = null;
          }
        },
      }),
      fn,
    );
  }
 
  /**
   * Subscribe to events when a value is needed to be disposed.
   *
   * A value is considered for disposal when:
   * - it is deleted from the map.
   * - it is replaced by another value (the old value is removed).
   * - it is cleared from the map.
   * - the map is disposed.
   *
   * Note that for performance reasons, it does not handle the case where multiple keys map to the same value.
   *
   * @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(entries?: Iterable<readonly [K, V]> | null) {
    super();
 
    if (entries) {
      for (const [key, value] of entries) {
        super.set(key, value);
      }
    }
  }
 
  public dispose(): void {
    if (this._disposed_) return;
    if (process.env.NODE_ENV !== "production") {
      this._disposed_ = new Error("[embra] ReactiveMap 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._onChanged_ = this.onDisposeValue_ = null;
  }
 
  public override set(key: K, value: V): this {
    if (this.has(key)) {
      const oldValue = this.get(key)!;
      if (!strictEqual(oldValue, value)) {
        const isBatchTop = batchStart();
        // task added in this._upsert_
        this.onDisposeValue_?.delete_.add(oldValue);
        this._upsert_(key, value);
        isBatchTop && batchFlush();
      }
    } else {
      const isBatchTop = batchStart();
      this._upsert_(key, value);
      isBatchTop && batchFlush();
    }
    return this;
  }
 
  public override delete(key: K): boolean {
    if (this.has(key)) {
      const isBatchTop = batchStart();
      if (this.onDisposeValue_) {
        this.onDisposeValue_.delete_.add(this.get(key)!);
        tasks.add(this.onDisposeValue_);
      }
      if (this._onChanged_) {
        this._onChanged_.delete_.add(key);
        this._onChanged_.upsert_.delete(key);
        tasks.add(this._onChanged_);
      }
      this._notify_();
      isBatchTop && batchFlush();
    }
    return super.delete(key);
  }
 
  public override clear(): void {
    if (this.size) {
      const isBatchTop = batchStart();
      if (this.onDisposeValue_ || this._onChanged_) {
        for (const [key, value] of this) {
          if (this.onDisposeValue_) {
            this.onDisposeValue_.delete_.add(value);
            tasks.add(this.onDisposeValue_);
          }
          if (this._onChanged_) {
            this._onChanged_.delete_.add(key);
            this._onChanged_.upsert_.delete(key);
            tasks.add(this._onChanged_);
          }
        }
      }
      super.clear();
      this._notify_();
      isBatchTop && batchFlush();
    }
  }
 
  public rename(key: K, newKey: K): void {
    if (this.has(key)) {
      const isBatchTop = batchStart();
      const value = this.get(key)!;
      this.delete(key);
      this.set(newKey, value);
      isBatchTop && batchFlush();
    }
  }
 
  /** @internal */
  private _disposed_?: Error | true;
 
  /** @internal */
  private _$?: OwnedWritable<this> | null;
 
  /** @internal */
  private _onChanged_?: null | OnChanged<K, V>;
 
  /** @internal */
  public onDisposeValue_?: null | OnDisposeValue<V>;
 
  /** @internal */
  private _upsert_(key: K, value: V): void {
    this.onDisposeValue_?.delete_.delete(value);
    if (this._onChanged_) {
      this._onChanged_.upsert_.set(key, value);
      this._onChanged_.delete_.delete(key);
      tasks.add(this._onChanged_);
    }
    super.set(key, value);
    this._notify_();
  }
 
  /** @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 ReactiveMap<K, V> = Omit<OwnedReactiveMap<K, V>, "dispose">;
 
export interface ReadonlyReactiveMap<K, V> extends ReadonlyMap<K, V> {
  readonly $: Readable<ReadonlyMap<K, V>>;
  /**
   * Subscribe to changes in the map.
   *
   * @param fn - The function to call when the map is changed.
   * @returns A disposer function to unsubscribe from the event.
   */
  onChanged(fn: (changed: ReactiveMapChanged<K, V>) => void): RemoveListener;
  /**
   * Subscribe to events when a value is needed to be disposed.
   *
   * A value is considered for disposal when:
   * - it is deleted from the map.
   * - it is replaced by another value (the old value is removed).
   * - it is cleared from the map.
   * - the map is disposed.
   *
   * Note that for performance reasons, it does not handle the case where multiple keys map to the same value.
   *
   * @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 reactiveMap = <K, V>(entries?: Iterable<readonly [K, V]> | null): OwnedReactiveMap<K, V> =>
  new OwnedReactiveMap(entries);