all files / src/ Application.js

45.03% Statements 77/171
45.65% Branches 21/46
28.57% Functions 16/56
36.44% Lines 43/118
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 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 53243×                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
// ReactIEE
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, hashHistory, browserHistory } from 'react-router';
 
// Redux
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import { syncHistoryWithStore, routerReducer, routerMiddleware } from 'react-router-redux';
 
// Utils
import { snakeCase } from 'lodash';
import invariant from 'invariant';
 
// Local
import { getLogger } from './Logger';I
 
// Package globals
const LOG = getLogger('Application');
 
const PluginType = {
  PLUGIN: 'plugin',
  MODULE: 'module',
};
 
// Application Singleton
let APPLICATION_INSTANCE;
 
/**
 * The application container is the heart of your app.
 * It wraps the Redux store and acts as a proxy for it.
 * You can use an instance of Application as a drop-in
 * replacement for the Redux store.
 *
 * It further provides the following functionality:
 * <ul>
 *   <li>{@link Module} registration</li>
 *   <li>Action type discovery</li>
 *   <li>Configurable middleware and store enhancers</li>
 * </ul>
 *
 * @class Application
 */
class Application {
  constructor() {
    if (!APPLICATION_INSTANCE) {
      this._name = 'Application';
      this._version = '0.0.0';
      this._key = 'config';
      this._mount = null;
      this._modules = new Map();
      this._plugins = new Map();
      this._reducers = {};
      this._actionTypes = {};
      this._store = null;
      this._middleware = [];
      this._enhancers = [];
      this._routes = [];
      this._history = null;
      this._historyApiEnabled = false;
      this._debug = false;
 
      APPLICATION_INSTANCE = this;
    }
 
    return APPLICATION_INSTANCE;
  }
 
  /**
   * Get the application name.
   *
   * @returns {string}
   */
  getName() {
    return this._name;
  }
 
  /**
   * Set the application name.
   *
   * @param {string} name - The application name.
   */
  setName(name) {
    this._name = name;
  }
 
  /**
   * Fluent interface for {@link setName}.
   *
   * @extends setName
   * @returns {Application}
   */
  name(name) {
    this.setName(name);
    return this;
  }
 
  /**
   * Get the application version.
   *
   * @returns {string}
   */
  getVersion() {
    return this._version;
  }
 
  /**
   * Set the application version.
   *
   * @param {string} version - A [semver]{@link http://semver.org/} compliant version.
   */
  setVersion(version) {
    this._version = version;
  }
 
  /**
   * Fluent interface for {@link setVersion}
   *
   * @extends setVersion
   * @returns {Application}
   */
  version(version) {
    this.setVersion(version);
    return this;
  }
 
  /**
   * Get the application state key.
   *
   * @returns {string}
   */
  getKey() {
    return this._key;
  }
 
  /**
   * Set the application state key.
   *
   * @param {string} key - A key.
   * @param {boolean} [transform=true] - Toggles automatic snakeCase transformation of key.
   */
  setKey(key, transform = true) {
    if (transform) {
      this._key = snakeCase(key);
    } else {
      this._key = key;
    }
  }
 
  /**
   * Fluent interface for {@link setKey}.
   *
   * @extends setName
   * @returns {Application}
   */
  key(key, transform = true) {
    this.setKey(key, transform);
    return this;
  }
 
  /**
   * Get the DOM node the application is mounted on.
   *
   * @returns {Node}
   */
  getMount() {
    return this._mount;
  }
 
  /**
   * Set the DOM node to mount the application on.
   *
   * @param {Node} node - A DOM node.
   */
  setMount(node) {
    this._mount = node;
  }
 
  /**
   * Fluent interface for {@link setMount}.
   *
   * @extends setMount
   * @returns {Application}
   */
  mount(node) {
    this.setMount(node);
    return this;
  }
 
