All files / ima/router ClientRouter.js

48.84% Statements 42/86
15% Branches 9/60
56% Functions 14/25
48.84% Lines 42/86
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                  3x               3x                                                   3x             2x                         15x             15x             16x 16x   16x             3x             3x             2x   2x 2x 2x                       2x       2x             2x 1x 1x   1x 1x 1x   1x               2x                                                                                 2x 2x                                                                                                                                                                                                             3x 1x     2x   2x     2x   2x                           1x       1x   1x                   2x 2x       2x   2x                       4x       3x  
// @client-side
 
import ns from '../namespace';
import AbstractRouter from './AbstractRouter';
import RouteFactory from './RouteFactory';
import Dispatcher from '../event/Dispatcher';
import PageManager from '../page/manager/PageManager';
import Window from '../window/Window';
 
ns.namespace('ima.router');
 
/**
 * Names of the DOM events the router responds to.
 *
 * @enum {string}
 * @type {Object<string, string>}
 */
const Events = Object.freeze({
  /**
	 * Name of the event produced when the user clicks the page using the
	 * mouse, or touches the page and the touch event is not stopped.
	 *
	 * @const
	 * @type {string}
	 */
  CLICK: 'click',
 
  /**
	 * Name of the event fired when the user navigates back in the history.
	 *
	 * @const
	 * @type {string}
	 */
  POP_STATE: 'popstate'
});
 
/**
 * The number used as the index of the mouse left button in DOM
 * {@code MouseEvent}s.
 *
 * @const
 * @type {number}
 */
const MOUSE_LEFT_BUTTON = 0;
 
/**
 * The client-side implementation of the {@codelink Router} interface.
 */
export default class ClientRouter extends AbstractRouter {
  static get $dependencies() {
    return [PageManager, RouteFactory, Dispatcher, Window];
  }
 
  /**
	 * Initializes the client-side router.
	 *
	 * @param {PageManager} pageManager The page manager handling UI rendering,
	 *        and transitions between pages if at the client side.
	 * @param {RouteFactory} factory Factory for routes.
	 * @param {Dispatcher} dispatcher Dispatcher fires events to app.
	 * @param {Window} window The current global client-side APIs provider.
	 */
  constructor(pageManager, factory, dispatcher, window) {
    super(pageManager, factory, dispatcher);
 
    /**
		 * Helper for accessing the native client-side APIs.
		 *
		 * @type {Window}
		 */
    this._window = window;
  }
 
  /**
	 * @inheritdoc
	 */
  init(config) {
    super.init(config);
    this._host = config.$Host || this._window.getHost();
 
    return this;
  }
 
  /**
	 * @inheritdoc
	 */
  getUrl() {
    return this._window.getUrl();
  }
 
  /**
	 * @inheritdoc
	 */
  getPath() {
    return this._extractRoutePath(this._window.getPath());
  }
 
  /**
	 * @inheritdoc
	 */
  listen() {
    let nativeWindow = this._window.getWindow();
 
    this._saveScrollHistory();
    let eventName = Events.POP_STATE;
    this._window.bindEventListener(nativeWindow, eventName, event => {
      if (event.state && !event.defaultPrevented) {
        this.route(this.getPath()).then(() => {
          let scroll = event.state.scroll;
 
          if (scroll) {
            this._pageManager.scrollTo(scroll.x, scroll.y);
          }
        });
      }
    });
 
    this._window.bindEventListener(nativeWindow, Events.CLICK, event => {
      this._handleClick(event);
    });
 
    return this;
  }
 
  /**
	 * @inheritdoc
	 */
  redirect(url = '', options = {}) {
    if (this._isSameDomain(url)) {
      let path = url.replace(this.getDomain(), '');
      path = this._extractRoutePath(path);
 
      this._saveScrollHistory();
      this._setAddressBar(url);
      this.route(path, options);
    } else {
      this._window.redirect(url);
    }
  }
 
  /**
	 * @inheritdoc
	 */
  route(path, options = {}) {
    return super
      .route(path, options)
      .catch(error => {
        return this.handleError({ error });
      })
      .catch(error => {
        this._handleFatalError(error);
      });
  }
 
  /**
	 * @inheritdoc
	 */
  handleError(params, options = {}) {
    if ($Debug) {
      console.error(params.error);
    }
 
    if (this.isClientError(params.error)) {
      return this.handleNotFound(params, options);
    }
 
    if (this.isRedirection(params.error)) {
      options.httpStatus = params.error.getHttpStatus();
      this.redirect(params.error.getParams().url, options);
      return Promise.resolve({
        content: null,
        status: options.httpStatus,
        error: params.error
      });
    }
 
    return super.handleError(params, options).catch(error => {
      this._handleFatalError(error);
    });
  }
 
  /**
	 * @inheritdoc
	 */
  handleNotFound(params, options = {}) {
    return super.handleNotFound(params, options).catch(error => {
      return this.handleError({ error });
    });
  }
 
