All files / src/core application.js

99.02% Statements 102/103
85% Branches 17/20
97.29% Functions 36/37
99% Lines 99/100

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 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391                                  1x 1x 1x 1x 1x         1x               2x           2x           2x           2x             2x           2x             2x     2x     2x                   2x 2x   2x 1x           1x 1x     2x                     5x 3x     5x                 1x               1x                   4x   4x 4x 3x   4x 4x 4x           4x 2x 2x       4x 4x 4x 4x   4x 3x 3x   3x     3x 3x       2x 2x   2x       2x   2x       1x 1x 1x       1x                   2x                     2x                 2x   2x   2x   2x   2x   2x       2x     2x     2x     2x     2x                 3x 3x 3x                 2x 2x 2x                 1x   1x 1x 1x       1x       1x                 2x 2x 2x                   2x 2x 2x                   2x 2x 2x   2x                 6x 6x                     6x 6x   8x   8x   6x                   4x                                
/**
 * @fileoverview Main MVC application class.
 * @author Dmytro Antonenko <dmitry.antonenko@pubwebkit.com>
 */
import {ActionEvent} from './events/action_event.js';
import {ActionExceptionEvent} from './events/action_exception_event.js';
import {ActionFilterContext} from './types/action_filter_context.js';
import {ActionFilterItem} from './types/action_filter_item.js';
import {ActionFilter} from './action_filter.js';
import {ApplicationEventType} from './application_event_type.js';
import {ApplicationFilterItem} from './types/application_filter_item.js';
import {ApplicationFilter} from './application_filter.js';
import {Controller} from './controller.js';
import {Request} from './request.js';
import {Response} from './response.js';
import {Router} from './router.js';
 
const EventTarget = goog.require('goog.events.EventTarget');
const Promise = goog.require('goog.Promise');
const array = goog.require('goog.array');
const dom = goog.require('goog.dom');
const gString = goog.require('goog.string');
 
/**
 * RegExp to parse route fragment.
 */
const ROUTE_PATTERN_REGEXP = /:[a-zA-Z0-9._-]*/g;
 
/**
 * @abstract
 * @extends {EventTarget}
 */
export class Application extends EventTarget {
  constructor() {
    super();
 
    /**
     * @const {!Router}
     * @private
     */
    this.router_ = new Router(false, undefined, this.getHistoryStateInput_());
 
    /**
     * @const {!Array<!ActionFilterItem>}
     * @private
     */
    this.actionFilters_ = [];
 
    /**
     * @const {!Array<!ApplicationFilterItem>}
     * @private
     */
    this.applicationFilters_ = [];
 
    /**
     * The fragment we are mapping the controller to.
     * @type {!RegExp}
     * @private
     */
    this.currentRoute_;
 
    /**
     * @type {boolean}
     * @private
     */
    this.isFirstLoad_ = true;
 
    /**
     * Initialized controllers map.
     * @const {!Map<string, !Controller>}
     * @private
     */
    this.controllersMap_ = new Map();
 
    // Initialize application.
    this.init();
 
    // Run application.
    this.run();
  }
 
  /**
   * Gets history state input field. Creates new one if it's not exist in the
   * document.
   * @returns {!HTMLInputElement}
   * @private
   */
  getHistoryStateInput_() {
    const id = 'history_state';
    let inputElement = dom.getElement(id);
 
    if (inputElement == null) {
      const attributes = {
        'id' : id,
        'type' : 'text',
        'name' : 'history_state',
        'style' : 'display:none'
      };
      inputElement = dom.createDom('input', attributes);
      dom.getDocument().body.appendChild(inputElement);
    }
 
    return /** @type {!HTMLInputElement} **/ (inputElement);
  }
 
  /**
   * Map route to controller.
   * @param {string} route The path The fragment we are mapping the controller
   * to.
   * @param {!Function} controller The name or object that identifying the
   * desired controller.
   */
  mapRoute(route, controller) {
    if(!gString.endsWith(route, '{?*}') && route !== '*') {
      route += '{?*}';
    }
 
    this.router_.route(
        route, goog.partial(this.processRoute_, route, controller).bind(this));
  }
 
