<commit_before>/**
 *  \details © 2011  Open Ximdex Evolution SL [http://www.ximdex.org]
 *
 *  Ximdex a Semantic Content Management System (CMS)
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published
 *  by the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  See the Affero GNU General Public License for more details.
 *  You should have received a copy of the Affero GNU General Public License
 *  version 3 along with Ximdex (see LICENSE file).
 *
 *  If not, visit http://gnu.org/licenses/agpl-3.0.html.
 *
 *  @author Ximdex DevTeam <dev@ximdex.com>
 *  @version $Revision$
 */
angular.module('ximdex.common.directive')
    .directive('ximButton', ['$window', function ($window) {
        return {
            replace: true,
            scope: {
                state: '=ximState',
                disabled: '=ximDisabled',
                label: '=ximLabel',
                progress: '=ximProgress'
            },
            restrict: 'A',
            template: '<button type="button" class="button ladda-button" data-style="slide-up" data-size="xs" ng-disabled="flagDisabled">'+
                    '#/label/#'+
                '</button>',
            link: function postLink(scope, element, attrs) {
                var loader = $window.Ladda.create(element[0]);
                scope.$watch('state', function(newState, oldState){
                    switch (newState) {
                        case 'submitting':
                        case 'pending':
                            loader.start();
                            break;
                        case 'resolved':
                        case 'success':
                        case 'error':
                            loader.stop();
                            break;
                    }
                });
                scope.$watch('progress', function(newValue, oldValue){
                    if (oldValue != newValue)
                        loader.setProgress(newValue)
                });
                //Not really needed just a hack to fix angular not properly binding disabled property (Angular)
                scope.$watch('disabled', function(newValue, oldValue){
                    scope.flagDisabled = !scope.flagDisabled;
                });
            }
        }
    }]);<commit_msg>Minor bugfix<commit_after>/**
 *  \details © 2011  Open Ximdex Evolution SL [http://www.ximdex.org]
 *
 *  Ximdex a Semantic Content Management System (CMS)
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published
 *  by the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  See the Affero GNU General Public License for more details.
 *  You should have received a copy of the Affero GNU General Public License
 *  version 3 along with Ximdex (see LICENSE file).
 *
 *  If not, visit http://gnu.org/licenses/agpl-3.0.html.
 *
 *  @author Ximdex DevTeam <dev@ximdex.com>
 *  @version $Revision$
 */
angular.module('ximdex.common.directive')
    .directive('ximButton', ['$window', function ($window) {
        return {
            replace: true,
            scope: {
                state: '=ximState',
                disabled: '=ximDisabled',
                label: '=ximLabel',
                progress: '=ximProgress'
            },
            restrict: 'A',
            template: '<button type="button" class="button ladda-button" data-style="slide-up" data-size="xs" ng-disabled="flagDisabled">'+
                    '#/label/#'+
                '</button>',
            link: function postLink(scope, element, attrs) {
                var loader = $window.Ladda.create(element[0]);
                scope.$watch('state', function(newState, oldState){
                    switch (newState) {
                        case 'submitting':
                        case 'pending':
                            loader.start();
                            break;
                        case 'resolved':
                        case 'success':
                        case 'error':
                            loader.stop();
                            break;
                    }
                });
                scope.$watch('progress', function(newValue, oldValue){
                    if (oldValue != newValue)
                        loader.setProgress(newValue)
                });
                //Not really needed just a hack to fix angular not properly binding disabled property (Angular)
                scope.flagDisabled = false;
                scope.$watch('disabled', function(newValue, oldValue){
                    scope.flagDisabled = newValue;
                });
            }
        }
    }]);<|endoftext|>


<commit_before>/* jslint maxlen:80, es6:true, white:true */

/* jshint bitwise:true, camelcase:true, curly:true, eqeqeq:true, forin:true,
   freeze:true, futurehostile:true, latedef:true, newcap:true, nocomma:true,
   nonbsp:true, singleGroups:true, strict:true, undef:true, unused:true,
   es3:true, esnext:true, plusplus:true, maxparams:1, maxdepth:2,
   maxstatements:11, maxcomplexity:3 */

/* eslint strict: 1, max-lines: 1, symbol-description: 1, max-nested-callbacks: 1,
   max-statements: 1 */

/* global JSON:true, expect, module, jasmine, require, describe, xit, it,
returnExports */