  /**
	 * Handle a fatal error application state. IMA handle fatal error when IMA
	 * handle error.
	 *
	 * @param {Error} error
	 */
  _handleFatalError(error) {
    if ($IMA && typeof $IMA.fatalErrorHandler === 'function') {
      $IMA.fatalErrorHandler(error);
    } else {
      if ($Debug) {
        console.warn(
          'You must implement $IMA.fatalErrorHandler in ' + 'services.js'
        );
      }
    }
  }
 
  /**
	 * Handles a click event. The method performs navigation to the target
	 * location of the anchor (if it has one).
	 *
	 * The navigation will be handled by the router if the protocol and domain
	 * of the anchor's target location (href) is the same as the current,
	 * otherwise the method results in a hard redirect.
	 *
	 * @param {MouseEvent} event The click event.
	 */
  _handleClick(event) {
    let target = event.target || event.srcElement;
    let anchorElement = this._getAnchorElement(target);
 
    if (!anchorElement || typeof anchorElement.href !== 'string') {
      return;
    }
 
    let anchorHref = anchorElement.href;
    let isDefinedTargetHref = anchorHref !== undefined && anchorHref !== null;
    let isSetTarget = anchorElement.getAttribute('target') !== null;
    let isLeftButton = event.button === MOUSE_LEFT_BUTTON;
    let isCtrlPlusLeftButton = event.ctrlKey && isLeftButton;
    let isCMDPlusLeftButton = event.metaKey && isLeftButton;
    let isSameDomain = this._isSameDomain(anchorHref);
    let isHashLink = this._isHashLink(anchorHref);
    let isLinkPrevented = event.defaultPrevented;
 
    if (
      !isDefinedTargetHref ||
      isSetTarget ||
      !isLeftButton ||
      !isSameDomain ||
      isHashLink ||
      isCtrlPlusLeftButton ||
      isCMDPlusLeftButton ||
      isLinkPrevented
    ) {
      return;
    }
 
    event.preventDefault();
    this.redirect(anchorHref);
  }
 
  /**
	 * The method determines whether an anchor element or a child of an anchor
	 * element has been clicked, and if it was, the method returns anchor
	 * element else null.
	 *
	 * @param {Node} target
	 * @return {?Node}
	 */
  _getAnchorElement(target) {
    let self = this;
 
    while (target && !hasReachedAnchor(target)) {
      target = target.parentNode;
    }
 
    function hasReachedAnchor(nodeElement) {
      return (
        nodeElement.parentNode &&
        nodeElement !== self._window.getBody() &&
        nodeElement.href !== undefined &&
        nodeElement.href !== null
      );
    }
 
    return target;
  }
 
  /**
	 * Tests whether the provided target URL contains only an update of the
	 * hash fragment of the current URL.
	 *
	 * @param {string} targetUrl The target URL.
	 * @return {boolean} {@code true} if the navigation to target URL would
	 *         result only in updating the hash fragment of the current URL.
	 */
  _isHashLink(targetUrl) {
    if (targetUrl.indexOf('#') === -1) {
      return false;
    }
 
    let currentUrl = this._window.getUrl();
    let trimmedCurrentUrl =
      currentUrl.indexOf('#') === -1
        ? currentUrl
        : currentUrl.substring(0, currentUrl.indexOf('#'));
    let trimmedTargetUrl = targetUrl.substring(0, targetUrl.indexOf('#'));
 
    return trimmedTargetUrl === trimmedCurrentUrl;
  }
 
  /**
	 * Sets the provided URL to the browser's address bar by pushing a new
	 * state to the history.
	 *
	 * The state object pushed to the history will be an object with the
	 * following structure: {@code {url: string}}. The {@code url} field will
	 * be set to the provided URL.
	 *
	 * @param {string} url The URL.
	 */
  _setAddressBar(url) {
    let scroll = {
      x: 0,
      y: 0
    };
    let state = { url, scroll };
 
    this._window.pushState(state, null, url);
  }
 
  /**
	 * Save user's scroll state to history.
	 *
	 * Replace scroll values in current state for actual scroll values in
	 * document.
	 */
  _saveScrollHistory() {
    let url = this.getUrl();
    let scroll = {
      x: this._window.getScrollX(),
      y: this._window.getScrollY()
    };
    let state = { url, scroll };
 
    this._window.replaceState(state, null, url);
  }
 
  /**
	 * Tests whether the the protocol and domain of the provided URL are the
	 * same as the current.
	 *
	 * @param {string=} [url=''] The URL.
	 * @return {boolean} {@code true} if the protocol and domain of the
	 *         provided URL are the same as the current.
	 */
  _isSameDomain(url = '') {
    return !!url.match(this.getBaseUrl());
  }
}
 
ns.ima.router.ClientRouter = ClientRouter;