All files / core/view EventQueue.ts

98.31% Statements 58/59
95% Branches 19/20
100% Functions 12/12
98.25% Lines 56/57
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                                  12x                                 12x         43x             43x         12x   2870x 2870x 626x 626x 626x 14x 14x     626x 479x     626x   2870x 465x                         12x 570x 570x 125x                         12x 1889x   1889x 422x               12x     2459x   2459x 2459x 557x 557x 547x 547x 536x 536x   11x         2459x 2452x     2459x   12x           12x         479x   479x         12x 626x           12x 536x 689x 689x 626x 626x 626x     626x               12x 708x   12x  
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import { Path } from '../util/Path';
import { log, logger, exceptionGuard } from '../util/util';
import { Event } from './Event';
 
/**
 * The event queue serves a few purposes:
 * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
 *    events being queued.
 * 2. raiseQueuedEvents() handles being called reentrantly nicely.  That is, if in the course of raising events,
 *    raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
 *    left off, ensuring that the events are still raised synchronously and in order.
 * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
 *    events are raised synchronously.
 *
 * NOTE: This can all go away if/when we move to async events.
 *
 * @constructor
 */
export class EventQueue {
  /**
   * @private
   * @type {!Array.<EventList>}
   */
  private eventLists_: EventList[] = [];
 
  /**
   * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
   * @private
   * @type {!number}
   */
  private recursionDepth_ = 0;
 
  /**
   * @param {!Array.<Event>} eventDataList The new events to queue.
   */
  queueEvents(eventDataList: Event[]) {
    // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
    let currList = null;
    for (let i = 0; i < eventDataList.length; i++) {
      const eventData = eventDataList[i];
      const eventPath = eventData.getPath();
      if (currList !== null && !eventPath.equals(currList.getPath())) {
        this.eventLists_.push(currList);
        currList = null;
      }
 
      if (currList === null) {
        currList = new EventList(eventPath);
      }
 
      currList.add(eventData);
    }
    if (currList) {
      this.eventLists_.push(currList);
    }
  }
 
  /**
   * Queues the specified events and synchronously raises all events (including previously queued ones)
   * for the specified path.
   *
   * It is assumed that the new events are all for the specified path.
   *
   * @param {!Path} path The path to raise events for.
   * @param {!Array.<Event>} eventDataList The new events to raise.
   */
  raiseEventsAtPath(path: Path, eventDataList: Event[]) {
    this.queueEvents(eventDataList);
    this.raiseQueuedEventsMatchingPredicate_((eventPath: Path) =>
      eventPath.equals(path)
    );
  }
 
  /**
   * Queues the specified events and synchronously raises all events (including previously queued ones) for
   * locations related to the specified change path (i.e. all ancestors and descendants).
   *
   * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
   *
   * @param {!Path} changedPath The path to raise events for.
   * @param {!Array.<!Event>} eventDataList The events to raise
   */
  raiseEventsForChangedPath(changedPath: Path, eventDataList: Event[]) {
    this.queueEvents(eventDataList);
 
    this.raiseQueuedEventsMatchingPredicate_((eventPath: Path) => {
      return eventPath.contains(changedPath) || changedPath.contains(eventPath);
    });
  }
 
  /**
   * @param {!function(!Path):boolean} predicate
   * @private
   */
  private raiseQueuedEventsMatchingPredicate_(
    predicate: (path: Path) => boolean
  ) {
    this.recursionDepth_++;
 
    let sentAll = true;
    for (let i = 0; i < this.eventLists_.length; i++) {
      const eventList = this.eventLists_[i];
      if (eventList) {
        const eventPath = eventList.getPath();
        if (predicate(eventPath)) {
          this.eventLists_[i].raise();
          this.eventLists_[i] = null;
        } else {
          sentAll = false;
        }
      }
    }
 
    if (sentAll) {
      this.eventLists_ = [];
    }
 
    this.recursionDepth_--;
  }
}
 
/**
 * @param {!Path} path
 * @constructor
 */
export class EventList {
  /**
   * @type {!Array.<Event>}
   * @private
   */
  private events_: Event[] = [];
 
  constructor(private readonly path_: Path) {}
 
  /**
   * @param {!Event} eventData
   */
  add(eventData: Event) {
    this.events_.push(eventData);
  }
 
  /**
   * Iterates through the list and raises each event
   */
  raise() {
    for (let i = 0; i < this.events_.length; i++) {
      const eventData = this.events_[i];
      if (eventData !== null) {
        this.events_[i] = null;
        const eventFn = eventData.getEventRunner();
        Iif (logger) {
          log('event: ' + eventData.toString());
        }
        exceptionGuard(eventFn);
      }
    }
  }
 
  /**
   * @return {!Path}
   */
  getPath(): Path {
    return this.path_;
  }
}