All files / ima/page/state PageStateManagerImpl.js

78.26% Statements 18/23
25% Branches 2/8
77.78% Functions 7/9
78.26% Lines 18/23
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      4x   4x             4x             12x         12x         12x         12x             6x 6x             1x   1x 1x 1x             3x             1x                                       5x 5x                             4x  
import ns from '../../namespace';
import PageStateManager from './PageStateManager';
 
ns.namespace('ima.page.state');
 
const MAX_HISTORY_LIMIT = 10;
 
/**
 * The implementation of the {@linkcode PageStateManager} interface.
 */
export default class PageStateManagerImpl extends PageStateManager {
  static get $dependencies() {
    return [];
  }
 
  /**
	 * Initializes the page state manager.
	 */
  constructor() {
    super();
 
    /**
		 * @type {Object<string, *>[]}
		 */
    this._states = [];
 
    /**
		 * @type {number}
		 */
    this._cursor = -1;
 
    /**
		 * @type {?function(Object<string, *>)}
		 */
    this.onChange = null;
  }
 
  /**
	 * @inheritdoc
	 */
  clear() {
    this._states = [];
    this._cursor = -1;
  }
 
  /**
	 * @inheritdoc
	 */
  setState(statePatch) {
    var newState = Object.assign({}, this.getState(), statePatch);
 
    this._eraseExcessHistory();
    this._pushToHistory(newState);
    this._callOnChangeCallback(newState);
  }
 
  /**
	 * @inheritdoc
	 */
  getState() {
    return this._states[this._cursor] || {};
  }
 
  /**
	 * @inheritdoc
	 */
  getAllStates() {
    return this._states;
  }
 
  /**
	 * Erase the oldest state from storage only if it exceed max
	 * defined size of history.
	 */
  _eraseExcessHistory() {
    if (this._states.length > MAX_HISTORY_LIMIT) {
      this._states.shift();
      this._cursor -= 1;
    }
  }
 
  /**
	 * Push new state to history storage.
	 *
	 * @param {Object<string, *>} newState
	 */
  _pushToHistory(newState) {
    this._states.push(newState);
    this._cursor += 1;
  }
 
  /**
	 * Call registered callback function on (@codelink onChange) with newState.
	 *
	 * @param {Object<string, *>} newState
	 */
  _callOnChangeCallback(newState) {
    if (this.onChange && typeof this.onChange === 'function') {
      this.onChange(newState);
    }
  }
}
 
ns.ima.page.state.PageStateManagerImpl = PageStateManagerImpl;