  /**
   * Gets all defined routes in the application.
   * @returns {!Array<!Object>}
   */
  getRoutes() {
    return this.router_.getRoutes();
  }
 
  /**
   * Gets application router class.
   * @returns {!Router}
   */
  getRouter() {
    return this.router_;
  }
 
  /**
   * @param {string} route The fragment we are mapping the controller to.
   * @param {function(new:Controller)} controller Controller constructor
   *    related to current route.
   * @private
   */
  processRoute_(route, controller) {
    this.setCurrentRoute_(route);
 
    const controllersMap = this.controllersMap_;
    if (!controllersMap.has(route)) {
      controllersMap.set(route, new controller());
    }
    const pattern = ROUTE_PATTERN_REGEXP;
    const controllerInstance = controllersMap.get(route);
    const routeData = {
      'action': 'index',
      'controller': controllerInstance.getControllerName(),
      'isFirstLoad': this.isFirstLoad_
    };
 
    for (let i = 3, match; (match = pattern.exec(route)) !== null; i++) {
      if (arguments[i] !== undefined) {
        routeData[gString.removeAll(match[0], ':')] = arguments[i];
      }
    }
 
    const queryVals = arguments[arguments.length - 1];
    const request = new Request(routeData, window.location.href, queryVals);
    const response = new Response(request, this.router_);
    const filterContext = new ActionFilterContext(request, response);
 
    if (typeof controllerInstance[routeData['action']] === 'function') {
      new Promise((resolve, reject) => {
        let event = new ActionEvent(filterContext,
            ApplicationEventType.ACTIONEXECUTING, resolve, this);
        this.dispatchEvent(event);
      })
      .then(() => {
        return new Promise((resolve, reject) => {
          resolve(controllerInstance[routeData['action']](request, response));
        });
      })
      .then(() => {
        return new Promise((resolve, reject) => {
          let event = new ActionEvent(filterContext,
              ApplicationEventType.ACTIONEXECUTED, resolve, this);
          this.dispatchEvent(event);
        });
      })
      .then(() => {
        return new Promise((resolve, reject) => {
          // Application loaded
          resolve(this.dispatchEvent(ApplicationEventType.APPLICATIONLOADED));
        });
      })
      .thenCatch((error) => {
        if (error instanceof Error) {
          let event = new ActionExceptionEvent(filterContext, this, error);
          this.dispatchEvent(event);
        }
      });
    } else {
      throw new Error(`Action "${routeData['action']}" does not exist!`);
    }
  }
 
  /**
   * Register application filter
   * @param {!ApplicationFilter} filter
   * @param {number=} opt_order
   */
  addApplicationFilter(filter, opt_order) {
    array.insert(
        this.applicationFilters_, new ApplicationFilterItem(filter, opt_order));
  }
 
  /**
   * Register action filter
   * @param {!ActionFilter} filter
   * @param {string|!RegExp=} opt_route Route to watch for.
   * @param {number=} opt_order
   */
  addActionFilter(filter, opt_route, opt_order) {
    array.insert(
        this.actionFilters_, new ActionFilterItem(filter, opt_route, opt_order));
  }
 
  /**
   * Start application execution
   */
  run() {
    // Initialize events
    this.listenOnce(ApplicationEventType.APPLICATIONSTART,
        this.onApplicationStart_, false, this);
    this.listenOnce(ApplicationEventType.APPLICATIONRUN,
        this.onApplicationRun_, false, this);
    this.listenOnce(ApplicationEventType.APPLICATIONLOADED,
        this.onApplicationLoaded_, false, this);
    this.listen(ApplicationEventType.ACTIONEXCEPTION,
        this.onActionException_, false, this);
    this.listen(ApplicationEventType.ACTIONEXECUTING,
        this.onActionExecuting_, false, this);
    this.listen(ApplicationEventType.ACTIONEXECUTED,
        this.onActionExecuted_, false, this);
 
    // Sort application filters
    array.sort(this.applicationFilters_, (a, b) => a.getOrder() - b.getOrder());
 
    // Application start
    this.dispatchEvent(ApplicationEventType.APPLICATIONSTART);
 
    // Sort action filters
    array.sort(this.actionFilters_, (a, b) => a.getOrder() - b.getOrder());
 
    // Check current route
    this.router_.checkRoutes();
 
    // Application run
    this.dispatchEvent(ApplicationEventType.APPLICATIONRUN);
  }
 