  /**
   * Add a {@link Module} to the application.
   * Fluent interface.
   *
   * @param {Module} module - A module to add to the application.
   * @returns {Application}
   */
  addModule(module) {
    return this._register(PluginType.MODULE, this._modules, module);
  }
 
  /**
   * Get a module by key.
   *
   * @param {string} key - The key of the module to return.
   * @returns {Module | null}
   */
  getModule(key) {
    invariant(
      this._modules.has(key),
      `No module with key ${key} is registered with the application`
    );
 
    return this._modules.get(key);
  }
 
  /**
   * Add a plugin to the application.
   * Fluent interface.
   *
   * @param {Plugin} plugin - The plugin to add to the application.
   * @return {Application}
   */
  addPlugin(plugin) {
    return this._register(PluginType.PLUGIN, this._plugins, plugin);
  }
 
  getPlugin(key) {
    invariant(
      this._plugins.has(key),
      `No plugin with key ${key} is registered with the application`
    );
 
    return this._plugins.get(key);
  }
 
  /**
   * Get all action types registered with the application.
   *
   * @returns {object}
   */
  getActionTypes() {
    return this._actionTypes;
  }
 
  /**
   * Add a middleware to the application.
   * Fluent interface.
   *
   * @see {@link http://redux.js.org/docs/advanced/Middleware.html} for more information.
   * @param {function} middleware - A middleware to add to the application.
   * @returns {Application}
   */
  addMiddleware(middleware) {
    this._log(`Registering middleware: ${middleware.name}`);
    this._middleware.push(middleware);
    return this;
  }
 
  /**
   * Add a store enhancer to the application.
   * Fluent interface.
   *
   * @see {@link http://redux.js.org/docs/Glossary.html#store-enhancer} for more information.
   * @param {function} enhancer - A store enhancer to add to the application.
   * @returns {Application}
   */
  addEnhancer(enhancer) {
    this._enhancers.push(enhancer);
    return this;
  }
 
  /**
   * Check if application is in debug mode.
   *
   * @returns {boolean}
   */
  isDebug() {
    return this._debug;
  }
 
  /**
   * Enable debug mode.
   * Fluent interface.
   *
   * @returns {Application}
   */
  debug() {
    this._debug = true;
    return this;
  }
 
  /**
   * Enable HTML5 history API.
   * Fluent interface.
   *
   * @see {@link https://github.com/reactjs/react-router/blob/master/docs/guides/Histories.md#browserhistory} for more information.
   * @returns {Application}
   */
  useHistoryApi() {
    this._historyApiEnabled = true;
    return this;
  }
 
  /**
   * Get all routes registered with the application.
   *
   * @returns {Array}
   */
  getRoutes() {
    return this._routes;
  }
 
  /**
   * Set the application routes.
   *
   * @see {@link https://github.com/reactjs/react-router/blob/master/docs/guides/RouteConfiguration.md}
   * @param {Object|JSX} routes - The routes for the application.
   */
  setRoutes(routes) {
    this._routes = routes;
  }
 
  /**
   * Fluent interface for {@link setRoutes}.
   *
   * @extends setRoutes
   * @returns {Application}
   */
  routes(routes) {
    this.setRoutes(routes);
    return this;
  }
 
  /**
   * Get the underlying Redux store instance.
   *
   * @see {@link http://redux.js.org/docs/api/Store.html} for more information.
   * @returns {*}
   */
  getStore() {
    return this._store;
  }
 
  /**
   * Get the routing history of the application.
   *
   * @returns {*}
   */
  getHistory() {
    return this._history;
  }
 
  /**
   * Run the application.
   *
   * @desc This will add all default middleware, initialize the store and
   * router and will render the application and subscribe to store change
   * events.
   */
  run() {
    LOG.debug('Starting Application ...');
    const historyImpl = this._selectHistory();
    this.addMiddleware(routerMiddleware(historyImpl));
    this._initStore();
    this._bootPlugins();
    this._bootModules();
    this._history = syncHistoryWithStore(historyImpl, APPLICATION_INSTANCE);
    this._render();
    this._store.subscribe(this._render);
  }
 
