all files / js/ screenManager.js

91.95% Statements 137/149
82.69% Branches 86/104
94.74% Functions 18/19
91.78% Lines 134/146
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                   47× 47× 47× 47×             99× 99× 54× 54× 54×             99× 47×   99× 48×   99× 47×   99× 47×   99× 47×   99× 47×   99× 53×           672× 672× 466× 47×   466× 206× 206× 206×   206× 206×       672× 184×           184× 15×       672×     3165×     3165×       3165× 245× 2920× 639× 2281× 743× 1538× 797× 741× 741×       262×     262×       262×   262× 64× 64× 64×         262× 87× 87× 87×           112×       112× 10×   112× 33×                 1789×               1077×                         33× 33× 22× 22×   11× 11×   33×   11× 16×                       16× 16× 16×     16× 136× 136×     16×   16× 168×   152× 56×     152× 152× 152× 152×     152× 152×                       152×   152× 808× 808× 808×   808× 136× 136× 136×         16×   14×       14× 14×   14× 48× 48×     14× 14×     16× 16× 16×             47× 47× 47×      
define(['utils', 'screenModel', 'IPlugin', 'errors'], function(Utils, Screen, IPlugin, Errors) {
    "use strict";
 
    /**
     * @class
     * Класс-менеджер моделей контента
     * @constructor ScreenManager
     * @extends IPlugin
     */
    function ScreenManager() {
        this._history = [];
        this._curScreen = null;
        this._relativeUpdateFn = this._updateRelativeScreen.bind(this);
        Screen.registerUpdateFn(this._relativeUpdateFn);
    }
    Utils.inherite(ScreenManager, IPlugin);
    /**
     * Применить конфигурацию к панели. Учитывает опции maxHistoryLength, isDirectPath, cyclicStep, getLeft, getTop, getRight, getBottom.
     * @param {Moving~config} config - конфигурация
     * @memberOf ScreenManager
     */
    ScreenManager.prototype.configure = function(config) {
        Eif (typeof config === 'object') {
            if (config.maxHistoryLength !== undefined) {
                Eif (typeof config.maxHistoryLength === 'number' && config.maxHistoryLength >= 0) {
                    this._maxHistoryLength = config.maxHistoryLength;
                    Iif (this._history.length > this._maxHistoryLength) {
                        this._history = this._history.slice(this._history.length - this._maxHistoryLength);
                    }
                } else {
                    throw new Errors.ArgumentError('maxHistoryLength', config.maxHistoryLength);
                }
            }
            if (config.isDirectPath !== undefined) {
                this._isDirectPath = config.isDirectPath;
            }
            if (config.cyclicStep !== undefined) {
                this._cyclicStep = config.cyclicStep;
            }
            if (config.getLeft !== undefined) {
                this._getLeft = config.getLeft;
            }
            if (config.getRight !== undefined) {
                this._getRight = config.getRight;
            }
            if (config.getTop !== undefined) {
                this._getTop = config.getTop;
            }
            if (config.getBottom !== undefined) {
                this._getBottom = config.getBottom;
            }
            if (config.savePrevious !== undefined) {
                this._savePrevious = config.savePrevious;
            }
 
        }
    };
 
    ScreenManager.prototype._updateScreens = function(side, screen, isSaveHistory) {
        var updated = false;
        if (screen) {
            if (this._curScreen !== screen) {
                updated = true;
            }
            this._curScreen = screen;
        } else Eif (this.getRelativeScreen(side)) {
            var prevScreen = this._curScreen;
            this._curScreen = this.getRelativeScreen(side);
 
            Eif (side !== 'center') {
                updated = true;
            }
        }
 
        if (updated && isSaveHistory !== false) {
            this._history.push({
                screen: prevScreen,
                side: Utils.oppositeSide(side),
                lastSide: this._lastSide,
                lastScreen: this._lastScreen
            });
            if (this._history.length > this._maxHistoryLength) {
                this._history.shift();
            }
        }
 
        return this._curScreen;
    };
 
    ScreenManager.prototype._getRelativeScreenByScreen = function(screen, side) {
        Iif (!(screen instanceof Screen)) {
            throw new Errors.ArgumentError('screen', screen);
        }
        Iif (Utils.sidesWithCenter.indexOf(side) === -1) {
            throw new Errors.ArgumentError('side', side);
        }
 
        if (side === 'center') {
            return screen;
        } else if (side === 'left') {
            return this._getLeft(screen);
        } else if (side === 'top') {
            return this._getTop(screen, this._cyclicStep);
        } else if (side === 'right') {
            return this._getRight(screen);
        } else Eif (side === 'bottom') {
            return this._getBottom(screen, this._cyclicStep);
        }
        return null;
    };
    ScreenManager.prototype._setRelativeScreen = function(side, baseScreen, targetScreen, isCheckSave, reverse) {
        Iif (!(targetScreen instanceof Screen)) {
            throw new Errors.ArgumentError('targetScreen', targetScreen);
        }
        Iif (!(baseScreen instanceof Screen)) {
            throw new Errors.ArgumentError('baseScreen', baseScreen);
        }
 
        var savePrevious = isCheckSave ? this._savePrevious : true;
 
        if (side === (reverse ? 'left' : 'right') && savePrevious) {
            var childIndex = baseScreen.getChildIndex(targetScreen);
            Eif (childIndex !== -1) {
                baseScreen.defaultChildIndex(childIndex);
            } else {
                throw new Errors.FatalError('Base screen is ' + baseScreen.toString() + '. Child screen not found: ', targetScreen.toString());
            }
        }
        if (side === (reverse ? 'right' : 'left') && savePrevious) {
            var parentIndex = baseScreen.getParentIndex(targetScreen);
            Eif (parentIndex !== -1) {
                baseScreen.defaultParentIndex(parentIndex);
            } else {
                throw new Errors.FatalError('Base screen is ' + baseScreen.toString() + '. Parent screen not found: ', targetScreen.toString());
            }
        }
    };
    ScreenManager.prototype._updateRelativeScreen = function(screen) {
        Iif (!(screen instanceof Screen)) {
            throw new Errors.ArgumentError('screen', screen);
        }
 
        if (!this._getRight(screen)) {
            screen.defaultChildIndex(0);
        }
        if (!this._getLeft(screen)) {
            screen.defaultParentIndex(0);
        }
    };
 
    /**
     * Возвращает модель текущей ячейки панели.
     * @returns {ScreenModel|null} модель текущей ячейки панели
     * @memberOf ScreenManager
     */
    ScreenManager.prototype.getCurScreen = function() {
        return this._curScreen;
    };
    /**
     * Возвращает модель, располагающуюся рядом с текущей ячейкой панели.
     * @param {string} side - сторона относительно текущей ячейки
     * @returns {ScreenModel|null} модель текущей ячейки панели
     * @memberOf ScreenManager
     */
    ScreenManager.prototype.getRelativeScreen = function(side) {
        return this._getRelativeScreenByScreen(this._curScreen, side);
    };
    /**
     * Очистить историю перемещений в панели.
     * @memberOf ScreenManager
     */
    ScreenManager.prototype.clearHistory = function() {
        this._history = [];
    };
    /**
     * Удаляет из истории перемещений последнее удачное перемещение в панели и возвращает модель, которая располагается в последней посещенной ячейке из истории.
     * @returns {ScreenModel} Модель из последнего удачного перемещения в истории
     * @memberOf ScreenManager
     */
    ScreenManager.prototype.popHistory = function() {
        var res = this._history.pop();
        if (res) {
            this._lastSide = res.lastSide;
            this._lastScreen = res.lastScreen;
        } else {
            this._lastSide = null;
            this._lastScreen = null;
        }
        return res;
    };
    ScreenManager.prototype._containsHistory = function(screen) {
        return this._history.some(function(val) {
            return val.screen === screen;
        });
    };
 
    /**
     * Поиск кратчайшего пути от одной модели до другой. Если для разных ячеек панели используются одинаковые модели, результат непредсказуем.
     * @param {ScreenModel} start - Модель, от которой начинает поиск пути
     * @param {ScreenModel} end - Конечная модель, в которую ищется путь
     * @returns {null|ScreenModel[]} Путь от начальной модели до конечной модели в панели
     * @memberOf ScreenManager
     */
    ScreenManager.prototype.findShortestPath = function (start, end) {
        function findPaths(start, end) {
            var costs = {},
                open = {'0': [start]},
                predecessors = {},
                keys;
 
            var addToOpen = function (cost, vertex) {
                if (!open[cost]) open[cost] = [];
                open[cost].push(vertex);
            };
 
            costs[start] = 0;
 
            while (open) {
                if(!(keys = Object.keys(open)).length) break;
 
                keys.sort(function (a, b) {
                    return a - b;
                });
 
                var key = keys[0],
                    bucket = open[key],
                    node = bucket.shift(),
                    currentCost = +key,
                    adjacentNodes;
 
                Eif (self._isDirectPath) {
                    adjacentNodes = node && node._children
                            .concat(node._parents)// todo если оставить только children будет настоящий поиск в графе
                            .concat(self._getRelativeScreenByScreen(node, 'top'))
                            .concat(self._getRelativeScreenByScreen(node, 'bottom')) || [];
                } else {
                    adjacentNodes = node && [self._getRelativeScreenByScreen(node, 'left'),
                            self._getRelativeScreenByScreen(node, 'top'),
                            self._getRelativeScreenByScreen(node, 'right'),
                            self._getRelativeScreenByScreen(node, 'bottom')
                        ] || [];
                }
 
                if (!bucket.length) delete open[key];
 
                for (var i = 0; i < adjacentNodes.length; i++) {
                    var vertex = adjacentNodes[i],
                        totalCost = currentCost + 1,
                        vertexCost = costs[vertex];
 
                    if ((vertexCost === undefined) || (vertexCost > totalCost)) {
                        costs[vertex] = totalCost;
                        addToOpen(totalCost, vertex);
                        predecessors[vertex] = node;
                    }
                }
            }
 
            if (costs[end] === undefined) {
                return null;
            } else {
                return predecessors;
            }
        }
        function extractShortest(predecessors, end) {
            var nodes = [],
                u = end;
 
            while (u) {
                nodes.push(u);
                u = predecessors[u];
            }
 
            nodes.reverse();
            return nodes;
        }
 
        var self = this;
        var predecessors = findPaths(start, end);
        return !predecessors ? null : extractShortest(predecessors, end);
    };
 
    /**
     * Уничтожить ScreenManager
     * @memberOf ScreenManager
     */
    ScreenManager.prototype.destroy = function() {
        Screen.unregisterUpdateFn(this._relativeUpdateFn);
        this._history = null;
        this._curScreen = null;
    };
 
    return ScreenManager;
});