;(function () { // eslint-disable-line no-extra-semi

  'use strict';

  var hasSymbolSupport = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
  var ifSymbolSupportIt = hasSymbolSupport ? it : xit;
  var assertIsCallable;
  if (typeof module === 'object' && module.exports) {
    require('es5-shim');
    require('es5-shim/es5-sham');
    if (typeof JSON === 'undefined') {
      JSON = {};
    }
    require('json3').runInContext(null, JSON);
    require('es6-shim');
    assertIsCallable = require('../../index.js');
  } else {
    assertIsCallable = returnExports;
  }

  describe('assertIsCallable', function () {
    it('primitives should throw a TypeError', function () {
      var block = function (value) {
        try {
          assertIsCallable(value);
          return false;
        } catch (e) {
          expect(e).toEqual(jasmine.any(TypeError));
          expect(e.message).toBe(String(value) + ' is not callable');
        }
        return true;
      };
      var values = [undefined, null, 1, true, ''];
      var expected = values.map(function () {
        return true;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });

    it('objects should throw a TypeError', function () {
      var block = function (value) {
        try {
          assertIsCallable(value);
          return false;
        } catch (e) {
          expect(e).toEqual(jasmine.any(TypeError));
          expect(e.message).toBe('#<Object> is not callable');
        }
        return true;
      };
      var values = [[], {}, /r/, new Date()];
      var expected = values.map(function () {
        return true;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });

    ifSymbolSupportIt('Symbol literals should throw a TypeError', function () {
      var block = function (value) {
        try {
          assertIsCallable(value);
          return false;
        } catch (e) {
          expect(e).toEqual(jasmine.any(TypeError));
          expect(e.message).toBe('Symbol(mySymbol) is not callable');
        }
        return true;
      };
      var values = [Symbol('mySymbol')];
      var expected = values.map(function () {
        return true;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });

    ifSymbolSupportIt('Symbol objects should throw a TypeError', function () {
      var block = function (value) {
        try {
          assertIsCallable(value);
          return false;
        } catch (e) {
          expect(e).toEqual(jasmine.any(TypeError));
          expect(e.message).toBe('#<Object> is not callable');
        }
        return true;
      };
      var values = [Object(Symbol('mySymbol'))];
      var expected = values.map(function () {
        return true;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });

    it('should return the function', function () {
      var block = function (value) {
        try {
          return assertIsCallable(value);
        } catch (ignore) {}
        return false;
      };
      var values = [function () {}, Array, block, assertIsCallable];
      var expected = values.map(function (x) {
        return x;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });
  });
}());
<commit_msg>Added es7-shim<commit_after>/* jslint maxlen:80, es6:true, white:true */

/* jshint bitwise:true, camelcase:true, curly:true, eqeqeq:true, forin:true,
   freeze:true, futurehostile:true, latedef:true, newcap:true, nocomma:true,
   nonbsp:true, singleGroups:true, strict:true, undef:true, unused:true,
   es3:true, esnext:true, plusplus:true, maxparams:1, maxdepth:2,
   maxstatements:11, maxcomplexity:3 */

/* eslint strict: 1, max-lines: 1, symbol-description: 1, max-nested-callbacks: 1,
   max-statements: 1 */

/* global JSON:true, expect, module, jasmine, require, describe, xit, it,
returnExports */

;(function () { // eslint-disable-line no-extra-semi

  'use strict';

  var hasSymbolSupport = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
  var ifSymbolSupportIt = hasSymbolSupport ? it : xit;
  var assertIsCallable;
  if (typeof module === 'object' && module.exports) {
    require('es5-shim');
    require('es5-shim/es5-sham');
    if (typeof JSON === 'undefined') {
      JSON = {};
    }
    require('json3').runInContext(null, JSON);
    require('es6-shim');
    var es7 = require('es7-shim');
    Object.keys(es7).forEach(function (key) {
      var obj = es7[key];
      if (typeof obj.shim === 'function') {
        obj.shim();
      }
    });
    assertIsCallable = require('../../index.js');
  } else {
    assertIsCallable = returnExports;
  }

  describe('assertIsCallable', function () {
    it('primitives should throw a TypeError', function () {
      var block = function (value) {
        try {
          assertIsCallable(value);
          return false;
        } catch (e) {
          expect(e).toEqual(jasmine.any(TypeError));
          expect(e.message).toBe(String(value) + ' is not callable');
        }
        return true;
      };
      var values = [undefined, null, 1, true, ''];
      var expected = values.map(function () {
        return true;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });

    it('objects should throw a TypeError', function () {
      var block = function (value) {
        try {
          assertIsCallable(value);
          return false;
        } catch (e) {
          expect(e).toEqual(jasmine.any(TypeError));
          expect(e.message).toBe('#<Object> is not callable');
        }
        return true;
      };
      var values = [[], {}, /r/, new Date()];
      var expected = values.map(function () {
        return true;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });

    ifSymbolSupportIt('Symbol literals should throw a TypeError', function () {
      var block = function (value) {
        try {
          assertIsCallable(value);
          return false;
        } catch (e) {
          expect(e).toEqual(jasmine.any(TypeError));
          expect(e.message).toBe('Symbol(mySymbol) is not callable');
        }
        return true;
      };
      var values = [Symbol('mySymbol')];
      var expected = values.map(function () {
        return true;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });

    ifSymbolSupportIt('Symbol objects should throw a TypeError', function () {
      var block = function (value) {
        try {
          assertIsCallable(value);
          return false;
        } catch (e) {
          expect(e).toEqual(jasmine.any(TypeError));
          expect(e.message).toBe('#<Object> is not callable');
        }
        return true;
      };
      var values = [Object(Symbol('mySymbol'))];
      var expected = values.map(function () {
        return true;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });

    it('should return the function', function () {
      var block = function (value) {
        try {
          return assertIsCallable(value);
        } catch (ignore) {}
        return false;
      };
      var values = [function () {}, Array, block, assertIsCallable];
      var expected = values.map(function (x) {
        return x;
      });
      var actual = values.map(block);
      expect(actual).toEqual(expected);
    });
  });
}());
<|endoftext|>


<commit_before>/**
 *
 *  CS3283/4 storage.js
 *  This class acts as a facade for other developers to access to the database.
 *  The implementation is a non-SQL local storage to support the WebApp.
 *
 */

import constants from './constants';

import entitiesCreator from './create/entitiesCreator';

import query from './retrieve/query';

import dataModifier from './data-modifier/dataModifier';

import exceptions from './exceptions';

// dummy function to initialize createTables promises
function initCreateTable() {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      resolve(true);
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createUserTable(isUserTableFirstInitialize) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      if (!isUserTableFirstInitialize) {
        entitiesCreator.createUserTable()
        .then(success => resolve(true))
        .catch(sqlError => reject(sqlError));
      } else {
        resolve('false');
      }
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createOrganizationTable(isOrganizationTableFirstInitialize) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      if (!isOrganizationTableFirstInitialize) {
        entitiesCreator.createOrganizationTable()
        .then(success => resolve(true))
        .catch(sqlError => reject(sqlError));
      } else {
        resolve('false');
      }
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createFolderTable(isFolderTableFirstInitialize) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      if (!isFolderTableFirstInitialize) {
        entitiesCreator.createFolderTable()
        .then(success => resolve(true))
        .catch(sqlError => reject(sqlError));
      } else {
        resolve('false');
      }
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createFileManagerTable(isFileTableFirstInitialize) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      if (!isFileTableFirstInitialize) {
        entitiesCreator.createFileManagerTable()
        .then(success => resolve(true))
        .catch(sqlError => reject(sqlError));
      } else {
        resolve('false');
      }
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function creationOfTables() {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      initCreateTable()
      .then(() =>
        query.isTableExistsInDatabase(constants.ENTITIES_USER)
        .then(isUserTableFirstInitialize =>
          createUserTable(isUserTableFirstInitialize)
          .catch(sqlError => reject(sqlError))
          )
        .catch(sqlError => reject(sqlError))
      )
      .then(isSuccess => query.isTableExistsInDatabase(constants.ENTITIES_ORGANIZATION)
        .then(isOrganizationTableFirstInitialize =>
          createOrganizationTable(isOrganizationTableFirstInitialize))
          .catch(sqlError => reject(sqlError))
        .catch(sqlError => reject(sqlError))
      )
      .then(() => query.isTableExistsInDatabase(constants.ENTITIES_FOLDER)
        .then(isFolderTableFirstInitialize =>
          createFolderTable(isFolderTableFirstInitialize))
          .catch(sqlError => reject(sqlError))
        .catch(sqlError => reject(sqlError))
      )
      .then(() => query.isTableExistsInDatabase(constants.ENTITIES_FILE_MANAGER)
        .then(isFileTableFirstInitialize =>
          createFileManagerTable(isFileTableFirstInitialize)
          .then(success => resolve(success))
        .catch(sqlError => reject(sqlError))
      ));
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

export default class storage {
  static constructor() {}

  static initializeDatabase() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
      entitiesCreator.initializeDatabase()
      .then(step1 => creationOfTables()
          .then((isFirstInstance) => {
            if (typeof isFirstInstance === 'boolean') {
              return entitiesCreator.fillUpDefaultData()
              .then(isFilledUp => resolve(isFilledUp))
              .catch(sqlErr => reject(sqlErr));
            } else {
              return resolve(true);
            }
          })
      )
      .catch(sqlError => reject(sqlError)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  // Searching the filename and foldername ONLY
  static partialSearch(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        query.searchString(searchString)
        .then(returnedArr => resolve(returnedArr))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static getList(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        query.loadFolder(folderId)
        .then(returnedArr => resolve(returnedArr))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static loadFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        query.loadFile(fileId)
        .then(returnedArr => resolve(returnedArr))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static saveFile(fileId, fileString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.saveFile(fileId, fileString)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createFile(organizationId, filePath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.createNewFile(organizationId, filePath, folderId)
        .then(data => resolve(data))
        .catch(err => reject(err))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static deleteFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.deleteFile(fileId)
          .then(data => resolve(true))
          .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createFolder(organizationId, folderPath, currentFolderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.createNewFolder(organizationId, folderPath, currentFolderId)
        .then(data => resolve(data))
        .catch(err => reject(err))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  // only delete folder for now without cascade delete
  static deleteFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.deleteFolder(folderId)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static deleteAll() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.deleteAllEntities()
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<commit_msg>Update promise implementation in storage.js<commit_after>/**
 *
 *  CS3283/4 storage.js
 *  This class acts as a facade for other developers to access to the database.
 *  The implementation is a non-SQL local storage to support the WebApp.
 *
 */

import constants from './constants';

import entitiesCreator from './create/entitiesCreator';

import query from './retrieve/query';

import dataModifier from './data-modifier/dataModifier';

import exceptions from './exceptions';

// dummy function to initialize createTables promises
function initCreateTable() {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      resolve(true);
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createUserTable(isUserTableFirstInitialize) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      if (!isUserTableFirstInitialize) {
        entitiesCreator.createUserTable()
        .then(success => resolve(true))
        .catch(sqlError => reject(sqlError));
      } else {
        resolve('false');
      }
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createOrganizationTable(isOrganizationTableFirstInitialize) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      if (!isOrganizationTableFirstInitialize) {
        entitiesCreator.createOrganizationTable()
        .then(success => resolve(true))
        .catch(sqlError => reject(sqlError));
      } else {
        resolve('false');
      }
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createFolderTable(isFolderTableFirstInitialize) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      if (!isFolderTableFirstInitialize) {
        entitiesCreator.createFolderTable()
        .then(success => resolve(true))
        .catch(sqlError => reject(sqlError));
      } else {
        resolve('false');
      }
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createFileManagerTable(isFileTableFirstInitialize) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      if (!isFileTableFirstInitialize) {
        entitiesCreator.createFileManagerTable()
        .then(success => resolve(true))
        .catch(sqlError => reject(sqlError));
      } else {
        resolve('false');
      }
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function creationOfTables() {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      initCreateTable()
      .then(() =>
        query.isTableExistsInDatabase(constants.ENTITIES_USER)
        .then(isUserTableFirstInitialize =>
          createUserTable(isUserTableFirstInitialize)
          .then(isSuccess => isSuccess)
          .catch(sqlError => reject(sqlError))
          )
        .catch(sqlError => reject(sqlError))
      )
      .then(() =>
        query.isTableExistsInDatabase(constants.ENTITIES_ORGANIZATION)
        .then(isOrganizationTableFirstInitialize =>
          createOrganizationTable(isOrganizationTableFirstInitialize))
          .then(isSuccess => isSuccess)
          .catch(sqlError => reject(sqlError))
        .catch(sqlError => reject(sqlError))
      )
      .then(() => query.isTableExistsInDatabase(constants.ENTITIES_FOLDER)
        .then(isFolderTableFirstInitialize =>
          createFolderTable(isFolderTableFirstInitialize))
          .then(isSuccess => isSuccess)
          .catch(sqlError => reject(sqlError))
        .catch(sqlError => reject(sqlError))
      )
      .then(() => query.isTableExistsInDatabase(constants.ENTITIES_FILE_MANAGER)
        .then(isFileTableFirstInitialize =>
          createFileManagerTable(isFileTableFirstInitialize)
          .then(isSuccess => isSuccess)
          .catch(sqlError => reject(sqlError)))
        .catch(sqlError => reject(sqlError))
      .then(isSuccess => resolve(isSuccess))
      .catch(sqlError => reject(sqlError))
      );
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

export default class storage {
  static constructor() {}

  static initializeDatabase() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        entitiesCreator.initializeDatabase()
        .then(step1 => creationOfTables()
          .then(isFirstInstance => isFirstInstance)
          .catch(sqlErr => reject(sqlErr)))
        .then((isFirstInstance) => {
          if (typeof isFirstInstance === 'boolean') {
            return entitiesCreator.fillUpDefaultData()
            .then(isFilledUp => resolve(isFilledUp))
            .catch(sqlErr => reject(sqlErr));
          } else {
            return resolve(true);
          }
        })
        .catch(sqlError => reject(sqlError));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  // Searching the filename and foldername ONLY
  static partialSearch(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        query.searchString(searchString)
        .then(returnedArr => resolve(returnedArr))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static getList(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        query.loadFolder(folderId)
        .then(returnedArr => resolve(returnedArr))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static loadFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        query.loadFile(fileId)
        .then(returnedArr => resolve(returnedArr))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static saveFile(fileId, fileString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.saveFile(fileId, fileString)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createFile(organizationId, filePath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.createNewFile(organizationId, filePath, folderId)
        .then(data => resolve(data))
        .catch(err => reject(err))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static deleteFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.deleteFile(fileId)
          .then(data => resolve(true))
          .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createFolder(organizationId, folderPath, currentFolderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.createNewFolder(organizationId, folderPath, currentFolderId)
        .then(data => resolve(data))
        .catch(err => reject(err))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  // only delete folder for now without cascade delete
  static deleteFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.deleteFolder(folderId)
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static deleteAll() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        dataModifier.deleteAllEntities()
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var nock    = require('../.')
  , nockBack= nock.back
  , tap     = require('tap')
  , http    = require('http')
  , fs      = require('fs')
  , exists  = fs.existsSync
  , _       = require('lodash');

nock.enableNetConnect();

var originalMode = nockBack.currentMode;

function testNock (t) {
  var dataCalled = false;

  var scope = nock('http://www.google.com')
    .get('/')
    .reply(200, "Hello World!");

  var req = http.request({
      host: "www.google.com"
    , path: '/'
    , port: 80
    }, function(res) {

      t.equal(res.statusCode, 200);
      res.once('end', function() {
          t.ok(dataCalled);
          scope.done();
          t.end();
        });
      res.on('data', function(data) {
          dataCalled = true;
          t.ok(data instanceof Buffer, "data should be buffer");
          t.equal(data.toString(), "Hello World!", "response should match");
        });
    });

  req.end();
}

function nockBackWithFixture (t, scopesLoaded) {
  var scopesLength = scopesLoaded ? 1 : 0;

  nockBack('goodRequest.json', function (done) {
    t.true(this.scopes.length === scopesLength);
    http.get('http://www.google.com').end();
    this.assertScopesFinished();
    done();
    t.end();
  });
}

function setOriginalModeOnEnd(t, nockBack) {
  t.once('end', function() {
    nockBack.setMode(originalMode);
  });
}

tap.test('nockBack throws an exception when fixtures is not set', function (t) {

  try {
    nockBack();
  } catch (e) {
    t.ok(true, 'excpected exception');
    t.end();
    return;
  }

  t.fail(true, false, 'test should have ended');

});

tap.test('nockBack throws an exception when fixtureName is not a string', function (t) {

  nockBack.fixtures = __dirname + '/fixtures';

  try {
    nockBack();
  } catch (e) {
    t.ok(true, 'excpected exception');
    t.equal(e.message, 'Parameter fixtureName must be a string');
    t.end();
    return;
  }

  t.fail(true, false, 'test should have ended');

});

tap.test('nockBack returns a promise when neither options nor nockbackFn are specified', function (t) {

  nockBack.fixtures = __dirname + '/fixtures';

  var promise = nockBack('test-promise-fixture.json');
  t.ok(promise);
  promise.then((params) => {
    var nockDone = params.nockDone;
    var context = params.context;
    t.assert(_.isFunction(nockDone));
    t.assert(_.isObject(context));
    t.end();
  });

});

tap.test('nockBack returns a promise when nockbackFn is not specified', function (t) {

  nockBack.fixtures = __dirname + '/fixtures';

  var promise = nockBack('test-promise-fixture.json', {test: 'options'});
  t.ok(promise);
  promise.then((params) => {
    var nockDone = params.nockDone;
    var context = params.context;
    t.assert(_.isFunction(nockDone));
    t.assert(_.isObject(context));
    t.end();
  });

});

tap.test('nockBack wild tests', function (nw) {

  //  Manually disable net connectivity to confirm that dryrun enables it.
  nock.disableNetConnect();

  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('wild');

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('nock back doesn\'t do anything', {skip: process.env.AIRPLANE}, function (t) {
    nockBackWithFixture(t, false);
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});

tap.test('nockBack dryrun tests', function (nw) {

  //  Manually disable net connectivity to confirm that dryrun enables it.
  nock.disableNetConnect();

  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('dryrun');

  nw.test('goes to internet even when no nockBacks are running', {skip: process.env.AIRPLANE}, function(t) {
    var req = http.request({
        host: "www.amazon.com"
      , path: '/'
      , port: 80
      }, function(res) {

        res.on('data', function() {
          //node v 0.10 requires this listener
        });
        t.ok([200, 301, 302].indexOf(res.statusCode) >= 0);
        t.end();

      });

    req.on('error', function(err) {

      //  This should never happen.
      t.assert(false);
      t.end();

    });

    req.end();
  });

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('uses recorded fixtures', function (t) {
    nockBackWithFixture(t, true);
  });

  nw.test('goes to internet, doesn\'t record new fixtures', {skip: process.env.AIRPLANE}, function (t) {
    var dataCalled = false;

    var fixture = 'someDryrunFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      var req = http.request({
          host: "amazon.com"
        , path: '/'
        , port: 80
        }, function(res) {

          t.ok([200, 301, 302].indexOf(res.statusCode) >= 0);
          res.on('end', function() {
            t.ok(dataCalled);
            t.false(exists(fixtureLoc));
            t.end();
          });

          res.on('data', function(data) {
            dataCalled = true;
          });

        });

      req.once('error', function(err) {
        if (err.code !== 'ECONNREFUSED') {
          throw err;
        }
        t.end();
      });

      req.end();
    });
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});

tap.test('nockBack record tests', function (nw) {
  nockBack.setMode('record');

  nw.test('it records when configured correctly', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };

    var fixture = 'someFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      fs.unlinkSync(fixtureLoc);
      t.end();
    });

  });

  //Adding this test because there was an issue when not calling
  //nock.activate() after calling nock.restore()
  nw.test('it can record twice', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };
    var fixture = 'someFixture2.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;
    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      fs.unlinkSync(fixtureLoc);
      t.end();
    });

  });

  nw.test('it shouldn\'t allow outside calls', function (t) {

    var fixture = 'wrongUri.json';

    nockBack(fixture, function (done) {

      http.get('http://www.amazon.com', function(res) {
        throw "should not request this";
      }).on('error', function(err) {
        t.equal(err.message, 'Nock: Not allow net connect for "www.amazon.com:80/"');
        done();
        t.end();
      });

    });

  });

  nw.test('it loads your recorded tests', function (t) {

    nockBack('goodRequest.json', function (done) {
      t.true(this.scopes.length > 0);
      http.get('http://www.google.com').end();
      this.assertScopesFinished();
      done();
      t.end();
    });

  });

  nw.test('it can filter after recording', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };

    var fixture = 'filteredFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    var afterRecord = function(scopes) {
       // You would do some filtering here, but for this test we'll just return an empty array
      return [];
    }

    nockBack(fixture, {afterRecord: afterRecord}, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      nockBack(fixture, function (done) {
        t.true(this.scopes.length === 0);
        done();

        fs.unlinkSync(fixtureLoc);
        t.end();
      });
    });
  });

  nw.end();

  setOriginalModeOnEnd(nw, nockBack);
});

tap.test('nockBack lockdown tests', function (nw) {
  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('lockdown');

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('nock back loads scope', function (t) {
    nockBackWithFixture(t, true);
  });

  nw.test('no unnocked http calls work', function (t) {
    var req = http.request({
        host: "google.com"
      , path: '/'
      }, function(res) {
        throw new Error('should not come here!');
      });

    req.on('error', function (err) {
      t.equal(err.message.trim(), 'Nock: Not allow net connect for "google.com:80/"');
      t.end();
    });

    req.end();
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});
<commit_msg>test: remove airplane dependency for 'tests/test_back#L154'<commit_after>'use strict';

var nock    = require('../.')
  , nockBack= nock.back
  , tap     = require('tap')
  , http    = require('http')
  , fs      = require('fs')
  , exists  = fs.existsSync
  , _       = require('lodash');

nock.enableNetConnect();

var originalMode = nockBack.currentMode;

function testNock (t) {
  var dataCalled = false;

  var scope = nock('http://www.google.com')
    .get('/')
    .reply(200, "Hello World!");

  var req = http.request({
      host: "www.google.com"
    , path: '/'
    , port: 80
    }, function(res) {

      t.equal(res.statusCode, 200);
      res.once('end', function() {
          t.ok(dataCalled);
          scope.done();
          t.end();
        });
      res.on('data', function(data) {
          dataCalled = true;
          t.ok(data instanceof Buffer, "data should be buffer");
          t.equal(data.toString(), "Hello World!", "response should match");
        });
    });

  req.end();
}

function nockBackWithFixture (t, scopesLoaded) {
  var scopesLength = scopesLoaded ? 1 : 0;

  nockBack('goodRequest.json', function (done) {
    t.true(this.scopes.length === scopesLength);
    http.get('http://www.google.com').end();
    this.assertScopesFinished();
    done();
    t.end();
  });
}

function setOriginalModeOnEnd(t, nockBack) {
  t.once('end', function() {
    nockBack.setMode(originalMode);
  });
}

tap.test('nockBack throws an exception when fixtures is not set', function (t) {

  try {
    nockBack();
  } catch (e) {
    t.ok(true, 'excpected exception');
    t.end();
    return;
  }

  t.fail(true, false, 'test should have ended');

});

tap.test('nockBack throws an exception when fixtureName is not a string', function (t) {

  nockBack.fixtures = __dirname + '/fixtures';

  try {
    nockBack();
  } catch (e) {
    t.ok(true, 'excpected exception');
    t.equal(e.message, 'Parameter fixtureName must be a string');
    t.end();
    return;
  }

  t.fail(true, false, 'test should have ended');

});

tap.test('nockBack returns a promise when neither options nor nockbackFn are specified', function (t) {

  nockBack.fixtures = __dirname + '/fixtures';

  var promise = nockBack('test-promise-fixture.json');
  t.ok(promise);
  promise.then((params) => {
    var nockDone = params.nockDone;
    var context = params.context;
    t.assert(_.isFunction(nockDone));
    t.assert(_.isObject(context));
    t.end();
  });

});

tap.test('nockBack returns a promise when nockbackFn is not specified', function (t) {

  nockBack.fixtures = __dirname + '/fixtures';

  var promise = nockBack('test-promise-fixture.json', {test: 'options'});
  t.ok(promise);
  promise.then((params) => {
    var nockDone = params.nockDone;
    var context = params.context;
    t.assert(_.isFunction(nockDone));
    t.assert(_.isObject(context));
    t.end();
  });

});

tap.test('nockBack wild tests', function (nw) {

  //  Manually disable net connectivity to confirm that dryrun enables it.
  nock.disableNetConnect();

  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('wild');

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('nock back doesn\'t do anything', {skip: process.env.AIRPLANE}, function (t) {
    nockBackWithFixture(t, false);
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});

tap.test('nockBack dryrun tests', function (nw) {

  //  Manually disable net connectivity to confirm that dryrun enables it.
  nock.disableNetConnect();

  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('dryrun');

  nw.test('goes to internet even when no nockBacks are running', function(t) {

    t.plan(2);

    const server = http.createServer((request, response) => {
      t.pass('server received a request');

      response.writeHead(200);
      response.end();
    });

    server.listen(() => {
      const request = http.request({
        host: 'localhost',
        path: '/',
        port: server.address().port
      }, response => {
        t.is(200, response.statusCode);

        server.close(t.end);
      });

      request.on('error', t.error);
      request.end();
    });

  });

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('uses recorded fixtures', function (t) {
    nockBackWithFixture(t, true);
  });

  nw.test('goes to internet, doesn\'t record new fixtures', {skip: process.env.AIRPLANE}, function (t) {
    var dataCalled = false;

    var fixture = 'someDryrunFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      var req = http.request({
          host: "amazon.com"
        , path: '/'
        , port: 80
        }, function(res) {

          t.ok([200, 301, 302].indexOf(res.statusCode) >= 0);
          res.on('end', function() {
            t.ok(dataCalled);
            t.false(exists(fixtureLoc));
            t.end();
          });

          res.on('data', function(data) {
            dataCalled = true;
          });

        });

      req.once('error', function(err) {
        if (err.code !== 'ECONNREFUSED') {
          throw err;
        }
        t.end();
      });

      req.end();
    });
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});

tap.test('nockBack record tests', function (nw) {
  nockBack.setMode('record');

  nw.test('it records when configured correctly', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };

    var fixture = 'someFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      fs.unlinkSync(fixtureLoc);
      t.end();
    });

  });

  //Adding this test because there was an issue when not calling
  //nock.activate() after calling nock.restore()
  nw.test('it can record twice', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };
    var fixture = 'someFixture2.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;
    t.false(exists(fixtureLoc));

    nockBack(fixture, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      fs.unlinkSync(fixtureLoc);
      t.end();
    });

  });

  nw.test('it shouldn\'t allow outside calls', function (t) {

    var fixture = 'wrongUri.json';

    nockBack(fixture, function (done) {

      http.get('http://www.amazon.com', function(res) {
        throw "should not request this";
      }).on('error', function(err) {
        t.equal(err.message, 'Nock: Not allow net connect for "www.amazon.com:80/"');
        done();
        t.end();
      });

    });

  });

  nw.test('it loads your recorded tests', function (t) {

    nockBack('goodRequest.json', function (done) {
      t.true(this.scopes.length > 0);
      http.get('http://www.google.com').end();
      this.assertScopesFinished();
      done();
      t.end();
    });

  });

  nw.test('it can filter after recording', {skip: process.env.AIRPLANE}, function (t) {
    nockBack.fixtures = __dirname + '/fixtures';

    var options = {
      host: 'www.google.com', method: 'GET', path: '/', port: 80
    };

    var fixture = 'filteredFixture.json';
    var fixtureLoc = nockBack.fixtures + '/' + fixture;

    t.false(exists(fixtureLoc));

    var afterRecord = function(scopes) {
       // You would do some filtering here, but for this test we'll just return an empty array
      return [];
    }

    nockBack(fixture, {afterRecord: afterRecord}, function (done) {
      http.request(options).end();
      done();

      t.true(exists(fixtureLoc));

      nockBack(fixture, function (done) {
        t.true(this.scopes.length === 0);
        done();

        fs.unlinkSync(fixtureLoc);
        t.end();
      });
    });
  });

  nw.end();

  setOriginalModeOnEnd(nw, nockBack);
});

tap.test('nockBack lockdown tests', function (nw) {
  nockBack.fixtures = __dirname + '/fixtures';
  nockBack.setMode('lockdown');

  nw.test('normal nocks work', function (t) {
    testNock(t);
  });

  nw.test('nock back loads scope', function (t) {
    nockBackWithFixture(t, true);
  });

  nw.test('no unnocked http calls work', function (t) {
    var req = http.request({
        host: "google.com"
      , path: '/'
      }, function(res) {
        throw new Error('should not come here!');
      });

    req.on('error', function (err) {
      t.equal(err.message.trim(), 'Nock: Not allow net connect for "google.com:80/"');
      t.end();
    });

    req.end();
  });

  setOriginalModeOnEnd(nw, nockBack);

  nw.end();
});
<|endoftext|>


<commit_before>//This still works in IE 11.

(function (){

	"use strict";

	let context = this,
		oldClass = context.Class,
		_initializing = false;

	/*** helper functions ***/

	function defineProperty(object, propertyName, value, isWritable, isEnumerable, isConfigurable){
		Object.defineProperty(object, propertyName, { value:value, writable:!!isWritable, enumerable:!!isEnumerable, configurable:!!isConfigurable });
	}
	function isPrimitive(o){ var t; return o===t || o===null || (t = typeof o)==="number" || t==="string" || t==="boolean"; }

	/*** base class ***/

	//the base Class constructor; it will have two static methods, 'extend' and 'noConflict'
	function Class(){}

	defineProperty(Class.prototype, "toString", function toString(){ return "[instance of Class]"; }, true, false, true);
	defineProperty(Class, "toString", function toString(){ return "function Class() { [custom code] }"; }, true, false, true);

	/**
	 * Creates a new class that inherits from the parent class.
	 *
	 * @param {object} [options]
	 * @param {string} [options.className] - Used as .name for the class function and in .toString() for instances of the class.
	 * @param {function} [options.constructorFn] - Initializes new instances of the class. A function is passed as the first argument, used to initialize the instance using the parent class' constructor; be sure to call it inside constructorFn (before using `this` or protected members).
	 * @param {function} [options.returnFn] - Returns a value when the constructor is called without using the 'new' keyword.
	 * @param {object} [options.extensions] - Additional and overriding properties and methods for the prototype of the class.
	 * @return {function} - The new class.
	 */
	let extendFn = function extend(options){

		if(options === void 0) options = {};
		else if(isPrimitive(options)) throw new TypeError("argument 'options' is not an object");

		function classNameIsValid(className){
		//checks if the specified classname is valid (note: this doesn't check for reserved words)
			return className !== (void 0) && /^[a-z_$][a-z0-9_$]*$/i.test(className);
		}

		/*** create the new constructor ***/

		let constructorFn = typeof(options.constructorFn) === "function" ? options.constructorFn : function (Super){ Super.apply(null, [].slice.call(arguments, 1)); };
		let returnFn = typeof(options.returnFn) === "function" ? options.returnFn : function (){};

		let newClass = function Class(){

			if(this && this instanceof newClass && (this.constructor === newClass.prototype.constructor || _initializing)){
			//A new instance is being created; initialize it.
			//This condition will be true in these cases:
			//  1) The 'new' operator was used to instantiate this class
			//  2) The 'new' operator was used to instantiate a subclass, and the subclass' constructorFn() calls its first argument (the bound superFn)
			//  3) The 'new' operator was used to instantiate a subclass, and the subclass' constructorFn() includes something like `MySuperClass.call(this)`
			//  4) Possibly if the prototype chain has been screwed with

				let newInstance = this,
					thisIsTheNewInstanceConstructor,
					_protected;

				if(newInstance.constructor === newClass.prototype.constructor){
				//this function is the constructor of the new instance (i.e., it's not a parent class' constructor)

					thisIsTheNewInstanceConstructor = true;
					defineProperty(newInstance, "constructor", newClass, true, false, true);
				}

				let superFn = function (){

					_protected = newClass.prototype.constructor.apply(newInstance, arguments) || {};

					//add the protected getters/setters to superFn
					for(name in _protected){
						if(Object.prototype.hasOwnProperty.call(_protected, name)){
							Object.defineProperty(superFn, name, {
								get:(_protected[name].get ? _protected[name].get.bind(newInstance) : void 0),
								set:(_protected[name].set ? _protected[name].set.bind(newInstance) : void 0),
								enumerable:true, configurable:true
							});
						}
					}

					/**
					 * Stores a getter and a setter (at least one, if not both), allowing a subclass' constructorFn to access a variable or function that is inside this class' constructorFn.
					 *
					 * @param {string} name
					 * @param {function} [getter]
					 * @param {function} [setter]
					 */
					Object.defineProperty(superFn, "addProtectedMember", {
						 value: function addProtectedMember(name, getter, setter){
							if(name === (void 0) || ""+name === "") throw new TypeError("argument 'name' is required");
							if(getter !== (void 0) && typeof(getter) !== "function") throw new TypeError("argument 'getter' is not a function");
							if(setter !== (void 0) && typeof(setter) !== "function") throw new TypeError("argument 'setter' is not a function");
							if(!getter && !setter) return;

							_protected[name] = {get:getter, set:setter};
						},
						writable:false, enumerable:false, configurable:true
					});

					/**
					 * Removes a stored getter & setter, preventing a subclass' constructorFn from accessing the (now private) member.
					 *
					 * @param {string} name
					 */
					Object.defineProperty(superFn, "removeProtectedMember", {
						 value: function addProtectedMember(name){
							if(name === (void 0) || ""+name === "") throw new TypeError("argument 'name' is required");

							delete _protected[name];
						},
						writable:false, enumerable:false, configurable:true
					});

				}

				_initializing = true;
				//constructorFn.apply(newInstance, [superFn].concat([].slice.call(arguments)));
				constructorFn.bind(newInstance, superFn).apply(null, arguments);
				_initializing = false;

				if(!thisIsTheNewInstanceConstructor){
				//this function is the constructor of a super-class
					return _protected;
				}
				//else return this

			}
			else{
			//the 'new' operator was not used; it was just called as a function

				return returnFn.apply(null, arguments);

			}

		}

		//override .name
		defineProperty(newClass, "name",
			classNameIsValid(options.className) ? options.className : classNameIsValid(this.name) ? this.name /*parent class' name*/ : "Class",
			false, false, true);

		//override .toString()
		defineProperty(newClass, "toString", function toString(){ return "function Class() { [custom code] }"; }, true, false, true);

		if(this.extend === extendFn){
		//the 'extend' method of the parent class was not modified

			//make extend() a static method of the new class
			defineProperty(newClass, "extend", extendFn, true, false, true);
		}

		/*** create the new prototype ***/

		//An uninitialized instance of the parent class will be the prototype of the new class.
		//To create an instance without initializing it, we'll temporarily use an empty function as the constructor.
		let emptyFn = function (){};
		emptyFn.prototype = this.prototype;
		let newPrototype = new emptyFn();
		defineProperty(newPrototype, "constructor", this, true, false, true);

		//override .toString()
		defineProperty(newPrototype, "toString",
			function toString(){
				if(this.constructor.name !== (void 0) && /^[a-z_$][a-z0-9_$]*$/i.test(this.constructor.name)){
					return "[instance of "+this.constructor.name+"]";
				}
				return "[instance of Class]";
			},
			true, false, true);

		defineProperty(newClass, "prototype", newPrototype, false, false, false);

		/*** add the new & overriding properties to the prototype ***/

		for(name in options.extensions){
			if(Object.prototype.hasOwnProperty.call(options.extensions, name)){
				newPrototype[name] = options.extensions[name];
			}
		}

		return newClass;

	}

	defineProperty(extendFn, "toString", function toString(){ return "function extend() { [custom code] }"; }, true, false, true);

	//make extend() a static method of Class
	defineProperty(Class, "extend", extendFn, true, false, true);

	/**
	 * Restores 'Class' to what it was before this script replaced it.
	 *
	 * @return {function} - The base Class constructor.
	 */
	function noConflict(){

		if(context) context.Class = oldClass;
		context = null;

		return Class;

	}
	//make noConflict() a static method of Class
	defineProperty(Class, "noConflict", noConflict, true, false, true);

	context.Class = Class;

}).call(window);
<commit_msg>Update Class.js<commit_after>//This still works in IE 11.

(function (){

	"use strict";

	let context = this,
		oldClass = context.Class,
		_initializing = false;

	/*** helper functions ***/

	function defineProperty(object, propertyName, value, isWritable, isEnumerable, isConfigurable){
		Object.defineProperty(object, propertyName, { value:value, writable:!!isWritable, enumerable:!!isEnumerable, configurable:!!isConfigurable });
	}
	function isPrimitive(o){ var t; return o===t || o===null || (t = typeof o)==="number" || t==="string" || t==="boolean"; }
	function warn(msg){
		if(window.console){
			if(typeof window.console.warn === "function") window.console.warn(msg);
			else if(typeof window.console.log === "function") window.console.log(msg);
		}
	}

	/*** base class ***/

	//the base Class constructor; it will have two static methods, 'extend' and 'noConflict'
	function Class(){}

	defineProperty(Class.prototype, "toString", function toString(){ return "[instance of Class]"; }, true, false, true);
	defineProperty(Class, "toString", function toString(){ return "function Class() { [custom code] }"; }, true, false, true);

	/**
	 * Creates a new class that inherits from the parent class.
	 *
	 * @param {object} [options]
	 * @param {string} [options.className] - Used as .name for the class function and in .toString() for instances of the class.
	 * @param {function} [options.constructorFn] - Initializes new instances of the class. A function is passed as the first argument, used to initialize the instance using the parent class' constructor; be sure to call it inside constructorFn (before using `this` or protected members).
	 * @param {function} [options.returnFn] - Returns a value when the constructor is called without using the 'new' keyword.
	 * @param {object} [options.extensions] - Additional and overriding properties and methods for the prototype of the class.
	 * @return {function} - The new class.
	 */
	let extendFn = function extend(options){

		if(options === void 0) options = {};
		else if(isPrimitive(options)) throw new TypeError("argument 'options' is not an object");

		function classNameIsValid(className){
		//checks if the specified classname is valid (note: this doesn't check for reserved words)
			return className !== (void 0) && /^[a-z_$][a-z0-9_$]*$/i.test(className);
		}

		/*** create the new constructor ***/

		let constructorFn = typeof(options.constructorFn) === "function" ? options.constructorFn : function (Super){ Super.apply(null, [].slice.call(arguments, 1)); };
		let returnFn = typeof(options.returnFn) === "function" ? options.returnFn : function (){};

		let newClass = function Class(){

			if(this && this instanceof newClass && (this.constructor === newClass.prototype.constructor || _initializing)){
			//A new instance is being created; initialize it.
			//This condition will be true in these cases:
			//  1) The 'new' operator was used to instantiate this class
			//  2) The 'new' operator was used to instantiate a subclass, and the subclass' constructorFn() calls its first argument (the bound superFn)
			//  3) The 'new' operator was used to instantiate a subclass, and the subclass' constructorFn() includes something like `MySuperClass.call(this)`
			//  4) Possibly if the prototype chain has been screwed with

				let newInstance = this,
					className = newClass.name,
					_protected,
					superFn,
					superFnCalled;

				if(newInstance.constructor === newClass.prototype.constructor){
				//this function is the constructor of the new instance (i.e., it's not a parent class' constructor)

					defineProperty(newInstance, "constructor", newClass, true, false, true);
				}

				superFn = function (){

					if(superFnCalled) return;	//don't initialize it more than once
					superFnCalled = true;

					_protected = newClass.prototype.constructor.apply(newInstance, arguments) || {};

					//add the protected getters/setters to superFn
					for(name in _protected){
						if(Object.prototype.hasOwnProperty.call(_protected, name)){
							Object.defineProperty(superFn, name, {
								get:(_protected[name].get ? _protected[name].get.bind(newInstance) : void 0),
								set:(_protected[name].set ? _protected[name].set.bind(newInstance) : void 0),
								enumerable:true, configurable:true
							});
						}
					}

					/**
					 * Stores a getter and a setter (at least one, if not both), allowing a subclass' constructorFn to access a variable or function that is inside this class' constructorFn.
					 *
					 * @param {string} name
					 * @param {function} [getter]
					 * @param {function} [setter]
					 */
					Object.defineProperty(superFn, "addProtectedMember", {
						 value: function addProtectedMember(name, getter, setter){
							if(name === (void 0) || ""+name === "") throw new TypeError("argument 'name' is required");
							if(getter !== (void 0) && typeof(getter) !== "function") throw new TypeError("argument 'getter' is not a function");
							if(setter !== (void 0) && typeof(setter) !== "function") throw new TypeError("argument 'setter' is not a function");
							if(!getter && !setter) return;

							_protected[name] = {get:getter, set:setter};
						},
						writable:false, enumerable:false, configurable:true
					});

					/**
					 * Removes a stored getter & setter, preventing a subclass' constructorFn from accessing the (now private) member.
					 *
					 * @param {string} name
					 */
					Object.defineProperty(superFn, "removeProtectedMember", {
						 value: function addProtectedMember(name){
							if(name === (void 0) || ""+name === "") throw new TypeError("argument 'name' is required");

							delete _protected[name];
						},
						writable:false, enumerable:false, configurable:true
					});

				}

				_initializing = true;
				//constructorFn.apply(newInstance, [superFn].concat([].slice.call(arguments)));
				constructorFn.bind(newInstance, superFn).apply(null, arguments);
				_initializing = false;

				if(!superFnCalled) warn(className+" constructor does not include a call to the 'Super' argument");

				if(newInstance.constructor !== newClass){
				//this function is the constructor of a super-class

					return _protected;
				}
				//else return this

			}
			else{
			//the 'new' operator was not used; it was just called as a function

				return returnFn.apply(null, arguments);

			}

		}

		//override .name
		defineProperty(newClass, "name",
			classNameIsValid(options.className) ? options.className : classNameIsValid(this.name) ? this.name /*parent class' name*/ : "Class",
			false, false, true);

		//override .toString()
		defineProperty(newClass, "toString", function toString(){ return "function Class() { [custom code] }"; }, true, false, true);

		if(this.extend === extendFn){
		//the 'extend' method of the parent class was not modified

			//make extend() a static method of the new class
			defineProperty(newClass, "extend", extendFn, true, false, true);
		}

		/*** create the new prototype ***/

		//An uninitialized instance of the parent class will be the prototype of the new class.
		//To create an instance without initializing it, we'll temporarily use an empty function as the constructor.
		let emptyFn = function (){};
		emptyFn.prototype = this.prototype;
		let newPrototype = new emptyFn();
		defineProperty(newPrototype, "constructor", this, true, false, true);

		//override .toString()
		defineProperty(newPrototype, "toString",
			function toString(){
				if(this.constructor.name !== (void 0) && /^[a-z_$][a-z0-9_$]*$/i.test(this.constructor.name)){
					return "[instance of "+this.constructor.name+"]";
				}
				return "[instance of Class]";
			},
			true, false, true);

		defineProperty(newClass, "prototype", newPrototype, false, false, false);

		/*** add the new & overriding properties to the prototype ***/

		for(name in options.extensions){
			if(Object.prototype.hasOwnProperty.call(options.extensions, name)){
				newPrototype[name] = options.extensions[name];
			}
		}

		return newClass;

	}

	defineProperty(extendFn, "toString", function toString(){ return "function extend() { [custom code] }"; }, true, false, true);

	//make extend() a static method of Class
	defineProperty(Class, "extend", extendFn, true, false, true);

	/**
	 * Restores 'Class' to what it was before this script replaced it.
	 *
	 * @return {function} - The base Class constructor.
	 */
	function noConflict(){

		if(context) context.Class = oldClass;
		context = null;

		return Class;

	}
	//make noConflict() a static method of Class
	defineProperty(Class, "noConflict", noConflict, true, false, true);

	context.Class = Class;

}).call(window);
<|endoftext|>


<commit_before>import { Session } from 'meteor/session';
import { Random } from 'meteor/random';
import { $ } from 'meteor/jquery';
import { _ } from 'meteor/underscore';
// Local Modules
import { OHIF } from 'meteor/ohif:core';
import { updateOrientationMarkers } from './updateOrientationMarkers';
import { getInstanceClassDefaultViewport } from './instanceClassSpecificViewport';

const getActiveViewportElement = () => {
    const viewportIndex = Session.get('activeViewport') || 0;
    return $('.imageViewerViewport').get(viewportIndex);
};

const zoomIn = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    const scaleIncrement = 0.15;
    const maximumScale = 10;
    viewport.scale = Math.min(viewport.scale + scaleIncrement, maximumScale);
    cornerstone.setViewport(element, viewport);
};

const zoomOut = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    const scaleIncrement = 0.15;
    const minimumScale = 0.05;
    viewport.scale = Math.max(viewport.scale - scaleIncrement, minimumScale);
    cornerstone.setViewport(element, viewport);
};

const zoomToFit = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    cornerstone.fitToWindow(element);
};

const rotateL = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    viewport.rotation -= 90;
    cornerstone.setViewport(element, viewport);
    updateOrientationMarkers(element, viewport);
};

const rotateR = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    viewport.rotation += 90;
    cornerstone.setViewport(element, viewport);
    updateOrientationMarkers(element, viewport);
};

const invert = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    viewport.invert = (viewport.invert === false);
    cornerstone.setViewport(element, viewport);
};

const flipV = () => {
    const element = getActiveViewportElement();
    const viewport = cornerstone.getViewport(element);
    viewport.vflip = (viewport.vflip === false);
    cornerstone.setViewport(element, viewport);
    updateOrientationMarkers(element, viewport);
};

const flipH = () => {
    const element = getActiveViewportElement();
    const viewport = cornerstone.getViewport(element);
    viewport.hflip = (viewport.hflip === false);
    cornerstone.setViewport(element, viewport);
    updateOrientationMarkers(element, viewport);
};

const resetViewport = () => {
    const element = getActiveViewportElement();
    const enabledElement = cornerstone.getEnabledElement(element);
    if (enabledElement.fitToWindow === false) {
        const imageId = enabledElement.image.imageId;
        const instance = cornerstoneTools.metaData.get('instance', imageId);

        enabledElement.viewport = cornerstone.getDefaultViewport(enabledElement.canvas, enabledElement.image);

        const instanceClassDefaultViewport = getInstanceClassDefaultViewport(instance, enabledElement, imageId);
        cornerstone.setViewport(element, instanceClassDefaultViewport);
    } else {
        cornerstone.reset(element);
    }
};

const clearTools = () => {
    const element = getActiveViewportElement();
    const toolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager;
    toolStateManager.clear(element);
    cornerstone.updateImage(element);
};

const linkStackScroll = () => {
    const synchronizer = OHIF.viewer.stackImagePositionOffsetSynchronizer;

    if(synchronizer.isActive()) {
        synchronizer.deactivate();
    } else {
        synchronizer.activate();
    }
};

// This function was originally defined alone inside client/lib/toggleDialog.js
// and has been moved here to avoid circular dependency issues.
const toggleDialog = (e =>lement) {
    const $element = $(element);
    if($element.is('dialog')) {
        if (element.hasAttribute('open')) {
            stopAllClips();
            element.close();
        } else {
            element.show();
        }
    }
    else {
        const isClosed = $element.hasClass('dialog-open');
        $element.toggleClass('dialog-closed', isClosed);
        $element.toggleClass('dialog-open', !isClosed);
    }

    Session.set('UpdateCINE', Random.id());
};

// Toggle the play/stop state for the cornerstone clip tool
const toggleCinePlay = () => {
    // Get the active viewport element
    const element = getActiveViewportElement();

    // Check if it's playing the clip to toggle it
    if (isPlaying()) {
        cornerstoneTools.stopClip(element);
    } else {
        cornerstoneTools.playClip(element);
    }

    // Update the UpdateCINE session property
    Session.set('UpdateCINE', Random.id());
};

// Show/hide the CINE dialog
const toggleCineDialog = () => {
    const dialog = document.getElementById('cineDialog');
    toggleDialog(dialog);
};

// Check if the clip is playing on the active viewport
const isPlaying = () => {
    // Create a dependency on LayoutManagerUpdated and UpdateCINE session
    Session.get('UpdateCINE');
    Session.get('LayoutManagerUpdated');

    // Get the viewport element and its current playClip tool state
    const element = getActiveViewportElement();
    // Empty Elements throws cornerstore exception
    if (!element || !$(element).find('canvas').length) {
        return;
    }

    const toolState = cornerstoneTools.getToolState(element, 'playClip');

    // Stop here if the tool state is not defined yet
    if (!toolState) {
        return false;
    }

    // Get the clip state
    const clipState = toolState.data[0];

    if(clipState) {
        // Return true if the clip is playing
        return !_.isUndefined(clipState.intervalId);
    }

    return false;
};

// Check if a study has multiple frames
const hasMultipleFrames = () => {
    // Its called everytime active viewport and/or layout change
    Session.get('activeViewport');
    Session.get('LayoutManagerUpdated');

    const activeViewport = getActiveViewportElement();

    // No active viewport yet: disable button
    if(!activeViewport || !$(activeViewport).find('canvas').length) {
      return true;
    }

    // Get images in the stack
    const stackToolData = cornerstoneTools.getToolState(activeViewport, 'stack');

    // No images in the stack, so disable button
    if (!stackToolData || !stackToolData.data || !stackToolData.data.length) {
        return true;
    }

    // Get number of images in the stack
    const stackData = stackToolData.data[0];
    const nImages = stackData.imageIds && stackData.imageIds.length ? stackData.imageIds.length : 1;

    // Stack has just one image, so disable button
    if(nImages === 1) {
      return true;
    }

    return false;
};

// Stop clips on all non-empty elements
const stopAllClips = () => {
    const elements = $('.imageViewerViewport').not('.empty');
    elements.each( (index, element) => {
        if ($(element).find('canvas').length) {
            cornerstoneTools.stopClip(element);
        }
    });
};

const isStackScrollLinkingDisabled = () => {
    // Its called everytime active viewport and/or layout change
    Session.get('activeViewport');
    Session.get('LayoutManagerUpdated');

    const synchronizer = OHIF.viewer.stackImagePositionOffsetSynchronizer;
    const linkableViewports = synchronizer.getLinkableViewports();

    return linkableViewports.length <= 1;
};

// Create an event listener to update playing state when a clip stops playing
$(window).on('CornerstoneToolsClipStopped', () => Session.set('UpdateCINE', Random.id()));

/**
 * Export functions inside viewportUtils namespace.
 */

const viewportUtils = {
    getActiveViewportElement,
    zoomIn,
    zoomOut,
    zoomToFit,
    rotateL,
    rotateR,
    invert,
    flipV,
    flipH,
    resetViewport,
    clearTools,
    linkStackScroll,
    toggleDialog,
    toggleCinePlay,
    toggleCineDialog,
    isPlaying,
    hasMultipleFrames,
    stopAllClips,
    isStackScrollLinkingDisabled
};

export { viewportUtils };
<commit_msg>Fixing mistaken push<commit_after>import { Session } from 'meteor/session';
import { Random } from 'meteor/random';
import { $ } from 'meteor/jquery';
import { _ } from 'meteor/underscore';
// Local Modules
import { OHIF } from 'meteor/ohif:core';
import { updateOrientationMarkers } from './updateOrientationMarkers';
import { getInstanceClassDefaultViewport } from './instanceClassSpecificViewport';

const getActiveViewportElement = () => {
    const viewportIndex = Session.get('activeViewport') || 0;
    return $('.imageViewerViewport').get(viewportIndex);
};

const zoomIn = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    const scaleIncrement = 0.15;
    const maximumScale = 10;
    viewport.scale = Math.min(viewport.scale + scaleIncrement, maximumScale);
    cornerstone.setViewport(element, viewport);
};

const zoomOut = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    const scaleIncrement = 0.15;
    const minimumScale = 0.05;
    viewport.scale = Math.max(viewport.scale - scaleIncrement, minimumScale);
    cornerstone.setViewport(element, viewport);
};

const zoomToFit = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    cornerstone.fitToWindow(element);
};

const rotateL = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    viewport.rotation -= 90;
    cornerstone.setViewport(element, viewport);
    updateOrientationMarkers(element, viewport);
};

const rotateR = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    viewport.rotation += 90;
    cornerstone.setViewport(element, viewport);
    updateOrientationMarkers(element, viewport);
};

const invert = () => {
    const element = getActiveViewportElement();
    if (!element) {
        return;
    }

    const viewport = cornerstone.getViewport(element);
    viewport.invert = (viewport.invert === false);
    cornerstone.setViewport(element, viewport);
};

const flipV = () => {
    const element = getActiveViewportElement();
    const viewport = cornerstone.getViewport(element);
    viewport.vflip = (viewport.vflip === false);
    cornerstone.setViewport(element, viewport);
    updateOrientationMarkers(element, viewport);
};

const flipH = () => {
    const element = getActiveViewportElement();
    const viewport = cornerstone.getViewport(element);
    viewport.hflip = (viewport.hflip === false);
    cornerstone.setViewport(element, viewport);
    updateOrientationMarkers(element, viewport);
};

const resetViewport = () => {
    const element = getActiveViewportElement();
    const enabledElement = cornerstone.getEnabledElement(element);
    if (enabledElement.fitToWindow === false) {
        const imageId = enabledElement.image.imageId;
        const instance = cornerstoneTools.metaData.get('instance', imageId);

        enabledElement.viewport = cornerstone.getDefaultViewport(enabledElement.canvas, enabledElement.image);

        const instanceClassDefaultViewport = getInstanceClassDefaultViewport(instance, enabledElement, imageId);
        cornerstone.setViewport(element, instanceClassDefaultViewport);
    } else {
        cornerstone.reset(element);
    }
};

const clearTools = () => {
    const element = getActiveViewportElement();
    const toolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager;
    toolStateManager.clear(element);
    cornerstone.updateImage(element);
};

const linkStackScroll = () => {
    const synchronizer = OHIF.viewer.stackImagePositionOffsetSynchronizer;

    if(synchronizer.isActive()) {
        synchronizer.deactivate();
    } else {
        synchronizer.activate();
    }
};

// This function was originally defined alone inside client/lib/toggleDialog.js
// and has been moved here to avoid circular dependency issues.
const toggleDialog = element => {
    const $element = $(element);
    if($element.is('dialog')) {
        if (element.hasAttribute('open')) {
            stopAllClips();
            element.close();
        } else {
            element.show();
        }
    }
    else {
        const isClosed = $element.hasClass('dialog-open');
        $element.toggleClass('dialog-closed', isClosed);
        $element.toggleClass('dialog-open', !isClosed);
    }

    Session.set('UpdateCINE', Random.id());
};

// Toggle the play/stop state for the cornerstone clip tool
const toggleCinePlay = () => {
    // Get the active viewport element
    const element = getActiveViewportElement();

    // Check if it's playing the clip to toggle it
    if (isPlaying()) {
        cornerstoneTools.stopClip(element);
    } else {
        cornerstoneTools.playClip(element);
    }

    // Update the UpdateCINE session property
    Session.set('UpdateCINE', Random.id());
};

// Show/hide the CINE dialog
const toggleCineDialog = () => {
    const dialog = document.getElementById('cineDialog');
    toggleDialog(dialog);
};

// Check if the clip is playing on the active viewport
const isPlaying = () => {
    // Create a dependency on LayoutManagerUpdated and UpdateCINE session
    Session.get('UpdateCINE');
    Session.get('LayoutManagerUpdated');

    // Get the viewport element and its current playClip tool state
    const element = getActiveViewportElement();
    // Empty Elements throws cornerstore exception
    if (!element || !$(element).find('canvas').length) {
        return;
    }

    const toolState = cornerstoneTools.getToolState(element, 'playClip');

    // Stop here if the tool state is not defined yet
    if (!toolState) {
        return false;
    }

    // Get the clip state
    const clipState = toolState.data[0];

    if(clipState) {
        // Return true if the clip is playing
        return !_.isUndefined(clipState.intervalId);
    }

    return false;
};

// Check if a study has multiple frames
const hasMultipleFrames = () => {
    // Its called everytime active viewport and/or layout change
    Session.get('activeViewport');
    Session.get('LayoutManagerUpdated');

    const activeViewport = getActiveViewportElement();

    // No active viewport yet: disable button
    if(!activeViewport || !$(activeViewport).find('canvas').length) {
      return true;
    }

    // Get images in the stack
    const stackToolData = cornerstoneTools.getToolState(activeViewport, 'stack');

    // No images in the stack, so disable button
    if (!stackToolData || !stackToolData.data || !stackToolData.data.length) {
        return true;
    }

    // Get number of images in the stack
    const stackData = stackToolData.data[0];
    const nImages = stackData.imageIds && stackData.imageIds.length ? stackData.imageIds.length : 1;

    // Stack has just one image, so disable button
    if(nImages === 1) {
      return true;
    }

    return false;
};

// Stop clips on all non-empty elements
const stopAllClips = () => {
    const elements = $('.imageViewerViewport').not('.empty');
    elements.each( (index, element) => {
        if ($(element).find('canvas').length) {
            cornerstoneTools.stopClip(element);
        }
    });
};

const isStackScrollLinkingDisabled = () => {
    // Its called everytime active viewport and/or layout change
    Session.get('activeViewport');
    Session.get('LayoutManagerUpdated');

    const synchronizer = OHIF.viewer.stackImagePositionOffsetSynchronizer;
    const linkableViewports = synchronizer.getLinkableViewports();

    return linkableViewports.length <= 1;
};

// Create an event listener to update playing state when a clip stops playing
$(window).on('CornerstoneToolsClipStopped', () => Session.set('UpdateCINE', Random.id()));

/**
 * Export functions inside viewportUtils namespace.
 */

const viewportUtils = {
    getActiveViewportElement,
    zoomIn,
    zoomOut,
    zoomToFit,
    rotateL,
    rotateR,
    invert,
    flipV,
    flipH,
    resetViewport,
    clearTools,
    linkStackScroll,
    toggleDialog,
    toggleCinePlay,
    toggleCineDialog,
    isPlaying,
    hasMultipleFrames,
    stopAllClips,
    isStackScrollLinkingDisabled
};

export { viewportUtils };
<|endoftext|>


<commit_before>/* @flow */

const path = require('path');
const babel = require('@babel/core');
const stylis = require('stylis');
const { SourceMapGenerator } = require('source-map');

/* ::
type Location = {
  line: number,
  column: number
}
*/

/* ::
type Result = {
  code: string,
  sourceMap: ?Object,
  cssText?: string,
  cssSourceMapText?: string,
  dependencies?: string[],
  rules?: {
    [className: string]: {
      cssText: string,
      displayName: string,
      start: ?Location,
    },
  },
  replacements?: Array<{
    original: { start: Location, end: Location },
    length: number
  }>,
}
*/

/* ::
type PluginOptions = {
  evaluate?: boolean,
  displayName?: boolean,
}
*/

const STYLIS_DECLARATION = 1;

module.exports = function transform(
  filename /* :string */,
  content /* :string */,
  options /* :PluginOptions */,
  inputSourceMap /* :?Object */,
  outputFilename /* : ?string */
) /* : Result */ {
  // Check if the file contains `css` or `styled` tag first
  // Otherwise we should skip transforming
  if (!/\b(styled(\([^)]+\)|\.[a-z0-9]+)|css)[\s\n]*`/.test(content)) {
    return { code: content, sourceMap: inputSourceMap };
  }

  const parserOpts = {
    // https://babeljs.io/docs/en/next/babel-parser.html#plugins
    plugins: [
      // ECMAScript proposals
      'asyncGenerators',
      'bigInt',
      'classProperties',
      'classPrivateProperties',
      'classPrivateMethods',
      ['decorators', { decoratorsBeforeExport: true }],
      'doExpressions',
      'dynamicImport',
      'exportDefaultFrom',
      'exportNamespaceFrom',
      'functionBind',
      'functionSent',
      'importMeta',
      'logicalAssignment',
      'nullishCoalescingOperator',
      'numericSeparator',
      'objectRestSpread',
      'optionalCatchBinding',
      'optionalChaining',
      ['pipelineOperator', { proposal: 'minimal' }],
      'throwExpressions',

      // Language extensions
      'jsx',
    ],
  };

  if (/\.tsx?/.test(filename)) {
    parserOpts.plugins.push('typescript');
  } else {
    parserOpts.plugins.push('flow');
  }

  const { metadata, code, map } = babel.transformSync(content, {
    filename,
    presets: [[require.resolve('./babel'), options]],
    exclude: /node_modules/,
    babelrc: false,
    configFile: false,
    sourceMaps: true,
    sourceFileName: filename,
    inputSourceMap,
    parserOpts,
  });

  const { rules, replacements, dependencies } = metadata.linaria || {};
  const mappings = [];

  let cssText = '';

  stylis.use(null)((context, decl) => {
    if (context === STYLIS_DECLARATION && outputFilename) {
      // When writing to a file, we need to adjust the relative paths inside url(..) expressions
      // It'll allow css-loader to resolve an imported asset properly
      return decl.replace(
        /\b(url\()(\.[^)]+)(\))/,
        (match, p1, p2, p3) =>
          p1 +
          // Replace asset path with new path relative to the output CSS
          path.relative(
            /* $FlowFixMe */
            path.dirname(outputFilename),
            // Get the absolute path to the asset from the path relative to the JS file
            path.resolve(path.dirname(filename), p2)
          ) +
          p3
      );
    }

    return decl;
  });

  Object.keys(rules).forEach((selector, index) => {
    mappings.push({
      generated: {
        line: index + 1,
        column: 0,
      },
      original: rules[selector].start,
      name: selector,
    });

    // Run each rule through stylis to support nesting
    cssText += `${stylis(selector, rules[selector].cssText)}\n`;
  });

  return {
    code,
    cssText,
    rules,
    replacements,
    dependencies,
    sourceMap: map,

    get cssSourceMapText() {
      if (mappings && mappings.length) {
        const generator = new SourceMapGenerator({
          file: filename.replace(/\.js$/, '.css'),
        });

        mappings.forEach(mapping =>
          generator.addMapping(Object.assign({}, mapping, { source: filename }))
        );

        generator.setSourceContent(filename, content);

        return generator.toString();
      }

      return '';
    },
  };
};
<commit_msg>fix: don't error if babel didn't return metadata.linaria<commit_after>/* @flow */

const path = require('path');
const babel = require('@babel/core');
const stylis = require('stylis');
const { SourceMapGenerator } = require('source-map');

/* ::
type Location = {
  line: number,
  column: number
}
*/

/* ::
type Result = {
  code: string,
  sourceMap: ?Object,
  cssText?: string,
  cssSourceMapText?: string,
  dependencies?: string[],
  rules?: {
    [className: string]: {
      cssText: string,
      displayName: string,
      start: ?Location,
    },
  },
  replacements?: Array<{
    original: { start: Location, end: Location },
    length: number
  }>,
}
*/

/* ::
type PluginOptions = {
  evaluate?: boolean,
  displayName?: boolean,
}
*/

const STYLIS_DECLARATION = 1;

module.exports = function transform(
  filename /* :string */,
  content /* :string */,
  options /* :PluginOptions */,
  inputSourceMap /* :?Object */,
  outputFilename /* : ?string */
) /* : Result */ {
  // Check if the file contains `css` or `styled` tag first
  // Otherwise we should skip transforming
  if (!/\b(styled(\([^)]+\)|\.[a-z0-9]+)|css)[\s\n]*`/.test(content)) {
    return { code: content, sourceMap: inputSourceMap };
  }

  const parserOpts = {
    // https://babeljs.io/docs/en/next/babel-parser.html#plugins
    plugins: [
      // ECMAScript proposals
      'asyncGenerators',
      'bigInt',
      'classProperties',
      'classPrivateProperties',
      'classPrivateMethods',
      ['decorators', { decoratorsBeforeExport: true }],
      'doExpressions',
      'dynamicImport',
      'exportDefaultFrom',
      'exportNamespaceFrom',
      'functionBind',
      'functionSent',
      'importMeta',
      'logicalAssignment',
      'nullishCoalescingOperator',
      'numericSeparator',
      'objectRestSpread',
      'optionalCatchBinding',
      'optionalChaining',
      ['pipelineOperator', { proposal: 'minimal' }],
      'throwExpressions',

      // Language extensions
      'jsx',
    ],
  };

  if (/\.tsx?/.test(filename)) {
    parserOpts.plugins.push('typescript');
  } else {
    parserOpts.plugins.push('flow');
  }

  const { metadata, code, map } = babel.transformSync(content, {
    filename,
    presets: [[require.resolve('./babel'), options]],
    exclude: /node_modules/,
    babelrc: false,
    configFile: false,
    sourceMaps: true,
    sourceFileName: filename,
    inputSourceMap,
    parserOpts,
  });

  if (!metadata.linaria) {
    return {
      code: content,
      sourceMap: inputSourceMap,
    };
  }

  const { rules, replacements, dependencies } = metadata.linaria;
  const mappings = [];

  let cssText = '';

  stylis.use(null)((context, decl) => {
    if (context === STYLIS_DECLARATION && outputFilename) {
      // When writing to a file, we need to adjust the relative paths inside url(..) expressions
      // It'll allow css-loader to resolve an imported asset properly
      return decl.replace(
        /\b(url\()(\.[^)]+)(\))/,
        (match, p1, p2, p3) =>
          p1 +
          // Replace asset path with new path relative to the output CSS
          path.relative(
            /* $FlowFixMe */
            path.dirname(outputFilename),
            // Get the absolute path to the asset from the path relative to the JS file
            path.resolve(path.dirname(filename), p2)
          ) +
          p3
      );
    }

    return decl;
  });

  Object.keys(rules).forEach((selector, index) => {
    mappings.push({
      generated: {
        line: index + 1,
        column: 0,
      },
      original: rules[selector].start,
      name: selector,
    });

    // Run each rule through stylis to support nesting
    cssText += `${stylis(selector, rules[selector].cssText)}\n`;
  });

  return {
    code,
    cssText,
    rules,
    replacements,
    dependencies,
    sourceMap: map,

    get cssSourceMapText() {
      if (mappings && mappings.length) {
        const generator = new SourceMapGenerator({
          file: filename.replace(/\.js$/, '.css'),
        });

        mappings.forEach(mapping =>
          generator.addMapping(Object.assign({}, mapping, { source: filename }))
        );

        generator.setSourceContent(filename, content);

        return generator.toString();
      }

      return '';
    },
  };
};
<|endoftext|>