  // ===============================================================================================
  // Redux Store delegate methods.
 
  /**
   * Get the application state.
   *
   * @see {@link http://redux.js.org/docs/api/Store.html#getState} for more information.
   * @returns {object}
   */
  getState() {
    return APPLICATION_INSTANCE.getStore().getState();
  }
 
  /**
   * Dispatch an action.
   *
   * @see {@link http://redux.js.org/docs/api/Store.html#dispatch} for more information.
   * @param {object} action - The action to dispatch.
   * @returns {*}
   */
  dispatch(action) {
    return APPLICATION_INSTANCE.getStore().dispatch(action);
  }
 
  /**
   * Add a change listener to the Redux store.
   *
   * @see {@link http://redux.js.org/docs/api/Store.html#subscribe} for more information.
   * @param {function} listener - The change listener.
   */
  subscribe(listener) {
    APPLICATION_INSTANCE.getStore().subscribe(listener);
  }
 
  /**
   * Replace the root reducer currently used by the store.
   *
   * @see {@link http://redux.js.org/docs/api/Store.html#replaceReducer} for more information.
   * @param {function} nextReducer
   * @returns {*}
   */
  replaceReducer(nextReducer) {
    return APPLICATION_INSTANCE.getStore().replaceReducer(nextReducer);
  }
 
  // ===============================================================================================
  // Private API

  _register(type, map, instance) {
    const name = instance.getName();
    const key = instance.getKey();
 
    invariant(
      !map.has(key),
      `A ${type} with the key ${key} is already registered with the application.`
    );
 
    this._log(`Registering ${type} ${name}`);
    map.set(key, instance);
 
    this._log(`Registering action types for ${type} ${name}`);
    instance.getActionTypes().then((actionTypes) => {
      this._actionTypes = Object.assign(this._actionTypes, actionTypes);
    });
 
 
    this._log(`Registering reducer for ${type} ${name}`);
 
    this._reducers = {
      ...this._reducers, [`${type}/${key}`]: instance.getReducer(),
    };
 
    instance.register(this);
 
    return this;
  }
 
  _selectHistory() {
    return this._historyApiEnabled
      ? browserHistory
      : hashHistory;
  }
 
  _initStore() {
    this._store = createStore(
      this._getReducer(),
      this._getInitialState(),
      this._getStoreEnhancers()
    );
  }
 
  _getStoreEnhancers() {
    return compose(
      applyMiddleware(...this._middleware),
      ...this._enhancers
    );
  }
 
  _getInitialState() {
    return {
      [this._key]: {
        name: this._name,
        version: this._version,
        actionTypes: this.getActionTypes(),
        isDebug: this._debug,
      },
    };
  }
 
  _getReducer() {
    return combineReducers({
      ...this._reducers,
      [this._key]: this._appReducer,
      routing: routerReducer,
    });
  }
 
  _bootPlugins() {
    this._plugins.forEach((plugin) => {
      plugin.boot(this);
    });
  }
 
  _bootModules() {
    this._modules.forEach((module) => {
      module.boot(this);
    });
  }
 
  _log(message, ...data) {
    if (this.isDebug()) {
      if (data.length > 0) {
        LOG.debug(message, data);
      } else {
        LOG.debug(message);
      }
    }
  }
 
  _appReducer(state = {}) {
    return state;
  }
 
  _render() {
    if (APPLICATION_INSTANCE.getMount() === null) {
      const el = document.getElementById('root');
      APPLICATION_INSTANCE.setMount(el);
    }
 
    ReactDOM.render(
      <Provider store={APPLICATION_INSTANCE.getStore()}>
        <Router history={APPLICATION_INSTANCE.getHistory()}>
          {APPLICATION_INSTANCE.getRoutes()}
        </Router>
      </Provider>
      , APPLICATION_INSTANCE.getMount());
  }
}
 
export default Application;