  /**
   * Called before the action method is invoked.
   * @param {!ActionEvent} e
   * @private
   */
  onActionExecuting_(e) {
    this.forEachActionFilter_(
        (filterItem) => filterItem.getFilter().onActionExecuting(e));
    e.resolvePromise();
  }
 
  /**
   * Called after the action method is invoked.
   * @param {!ActionEvent} e
   * @private
   */
  onActionExecuted_(e) {
    this.forEachActionFilter_(
        (filterItem) => filterItem.getFilter().onActionExecuted(e));
    e.resolvePromise();
  }
 
  /**
   * Called when an unhandled exception occurs in the action.
   * @param {!ActionExceptionEvent} e
   * @private
   */
  onActionException_(e) {
    let exceptionHandled = false;
 
    this.forEachActionFilter_((filterItem) => {
      exceptionHandled = true;
      filterItem.getFilter().onException(e);
    });
 
    // Print error to console if not handled
    Iif (!exceptionHandled) {
      console.error(e.getError(), e);
    }
 
    e.resolvePromise();
  }
 
  /**
   * Called when an application start initialization.
   * @param {!Event} e
   * @private
   */
  onApplicationStart_(e) {
    const router = this.router_;
    this.forEachApplicationFilter_((filterItem) => {
      filterItem.getFilter().onApplicationStart(e, router);
    });
  }
 
  /**
   * Called when an application end initialization.
   * @param {!Event} e
   * @private
   */
  onApplicationRun_(e) {
    const router = this.router_;
    this.forEachApplicationFilter_((filterItem) => {
      filterItem.getFilter().onApplicationRun(e, router);
    });
  }
 
  /**
   * Called when an application launched.
   * @param {!Event} e
   * @private
   */
  onApplicationLoaded_(e) {
    const router = this.router_;
    this.forEachApplicationFilter_((filterItem) => {
      filterItem.getFilter().onApplicationLoaded(e, router);
    });
    this.isFirstLoad_ = false;
  }
 
  /**
   * Calls a function for each registered application filter.
   * @param {!Function} callback
   * @private
   */
  forEachApplicationFilter_(callback) {
    array.forEach(this.applicationFilters_, (filterItem) => {
      callback.call(this, filterItem);
    }, this);
  }
 
  /**
   * Calls a function for each registered action filter, but skip filters with
   * route that not match current route.
   * @param {!Function} callback
   * @private
   */
  forEachActionFilter_(callback) {
    const currentRoute = this.currentRoute_;
    array.forEach(this.actionFilters_, (filterItem) => {
      // Check route and run
      let route = filterItem.getRoute();
 
      if (gString.isEmptyOrWhitespace(gString.makeSafe(route)) ||
          currentRoute.exec(route)) {
        callback.call(this, filterItem);
      }
    }, this);
  }
 
  /**
   * @param {string} route
   * @private
   */
  setCurrentRoute_(route) {
    this.currentRoute_ =
        new RegExp('^' + gString.regExpEscape(route)
            .replace(/\\:\w+/g, '([a-zA-Z0-9._-]+)')
            .replace(/\\\*/g, '(.*)')
            .replace(/\\\[/g, '(')
            .replace(/\\\]/g, ')?')
            .replace(/\\\{/g, '(?:')
            .replace(/\\\}/g, ')?') + '$');
  }
 
  /**
   * Initialize application.
   * @abstract
   */
  init() {}
}