all files / js/ screenModel.js

86.11% Statements 155/180
75% Branches 45/60
86.49% Functions 32/37
86.11% Lines 155/180
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                                                             220× 23×     220× 220×       220× 128× 128× 128× 128× 128× 128× 128× 92×       220× 220×   220× 127×   220× 215×   220× 220×     220× 220× 220× 220× 220× 220×   220× 220×               3776×                 231×       231×               118×                             1304× 74×   1304×               1528× 120×   1528×     221× 213×     213× 213×             221× 116× 58× 58× 58×       221×   6286× 6286× 4238× 10×   4228× 2048×             2048× 2048×       6276×   27× 27×   27× 12×   15×   12×     12× 12×     12×                                     1142×                 3825×               2406× 2406×                             315× 305× 145×   10× 10×         315× 315×               220× 220×   220×     220×                                   458×                 2434×               1881× 1871×                             224× 224×                 224× 224×               220× 220×   220×     220×                                                   47× 47×             47×             94×             94× 141×                 554× 224×          
define(['errors'], function(Errors) {
    "use strict";
 
    /**
     * Конфигурация модели
     * @typedef {Object} ScreenModel~ScreenConfig
     * @property {ScreenModel[]} [children] - Потомки модели
     * @property {ScreenModel[]} [parents] - Предки модели
     * @property {boolean} [isPermanent] - Является ли модель постоянно хранимой, если да, то попав на страницу не будет оттуда удаляться.
     * @property {boolean} [isDirectedGraph] - Является ли строящийся граф моделей ориентированным.
     * @property {string} [html] - Контент модели
     * @property {number} [defaultChildIndex] - Индекс модели по умолчанию среди моделей-потомков
     * @property {number} [defaultParentIndex] - Индекс модели по умолчанию среди моделей-предков
     */
    /**
     * Конфигурация моделей по умолчанию
     * @typedef {Object} ScreenModel~DefaultScreenConfig
     * @property {boolean} [isPermanent] - Является ли модель постоянно хранимой, если да, то попав на страницу не будет оттуда удаляться.
     * @property {boolean} [isDirectedGraph] - Является ли строящийся граф моделей ориентированным.
     * @property {number} [defaultChildIndex] - Индекс модели по умолчанию среди моделей-потомков
     * @property {number} [defaultParentIndex] - Индекс модели по умолчанию среди моделей-предков
     */
    /**
     * @class
     * Модель контента, отображаемая в ячейке панели.
     * @param {String|ScreenModel~ScreenConfig} [html] - контент модели
     * @param {ScreenModel[]} [children] - потомки модели
     * @param {ScreenModel[]} [parents] - предки модели
     * @constructor ScreenModel
     */
    function ScreenModel(html, children, parents) {
        if (!ScreenModel._mainScreenSetted) {
            ScreenModel._mainScreen = this;
        }
 
        this._children = [];
        this._parents = [];
 
        var isPermanent, isDirectedGraph, defaultChildIndex, defaultParentIndex;
 
        if (typeof html === 'object') {
            children = html.children;
            parents = html.parents;
            isPermanent = html.isPermanent;
            isDirectedGraph = html.isDirectedGraph;
            defaultChildIndex = html.defaultChildIndex;
            defaultParentIndex = html.defaultParentIndex;
            html = html.html;
        } else Iif (typeof html !== 'string') {
            html = '';
        }
 
        Eif (isPermanent === undefined) {
            isPermanent = ScreenModel.isPermanent;
        }
        if (isDirectedGraph === undefined) {
            isDirectedGraph = ScreenModel.isDirectedGraph;
        }
        if (defaultChildIndex === undefined) {
            defaultChildIndex = ScreenModel.defaultChildIndex;
        }
        Eif (defaultParentIndex === undefined) {
            defaultParentIndex = ScreenModel.defaultParentIndex;
        }
 
        this._id = 'screen_' + ScreenModel._length++;
        this._html = html;
        this._temporary = !isPermanent; // Todo на изменение тут менять и там где используется
        this._isDirectedGraph = !!isDirectedGraph; // Todo на изменение тут менять и там где используется
        this._defaultChildIndex = defaultChildIndex;
        this._defaultParentIndex = defaultParentIndex;
 
        this.resetChildren(children);
        this.resetParents(parents);
    }
 
    /**
     * Возвращает идентификатор модели
     * @returns {string} идентификатор модели
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.toString = function() {
        return this._id;
    };
 
    /**
     * Возвращает контент модели
     * @param {string} [html] - если аргумент задан, он будет установлен в качестве контента модели
     * @returns {string} контент модели
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.html = function (html) {
        Iif (typeof html === 'string') {
            this._html = html;
            // todo обновить все ячейки в которых лежит эта модель
        }
        return this._html;
    };
 
    /**
     * Возвращает опцию "временная модель". Если модель временная, она не будет храниться на странице, если не отображается.
     * @returns {boolean} опция "временная модель"
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.isTemporary = function() {
        return this._temporary;
    };
    /**
     * Возвращает опцию "ориентированный граф". Если true, модель является частью ориентированного графа.
     * @returns {boolean} опция "ориентированный граф"
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.isDirectedGraph = function() {
        return this._isDirectedGraph;
    };
    /**
     * Возвращает индекс модели по умолчанию среди моделей-потомков
     * @param {number} [index] - если задан индекс, он будет установлен как значение по умолчанию
     * @returns {number} индекс модели по умолчанию среди моделей-потомков
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.defaultChildIndex = function(index) {
        if (typeof index === 'number') {
            this._defaultChildIndex = index;
        }
        return this._defaultChildIndex;
    };
    /**
     * Возвращает индекс модели по умолчанию среди моделей-предков
     * @param {number} [index] - если задан индекс, он будет установлен как значение по умолчанию
     * @returns {number} индекс модели по умолчанию среди моделей-предков
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.defaultParentIndex = function(index) {
        if (typeof index === 'number') {
            this._defaultParentIndex = index;
        }
        return this._defaultParentIndex;
    };
 
    ScreenModel.prototype._addScreen = function(screen, isChild) {
        if (isChild) {
            Iif (this.getChildIndex(screen) !== -1) {
                console.log('screenModel: "' + screen.toString() + '" child screen exists!');
            } else {
                this._children.push(screen); //todo смотреть что оба скрина одного типа isDirectGraph
                screen._parents.push(this);
            }
        } else {
            Iif (this.getParentIndex(screen) !== -1) {
                console.log('screenModel: "' + screen.toString() + '" parent screen exists!');
            } else {
                this._parents.push(screen);
                screen._children.push(this);
            }
        }
        if (!this._isDirectedGraph) {
            if (!screen._isAddingState) {
                this._isAddingState = true;
                screen._addScreen(this, isChild);
                this._isAddingState = false;
            }
        }
 
        return this;
    };
    ScreenModel.prototype._getScreenIndex = function(screen, arr) {
        var index = -1;
        if (typeof screen === 'number') {
            if (isNaN(screen)) {
                throw new Errors.ArgumentError('screen', screen);
            }
            index = screen;
        } else Iif (typeof screen === 'string') {
            screen = arr.find(function(curScreen, curIndex) {
                if (curScreen.toString() === screen) {
                    index = curIndex;
                    return true;
                }
            });
        } else Eif (screen instanceof ScreenModel) {
            index = arr.indexOf(screen);
        } else {
            throw new Errors.ArgumentError('screen', screen);
        }
        return index;
    };
    ScreenModel.prototype._removeScreen = function(screen, isChild) {
        var arr = isChild ? this._children : this._parents,
            index = this._getScreenIndex(screen, arr);
 
        if (index !== -1) {
            var removed = arr.splice(index, 1)[0];
        } else {
            return;
        }
        if (isChild) {
            removed.removeParent(this);
        } else {
            removed.removeChild(this);
        }
        Eif (!this._isDirectedGraph) {
            removed._removeScreen(this, isChild);
        }
 
        return this;
    };
 
    /**
     * Сортирует набор потомков. Сортировка происходит по правилам сортировки массива.
     * @param {function} [compareFn] - Если задана функция сравнения, она будет использована при сортировке.
     * @returns {ScreenModel} текущая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.sortChildren = function(compareFn) {
        this._children = this._children.sort(compareFn);
        ScreenModel._runUpdateFn(this);
        return this;
    };
 
    /**
     * Возвращает количество потомков.
     * @returns {Number} количество потомков
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.childrenLength = function () {
        return this._children.length;
    };
 
    /**
     * Находит индекс модели среди набора потомков
     * @param {ScreenModel|string|number} child - искомая модель, ее идентификатор или порядковый номер в наборе
     * @returns {number} искомый индекс модели
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.getChildIndex = function(child) {
        return this._getScreenIndex(child, this._children);
    };
    /**
     * Находит модель среди набора потомков
     * @param {ScreenModel|string|number} child - искомая модель, ее идентификатор или порядковый номер в наборе
     * @returns {ScreenModel} искомая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.getChild = function(child) {
        var index = this.getChildIndex(child);
        return this._children[index];
    };
    /**
     * Удаляет модель из набора потомков
     * @param {ScreenModel|string|number} child - удаляемая модель, ее идентификатор или порядковый номер в наборе
     * @returns {ScreenModel} текущая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.removeChild = function(child) {
        this._removeScreen(child, true);
        ScreenModel._runUpdateFn(this);
        return this;
    };
    /**
     * Добавить набор моделей в конец к набору потомков
     * @param {ScreenModel[]|ScreenModel} children - набор добавляемый моделей
     * @returns {ScreenModel} текущая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.pushChildren = function(children) {
        if (Array.isArray(children)) {
            for (var i = 0; i < children.length; i++) {
                this._addScreen(children[i], true);
            }
        } else Eif (children instanceof ScreenModel) {
            this._addScreen(children, true);
        } else {
            ScreenModel._runUpdateFn(this);
            throw new Errors.ArgumentError('children', children);
        }
        ScreenModel._runUpdateFn(this);
        return this;
    };
    /**
     * Переопределить набор моделей потомков, то есть удалить старые и установить новые
     * @param {ScreenModel[]} [children] - набор добавляемый моделей
     * @returns {ScreenModel} текущая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.resetChildren = function(children) {
        this._clearChildren().pushChildren(children || []);
        return this;
    };
    ScreenModel.prototype._clearChildren = function() {
        for (var i = this._children.length - 1; i >= 0; i--) {
            this._removeScreen(this._children[i], true);
        }
        return this;
    };
 
    /**
     * Сортирует набор предков. Сортировка происходит по правилам сортировки массива.
     * @param {function} [compareFn] - Если задана функция сравнения, она будет использована при сортировке.
     * @returns {ScreenModel} текущая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.sortParents = function(compareFn) {
        this._parents = this._parents.sort(compareFn);
        ScreenModel._runUpdateFn(this);
        return this;
    };
    /**
     * Возвращает количество предков.
     * @returns {Number} количество предков
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.parentsLength = function () {
        return this._parents.length;
    };
 
    /**
     * Находит индекс модели среди набора предков
     * @param {ScreenModel|string|number} parent - искомая модель, ее идентификатор или порядковый номер в наборе
     * @returns {number} искомый индекс модели
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.getParentIndex = function(parent) {
        return this._getScreenIndex(parent, this._parents);
    };
    /**
     * Находит модель среди набора предков
     * @param {ScreenModel|string|number} parent - искомая модель, ее идентификатор или порядковый номер в наборе
     * @returns {ScreenModel} искомая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.getParent = function(parent) {
        var index = this.getParentIndex(parent);
        return this._parents[index];
    };
    /**
     * Удаляет модель из набора предков
     * @param {ScreenModel|string|number} parent - удаляемая модель, ее идентификатор или порядковый номер в наборе
     * @returns {ScreenModel} текущая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.removeParent = function(parent) {
        this._removeScreen(parent, false);
        ScreenModel._runUpdateFn(this);
        return this;
    };
    /**
     * Добавить набор моделей в конец к набору предков
     * @param {ScreenModel[]|ScreenModel} parents - набор добавляемый моделей
     * @returns {ScreenModel} текущая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.pushParents = function(parents) {
        Eif (Array.isArray(parents)) {
            for (var i = 0; i < parents.length; i++) {
                this._addScreen(parents[i], false);
            }
        } else if (parents instanceof ScreenModel) {
            this._addScreen(parents, false);
        } else {
            ScreenModel._runUpdateFn(this);
            throw new Errors.ArgumentError('parents', parents);
        }
 
        ScreenModel._runUpdateFn(this);
        return this;
    };
    /**
     * Переопределить набор моделей предков, то есть удалить старые и установить новые
     * @param {ScreenModel[]} [parents] - набор добавляемый моделей
     * @returns {ScreenModel} текущая модель
     * @memberOf ScreenModel
     */
    ScreenModel.prototype.resetParents = function(parents) {
        this._clearParents().pushParents(parents || []);
        return this;
    };
    ScreenModel.prototype._clearParents = function() {
        for (var i = this._parents.length - 1; i >= 0; i--) {
            this._removeScreen(this._parents[i], false);
        }
        return this;
    };
 
    /**
     * Устанавливает конфигурацию моделей по умолчанию. Изначальные значения по умоланию: <br>
     * isPermanent: false, <br>
     * isDirectedGraph: true, <br>
     * defaultChildIndex: 0, <br>
     * defaultParentIndex: 0
     * @param {ScreenModel~DefaultScreenConfig} config - конфигурация
     * @memberOf ScreenModel
     */
    ScreenModel.configure = function(config) {
        ScreenModel.isPermanent = config.isPermanent;
        ScreenModel.isDirectedGraph = config.isDirectedGraph;
        ScreenModel.defaultChildIndex = config.defaultChildIndex;
        ScreenModel.defaultParentIndex = config.defaultParentIndex;
    };
    ScreenModel.configure({
        isPermanent: false,
        isDirectedGraph: true,
        defaultChildIndex: 0,
        defaultParentIndex: 0
    });
    ScreenModel._length = 1;
    ScreenModel._relativeUpdateFn = [];
 
    /**
     * Установить модель по умолчанию, она будет использоваться в качестве стартовой для панелей, если при старте не заданы иные модели.
     * Если модель по умолчанию не установлена вручную, будет использован первый созданный экземпляр модели.
     * @param {ScreenModel} screen - модель по умолчанию
     * @memberOf ScreenModel
     * @see {@link module:RbManager.init}
     */
    ScreenModel.setMainScreen = function(screen) {
        ScreenModel._mainScreen = screen;
        ScreenModel._mainScreenSetted = true;
    };
    /**
     * Получить модель по умолчанию
     * @returns {ScreenModel} модель по умолчанию
     * @memberOf ScreenModel
     */
    ScreenModel.getMainScreen = function() {
        return ScreenModel._mainScreen;
    };
    /**
     * Зарегистрировать функцию для запуска, когда изменится структура графа
     * @param {function} fn - функция для запуска
     * @memberOf ScreenModel
     */
    ScreenModel.registerUpdateFn = function(fn) {
        ScreenModel._relativeUpdateFn.push(fn);
    };
    /**
     * Удалить функцию из списка функций для запуска, когда изменится структура графа
     * @param {function} fn - функция для запуска
     * @memberOf ScreenModel
     */
    ScreenModel.unregisterUpdateFn = function(fn) {
        ScreenModel._relativeUpdateFn = ScreenModel._relativeUpdateFn.filter(function(value) {
            return value !== fn;
        });
    };
    /**
     * Очистить набор функций для запуска, когда изменится структура графа
     * @memberOf ScreenModel
     */
    ScreenModel.clearUpdateFn = function() {
        ScreenModel._relativeUpdateFn = [];
    };
    ScreenModel._runUpdateFn = function(screen) {
        ScreenModel._relativeUpdateFn.forEach(function(fn) {
            fn.call(undefined, screen);
        });
    };
 
    return ScreenModel;
});