All files / json-crdt/model/api NodeEvents.ts

100% Statements 12/12
100% Branches 0/0
100% Functions 5/5
100% Lines 10/10

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  156x         156x                                           591x 591x 591x                   581x 581x         591x 2x 591x    
import type {FanOut} from 'thingies/lib/fanout';
import {MapFanOut, OnNewFanOut} from './fanout';
import type {JsonNode, JsonNodeView} from '../../nodes';
import type {SyncStore, SyncStoreUnsubscribe} from '../../../util/events/sync-store';
import type {NodeApi} from './nodes';
 
export class NodeEvents<N extends JsonNode = JsonNode> implements SyncStore<JsonNodeView<N>> {
  /**
   * Fired on any model change, even if the node's value has not changed. The
   * changes are fired once per microtask, so multiple changes in the same
   * microtask are batched into a single event.
   */
  public readonly onChanges: FanOut<JsonNodeView<N>>;
 
  /**
   * Similar to `.onChanges`, but fired when the node's view has changed,
   * checked using triple equality `===`.
   *
   * The strict equality identity is preserved deeply equal values, even for
   * objects and arrays. So, this event will not fire if there was a change
   * to the node's value, but the value is still deeply equal to the previous
   * value.
   *
   * This event depends on overall Model's `onChanges` event, which is
   * batched using `queueMicrotask`.
   */
  public readonly onViewChanges: FanOut<JsonNodeView<N>>;
 
  constructor(private readonly api: NodeApi<N>) {
    this.onChanges = new MapFanOut(this.api.api.onChanges, this.getSnapshot);
    this.onViewChanges = new OnNewFanOut(this.onChanges, this.api.view());
  }
 
  /**
   * Called when this node is deleted.
   *
   * @internal
   * @ignore
   */
  public handleDelete() {
    (this.onViewChanges as OnNewFanOut<JsonNodeView<N>>).clear();
    (this.onChanges as MapFanOut<unknown, unknown>).clear();
  }
 
  // ---------------------------------------------------------------- SyncStore
 
  public readonly subscribe = (callback: () => void): SyncStoreUnsubscribe =>
    this.onViewChanges.listen(() => callback());
  public readonly getSnapshot = () => this.api.view();
}