<commit_before>/**
 * @class CM_FormField_DateTimeInterval
 * @extends CM_FormField_Abstract
 */
var CM_FormField_DateTimeInterval = CM_FormField_Abstract.extend({
  _class: 'CM_FormField_DateTimeInterval',

  ready: function() {
    this.bindJquery(this.$('select,input'), 'change', function() {
      this.trigger('change');
    });
  },

  isEmpty: function(value) {
    return _.isEmpty(value.day) || _.isEmpty(value.month) || _.isEmpty(value.year) || _.isEmpty(value.start) || _.isEmpty(value.end);
  },

  getInput: function() {
    return this.$('select');
  },

  /**
   * @returns {{day: *, month: *, year: *, start: *, end: *}}
   */
  getValue: function() {
    return {
      day: this.$('select.day').val(),
      month: this.$('select.month').val(),
      year: this.$('select.year').val(),
      start: this.$('input.start').val(),
      end: this.$('input.end').val()
    };
  },

  /**
   * @param {{day: *, month: *, year: *, start: *, end: *}} dateTimeInterval
   */
  setValue: function(dateTimeInterval) {
    this.$('select.day').val(dateTimeInterval.day);
    this.$('select.month').val(dateTimeInterval.month);
    this.$('select.year').val(dateTimeInterval.year);
    this.$('input.start').val(dateTimeInterval.year);
    this.$('input.end').val(dateTimeInterval.year);
  }
});
<commit_msg>include all inputs in getInput()<commit_after>/**
 * @class CM_FormField_DateTimeInterval
 * @extends CM_FormField_Abstract
 */
var CM_FormField_DateTimeInterval = CM_FormField_Abstract.extend({
  _class: 'CM_FormField_DateTimeInterval',

  ready: function() {
    this.bindJquery(this.getInput(), 'change', function() {
      this.trigger('change');
    });
  },

  isEmpty: function(value) {
    return _.isEmpty(value.day) || _.isEmpty(value.month) || _.isEmpty(value.year) || _.isEmpty(value.start) || _.isEmpty(value.end);
  },

  getInput: function() {
    return this.$('select, input');
  },

  /**
   * @returns {{day: *, month: *, year: *, start: *, end: *}}
   */
  getValue: function() {
    return {
      day: this.$('select.day').val(),
      month: this.$('select.month').val(),
      year: this.$('select.year').val(),
      start: this.$('input.start').val(),
      end: this.$('input.end').val()
    };
  },

  /**
   * @param {{day: *, month: *, year: *, start: *, end: *}} dateTimeInterval
   */
  setValue: function(dateTimeInterval) {
    this.$('select.day').val(dateTimeInterval.day);
    this.$('select.month').val(dateTimeInterval.month);
    this.$('select.year').val(dateTimeInterval.year);
    this.$('input.start').val(dateTimeInterval.year);
    this.$('input.end').val(dateTimeInterval.year);
  }
});
<|endoftext|>


<commit_before>module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    return this.addBowerPackagesToProject([
      { name: 'qunit',                           target: '~1.18.0' },
      { name: 'ember-cli-test-loader',           target: '0.1.3'   },
      { name: 'ember-qunit-notifications',       target: '0.0.7'   },
      { name: 'ember-qunit',                     target: '0.4.10'   }
    ]);
  }
};
<commit_msg>Update version of ember-cli-test-loader.<commit_after>module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    return this.addBowerPackagesToProject([
      { name: 'qunit',                           target: '~1.18.0' },
      { name: 'ember-cli-test-loader',           target: '0.2.1'   },
      { name: 'ember-qunit-notifications',       target: '0.0.7'   },
      { name: 'ember-qunit',                     target: '0.4.10'   }
    ]);
  }
};
<|endoftext|>


<commit_before>'use strict';

import fs from 'fs';
import path from 'path';
import Platform from '../services/platform';

let pathWindowsRegex = /^[a-zA-Z]:\\(?:[^#%\\/:*?"<>|\r\n]+\\)*[^#%\\/:*?"<>|\r\n]*$/;
let nonAsciiRegex = /[^\x00-\x7F]+/;

function pathValidator() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, mCtrl) {

      function validateFormatWindows(value) {
        return pathWindowsRegex.test(value);
      }

      function validateAscii(value) {
        return !nonAsciiRegex.test(value);
      }

      function validateLength(value) {
        return value.length<=90;
      }

      function validateDisk(value) {
        let stats = path.parse(value);
        return !stats.root.length == 0 && fs.existsSync(stats.root);
      }

      function isSelected(value) {
        return value.trim().length>0;
      }

      function isAbsolute(value) {
        return path.isAbsolute(value);
      }

      mCtrl.$validators['notSelected'] = isSelected;
      mCtrl.$validators['notAbsolute'] = isAbsolute;
      mCtrl.$validators['tooLong'] = validateLength;
      if(Platform.OS == 'win32') {
        mCtrl.$validators['invalidAscii'] = validateAscii;
        mCtrl.$validators['invalidFormat'] = validateFormatWindows;
        mCtrl.$validators['invalidDisk'] = validateDisk;
      }
    }
  };
}

export default pathValidator;
<commit_msg>JBDS-4334 Restore validation for locations with spaces<commit_after>'use strict';

import fs from 'fs';
import path from 'path';
import Platform from '../services/platform';

let pathWindowsRegex = /^[a-zA-Z]:\\(?:[^#%\\/:*?"<>|\r\n]+\\)*[^#%\\/:*?"<>|\r\n]*$/;
let nonAsciiRegex = /[^\x00-\x7F]+/;

function pathValidator() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, mCtrl) {

      function validateFormatWindows(value) {
        return pathWindowsRegex.test(value);
      }

      function validateAscii(value) {
        return !nonAsciiRegex.test(value);
      }

      function validateLength(value) {
        return value.length<=90;
      }

      function hasNoSpaces(value) {
        return !value.includes(' ');
      }

      function validateDisk(value) {
        let stats = path.parse(value);
        return !stats.root.length == 0 && fs.existsSync(stats.root);
      }

      function isSelected(value) {
        return value.trim().length>0;
      }

      function isAbsolute(value) {
        return path.isAbsolute(value);
      }

      mCtrl.$validators['notSelected'] = isSelected;
      mCtrl.$validators['notAbsolute'] = isAbsolute;
      mCtrl.$validators['tooLong'] = validateLength;
      mCtrl.$validators['hasSpaces'] = hasNoSpaces;
      if(Platform.OS == 'win32') {
        mCtrl.$validators['invalidAscii'] = validateAscii;
        mCtrl.$validators['invalidFormat'] = validateFormatWindows;
        mCtrl.$validators['invalidDisk'] = validateDisk;
      }
    }
  };
}

export default pathValidator;
<|endoftext|>


<commit_before>'use strict';

let dialog = require('remote').require('dialog');
let fs = require('fs');
let path = require('path');
let ipcRenderer = require('electron').ipcRenderer;

class ConfirmController {
  constructor($scope, $state, $timeout, installerDataSvc) {
    this.router = $state;
    this.sc = $scope;
    this.timeout = $timeout;
    this.installerDataSvc = installerDataSvc;
    this.folder = installerDataSvc.installDir();
    this.folderExists = false;
    this.installables = new Object();
    $scope.checkboxModel = new Object();

    $scope.detectionStyle = true;
    for (var [key, value] of this.installerDataSvc.allInstallables().entries()) {
      $scope.checkboxModel[key] = value;
    }
    $scope.isConfigurationValid = this.isConfigurationValid;

    $scope.$watch(()=>{
      return $scope.checkboxModel.jdk.isConfigured()
    },(nVal,oVal)=>{
      if(nVal===false) {
        $scope.checkboxModel.jbds.selected = false;
      }
    });
    $scope.$watch('$viewContentLoaded', ()=>{
      console.log('content loaded');
      $scope.checkboxModel.virtualbox.detectExistingInstall(()=> {
        $scope.checkboxModel.vagrant.detectExistingInstall(()=> {
          $scope.checkboxModel.jdk.detectExistingInstall(()=> {
            $timeout(()=>{
              $scope.detectionStyle = false;
              $scope.$apply();
            });
          });
        });
      });
    });
  }

  install() {
    this.checkFolder();
    if (!this.folderExists) {
      fs.mkdirSync(this.folder);
    }

    this.installerDataSvc.setup(this.folder,
      this.itemRoot('virtualbox'),
      this.itemRoot('jdk'),
      this.itemRoot('jbds'),
      this.itemRoot('vagrant'),
      this.itemRoot('cygwin'),
      this.itemRoot('cdk')
    );
    this.router.go('install');
  }

  selectItem(key) {
    let selection = dialog.showOpenDialog({
      properties: [ 'openDirectory' ],
      defaultPath: this.installables[key] && this.installables[key][0].existingInstallLocation ? this.installables[key][0].existingInstallLocation : this.installerDataSvc.installRoot
    });
    let item = this.installerDataSvc.allInstallables().get(key);

    if (selection) {
      item.checkForExistingInstall(selection, this.installables);
    } else {
      this.timeout(()=>{
        this.sc.$apply(()=>{
          item.detectExistingInstall();
        })
      });
    }
  }

  checkItem(key) {
    let item = this.installerDataSvc.allInstallables().get(key);
    item.checkForExistingInstall();
  }

  selectFolder() {
    let selection = dialog.showOpenDialog({
      properties: [ 'openDirectory' ],
      defaultPath: this.folder
    });

    if (selection) {
      this.folder = selection[0] || this.folder;
    }

    this.checkFolder();
  }

  checkFolder() {
    try {
      fs.accessSync(this.folder, fs.F_OK);
      this.folderExists = true;
    } catch (err) {
      this.folderExists = false;
    }
  }

  folderChanged() {
    this.folder = folder.value;
    this.checkFolder()
  }

  itemRoot(key) {
    let root = this.installables[key] ? this.installables[key][0].existingInstallLocation : null;
    if (root && (root.length === 0 || !this.installables[key][0].existingInstall)) {
      root = null;
    }
    return root;
  }

  isConfigurationValid() {
    return this.checkboxModel.virtualbox.isConfigured()
        && this.checkboxModel.cygwin.isConfigured()
        && this.checkboxModel.vagrant.isConfigured()
        && this.checkboxModel.cdk.isConfigured();
  }
}

ConfirmController.$inject = ['$scope', '$state', '$timeout', 'installerDataSvc'];

export default ConfirmController;
<commit_msg>Turn off the grey screen on the confirm page. This will be activated at a later date.<commit_after>'use strict';

let dialog = require('remote').require('dialog');
let fs = require('fs');
let path = require('path');
let ipcRenderer = require('electron').ipcRenderer;

class ConfirmController {
  constructor($scope, $state, $timeout, installerDataSvc) {
    this.router = $state;
    this.sc = $scope;
    this.timeout = $timeout;
    this.installerDataSvc = installerDataSvc;
    this.folder = installerDataSvc.installDir();
    this.folderExists = false;
    this.installables = new Object();
    $scope.checkboxModel = new Object();

    $scope.detectionStyle = false;
    for (var [key, value] of this.installerDataSvc.allInstallables().entries()) {
      $scope.checkboxModel[key] = value;
    }
    $scope.isConfigurationValid = this.isConfigurationValid;

    $scope.$watch(()=>{
      return $scope.checkboxModel.jdk.isConfigured()
    },(nVal,oVal)=>{
      if(nVal===false) {
        $scope.checkboxModel.jbds.selected = false;
      }
    });
    $scope.$watch('$viewContentLoaded', ()=>{
      console.log('content loaded');
      $scope.checkboxModel.virtualbox.detectExistingInstall(()=> {
        $scope.checkboxModel.vagrant.detectExistingInstall(()=> {
          $scope.checkboxModel.jdk.detectExistingInstall(()=> {
            $timeout(()=>{
              $scope.detectionStyle = false;
              $scope.$apply();
            });
          });
        });
      });
    });
  }

  install() {
    this.checkFolder();
    if (!this.folderExists) {
      fs.mkdirSync(this.folder);
    }

    this.installerDataSvc.setup(this.folder,
      this.itemRoot('virtualbox'),
      this.itemRoot('jdk'),
      this.itemRoot('jbds'),
      this.itemRoot('vagrant'),
      this.itemRoot('cygwin'),
      this.itemRoot('cdk')
    );
    this.router.go('install');
  }

  selectItem(key) {
    let selection = dialog.showOpenDialog({
      properties: [ 'openDirectory' ],
      defaultPath: this.installables[key] && this.installables[key][0].existingInstallLocation ? this.installables[key][0].existingInstallLocation : this.installerDataSvc.installRoot
    });
    let item = this.installerDataSvc.allInstallables().get(key);

    if (selection) {
      item.checkForExistingInstall(selection, this.installables);
    } else {
      this.timeout(()=>{
        this.sc.$apply(()=>{
          item.detectExistingInstall();
        })
      });
    }
  }

  checkItem(key) {
    let item = this.installerDataSvc.allInstallables().get(key);
    item.checkForExistingInstall();
  }

  selectFolder() {
    let selection = dialog.showOpenDialog({
      properties: [ 'openDirectory' ],
      defaultPath: this.folder
    });

    if (selection) {
      this.folder = selection[0] || this.folder;
    }

    this.checkFolder();
  }

  checkFolder() {
    try {
      fs.accessSync(this.folder, fs.F_OK);
      this.folderExists = true;
    } catch (err) {
      this.folderExists = false;
    }
  }

  folderChanged() {
    this.folder = folder.value;
    this.checkFolder()
  }

  itemRoot(key) {
    let root = this.installables[key] ? this.installables[key][0].existingInstallLocation : null;
    if (root && (root.length === 0 || !this.installables[key][0].existingInstall)) {
      root = null;
    }
    return root;
  }

  isConfigurationValid() {
    return this.checkboxModel.virtualbox.isConfigured()
        && this.checkboxModel.cygwin.isConfigured()
        && this.checkboxModel.vagrant.isConfigured()
        && this.checkboxModel.cdk.isConfigured();
  }
}

ConfirmController.$inject = ['$scope', '$state', '$timeout', 'installerDataSvc'];

export default ConfirmController;
<|endoftext|>


<commit_before>/* global ComponentsRegistry, alert */
enyo.kind({
	name:"Ares.DevelopmentPanel",
	kind:"FittableRows",
	components:[
		{kind: "onyx.MoreToolbar", name:"toolbar", classes: "ares-top-toolbar ares-designer-panels", layoutKind: "FittableColumnsLayout", noStretch: true, components: [
			{kind: "onyx.Grabber", classes: "ares-grabber ares-icon", ontap: "activePanel", components:[
				{kind: "aresGrabber", name: "aresGrabberDirection", classes:"lleftArrow"}
			]},
			{name:"editorControls", kind: "FittableColumns", fit:true, classes: "onyx-toolbar-inline", components:[
				{name: "editorFileMenu", kind: "Ares.FileMenu", onSelect: "fileMenuItemSelected"},
				{name: "newKindDecorator", kind: "onyx.TooltipDecorator", components: [
					{name: "newKindButton", kind: "onyx.IconButton", src: "assets/images/new_kind.png", ontap: "newKindAction"},
					{kind: "onyx.Tooltip", content: $L("New Kind")}
				]},
				{fit: true},
				{name: "editorSettingDecorator", kind: "onyx.TooltipDecorator", components: [
					{name: "editorButton", kind: "onyx.IconButton", src: "assets/images/editor_settings.png", ontap: "editorSettings"},
					{kind: "onyx.Tooltip", content: "Editor Settings"}
				]},
				{name: "designerDecorator", kind: "onyx.TooltipDecorator", components: [
					{name: "designerButton", kind: "onyx.IconButton", src: "assets/images/designer.png", ontap: "designerAction"},
					{name: "designerButtonBroken", kind: "onyx.IconButton", src: "assets/images/designer_broken.png", ontap: "doDesignerBroken"},
					{name: "designerTooltipBroken", kind: "Ares.ErrorTooltip", content: $L("Designer")}
				]}
			]},
			{name:"deimosControls", kind: "FittableColumns", fit:true,  classes: "onyx-toolbar-inline", components:[
				{name: "designerFileMenu", kind: "Ares.FileMenu", onSelect: "fileMenuItemSelected"},
				{name: "docLabel", content: "Deimos", classes: "ares-left-margin"},
				{kind: "onyx.PickerDecorator", classes: "ares-right-margin", components: [
					{name: "kindButton", classes:"ares-toolbar-picker", kind: "onyx.PickerButton"},
					{name: "kindPicker", kind: "onyx.Picker", onChange: "kindSelected", components: [
					]}
				]},
				{fit: true},
				{name: "codeEditorDecorator", kind: "onyx.TooltipDecorator", classes: "ares-icon", components: [
					{kind: "onyx.IconButton", src: "assets/images/code_editor.png", ontap: "closeDesignerAction"},
					{kind: "onyx.Tooltip", content: "Code editor"}
				]}
			]},
			{name: "codePreviewDecorator", kind: "onyx.TooltipDecorator", classes: "ares-icon", components: [
				{kind: "onyx.IconButton", src: "../project-view/assets/images/project_view_preview.png", ontap: "doSavePreviewAction"},
				{kind: "onyx.Tooltip", name:"previewTooltip", content: "Preview"}
			]},
			{classes:"ares-logo-container", components:[
				{name:"logo", kind:"Ares.Logo"}
			]}
		]},
		{
			name: "bottomBar",
			kind: "DocumentToolbar",
			classes: "ares-bottom-bar"
		},
		{
			kind: "Panels",
			arrangerKind: "CarouselArranger",
			draggable: false,
			classes:"enyo-fit ares-panels",
			onTransitionStart : "stopPanelEvent",
			onTransitionFinish: "stopPanelEvent",
			ondragstart	      : "stopPanelEvent",
			ondrag            : "stopPanelEvent",
			ondragfinish      : "stopPanelEvent",
			components: [
				{components: [
					{kind: "Phobos"}
				]},
				{components: [
					{kind: "Deimos", onCloseDesigner: "closeDesigner"}
				]}
			]
		}
	],
	events: {
		onRegisterMe: "",
		onMovePanel:"",
		onSavePreviewAction:"",
		onDesignerBroken: "",
		onFileEdited:"_fileEdited"
	},
	published: {
		panelIndex: 2,
		aceActive: true
	},
	handlers: {
		onAceFocus: "aceFocus"
	},
	create: function() {
		this.inherited(arguments);
		this.doRegisterMe({name:"developmentPanel", reference:this});
	},
	activePanel : function(){
		this.doMovePanel({panelIndex:this.panelIndex});
	},
	stopPanelEvent: function(){
		return true;
	},
	fileMenuItemSelected: function(inSender, inEvent) {
		ComponentsRegistry.getComponent("phobos").fileMenuItemSelected(inSender, inEvent);
	},
	editorSettings: function(){
		ComponentsRegistry.getComponent("phobos").editorSettings();
	},
	newKindAction: function() {
		ComponentsRegistry.getComponent("phobos").newKindAction();
	},
	kindSelected: function(inSender, inEvent) {
		ComponentsRegistry.getComponent("deimos").kindSelected(inSender, inEvent);
	},
	designerAction: function() {
		if(ComponentsRegistry.getComponent("phobos").editorUserSyntaxError() !== 0)
		{
			this.userSyntaxErrorPop();
		}
		else
		{
			ComponentsRegistry.getComponent("phobos").designerAction();
			this.manageControls(true);
		}
	},
	enableDesignerButton: function(enable) {
		this.$.designerButton.setShowing(enable);
		this.$.designerButtonBroken.setShowing(! enable);
	},
	userSyntaxErrorPop: function(){
		this.doError({msg: $L("Designer cannot work on a file with a syntax error. Please fix the error highlighted in code editor before launching the designer."), title: $L("Syntax Error")});
	},
	closeDesignerAction: function(){
		ComponentsRegistry.getComponent("deimos").closeDesignerAction();
		this.aceFocus();
	},
	/**
	 * Change controls on the panel top toolbar
	 *
	 * @private
	 * @param {boolean} designer, designer = true if designer's controls should be available
	 */
	manageControls: function(designer){
		this.setAceActive(!designer);
		this.$.editorControls.setShowing(!designer);
		this.$.deimosControls.setShowing(designer);
		this.$.toolbar.resized();
	},
	switchGrabberDirection: function(active){
		this.$.aresGrabberDirection.switchGrabberDirection(active);
	},
	addPreviewTooltip: function(message){
		this.$.previewTooltip.setContent(message);
	},
	updateDeimosLabel: function(edited) {
		if (edited) {
			this.$.docLabel.setContent("Deimos *");
		} else {
			this.$.docLabel.setContent("Deimos");
		}
		this.$.toolbar.resized();
	},
	aceFocus: function(){
		if(this.getAceActive()){
			ComponentsRegistry.getComponent("phobos").focusEditor();
		}
	},
	showErrorTooltip: function(inSender, inEvent){
		this.$.designerTooltipBroken.reset("Designer");
		this.$.designerButtonBroken.setDisabled(false);
		this.$.designerTooltipBroken.raise(inEvent);
	},
	resetErrorTooltip: function(){
		this.$.designerTooltipBroken.reset("Designer");
		this.$.designerButtonBroken.setDisabled(true);
	},
	getErrorFromDesignerBroken: function(){
		return this.$.designerTooltipBroken.error;
	},
	_fileEdited: function(){
		ComponentsRegistry.getComponent("developmentController")._fileEdited();
	}
});

enyo.kind({
	name: "Ares.DevelopmentController",
	kind: "enyo.Component",

	events: {
		onRegisterMe: "",
		onNewActiveDocument: "", // to preserve legacy in Ares.js
	},

	debug: false,

	create: function() {
		this.inherited(arguments);

		// Setup this.trace() function according to this.debug value
		ares.setupTraceLogger(this);

		this.doRegisterMe({name:"developmentController", reference:this});
	},

	activeDocument: null,

	switchToDocument: function(newDoc) {
		// safety net
		if ( ! newDoc ) {
			if  (this.debug) { throw("File ID " + newDoc + " not found in cache!");}
			else             { alert("File ID not found in cache!");}
			return;
		}

		var oldDoc = this.activeDocument ; // may be undef when a project is closed
		var newName = newDoc.getProjectData().getName() ;
		this.trace("switch " + (oldDoc ? "from " + oldDoc.getId() + " " : " ")
				   + "to " + newDoc.getId() );

		//select project if the file(d) comes from another project then the previous file
		if (!oldDoc || oldDoc.getProjectData().getName() !== newName){
			this.trace("also switch project "
					   + (oldDoc ? "from " + oldDoc.getProjectData().getName()  + " " : " ")
					   + ' to ' + newDoc.getProjectData().getName());
			var project = Ares.Workspace.projects.get(newDoc.getProjectData().id);
			// switch document is done in the callback
			ComponentsRegistry.getComponent("projectList")
				.selectInProjectList(project, this._switchDoc.bind(this,newDoc));
		}
		else {
			this._switchDoc(newDoc);
		}

	},

	// switch Phobos or Deimos to new document
	_switchDoc: function(newDoc) {
		var oldDoc = this.activeDocument ;
		this.trace("switch " + (oldDoc ? "from " + oldDoc.getId()  + " " : " ")
				   + ' to ' + newDoc.getId());
		// We no longer save the data as the ACE edit session will keep the data for us
		if (!oldDoc || newDoc !== oldDoc) {
			ComponentsRegistry.getComponent("phobos").openDoc(newDoc);
		}
		var currentIF = newDoc.getCurrentIF();
		this.activeDocument = newDoc;
		var developmentPanel = ComponentsRegistry.getComponent("developmentPanel");
		developmentPanel.addPreviewTooltip("Preview " + newDoc.getProjectData().id);

		if (currentIF === 'code') {
			developmentPanel.$.panels.setIndex(this.phobosViewIndex);
			developmentPanel.manageControls(false);
		} else {
			ComponentsRegistry.getComponent("phobos").designerAction();
			developmentPanel.manageControls(true);
		}
		this._fileEdited();
		ComponentsRegistry.getComponent("documentToolbar").activateFileWithId(newDoc.getId());
		this.doNewActiveDocument({ doc: this.activeDocument} );
	},
	_fileEdited: function() {
		ComponentsRegistry.getComponent("developmentPanel").updateDeimosLabel(this.activeDocument.getEdited());
	},

});

/**
	Ares.FileMenu extends _onyx.MenuDecorator_. This contains the various drop-down options (save, close, etc.) in our file menu
*/
enyo.kind({
	name: "Ares.FileMenu",
	kind: "onyx.MenuDecorator",
	classes:"aresmenu ares-right-margin ares-left-margin",
	events: {
		onAceFocus: ""
	},
	components: [
		{tag:"button", content: "File"},
		{kind: "onyx.Menu", floating: true, classes:"sub-aresmenu", maxHeight: "100%", components: [
			{name: "saveButton", value: "saveDocAction", classes:"aresmenu-button", components: [
				{kind: "onyx.IconButton", src: "$phobos/assets/images/menu-icon-save-darken.png"},
				{content: $L("Save")}
			]},
			{name: "saveAsButton", value: "saveAsDocAction", classes:"aresmenu-button", components: [
				{kind: "onyx.IconButton", src: "$phobos/assets/images/menu-icon-save-darken.png"},
				{content: $L("Save as...")}
			]},
			{classes: "onyx-menu-divider"},
			{name: "closeButton", value: "closeDocAction", classes:"aresmenu-button", components: [
				{kind: "onyx.IconButton", src: "$phobos/assets/images/menu-icon-stop.png"},
				{content: $L("Close")}
			]},
			{name: "closeAllButton", value: "closeAllDocAction", classes:"aresmenu-button", components: [
				{kind: "onyx.IconButton", src: "$phobos/assets/images/menu-icon-stop.png"},
				{content: $L("Close All")}
			]}
		]}
	]
});
<commit_msg>ENYO-3082: improved trace<commit_after>/* global ComponentsRegistry, alert */
enyo.kind({
	name:"Ares.DevelopmentPanel",
	kind:"FittableRows",
	components:[
		{kind: "onyx.MoreToolbar", name:"toolbar", classes: "ares-top-toolbar ares-designer-panels", layoutKind: "FittableColumnsLayout", noStretch: true, components: [
			{kind: "onyx.Grabber", classes: "ares-grabber ares-icon", ontap: "activePanel", components:[
				{kind: "aresGrabber", name: "aresGrabberDirection", classes:"lleftArrow"}
			]},
			{name:"editorControls", kind: "FittableColumns", fit:true, classes: "onyx-toolbar-inline", components:[
				{name: "editorFileMenu", kind: "Ares.FileMenu", onSelect: "fileMenuItemSelected"},
				{name: "newKindDecorator", kind: "onyx.TooltipDecorator", components: [
					{name: "newKindButton", kind: "onyx.IconButton", src: "assets/images/new_kind.png", ontap: "newKindAction"},
					{kind: "onyx.Tooltip", content: $L("New Kind")}
				]},
				{fit: true},
				{name: "editorSettingDecorator", kind: "onyx.TooltipDecorator", components: [
					{name: "editorButton", kind: "onyx.IconButton", src: "assets/images/editor_settings.png", ontap: "editorSettings"},
					{kind: "onyx.Tooltip", content: "Editor Settings"}
				]},
				{name: "designerDecorator", kind: "onyx.TooltipDecorator", components: [
					{name: "designerButton", kind: "onyx.IconButton", src: "assets/images/designer.png", ontap: "designerAction"},
					{name: "designerButtonBroken", kind: "onyx.IconButton", src: "assets/images/designer_broken.png", ontap: "doDesignerBroken"},
					{name: "designerTooltipBroken", kind: "Ares.ErrorTooltip", content: $L("Designer")}
				]}
			]},
			{name:"deimosControls", kind: "FittableColumns", fit:true,  classes: "onyx-toolbar-inline", components:[
				{name: "designerFileMenu", kind: "Ares.FileMenu", onSelect: "fileMenuItemSelected"},
				{name: "docLabel", content: "Deimos", classes: "ares-left-margin"},
				{kind: "onyx.PickerDecorator", classes: "ares-right-margin", components: [
					{name: "kindButton", classes:"ares-toolbar-picker", kind: "onyx.PickerButton"},
					{name: "kindPicker", kind: "onyx.Picker", onChange: "kindSelected", components: [
					]}
				]},
				{fit: true},
				{name: "codeEditorDecorator", kind: "onyx.TooltipDecorator", classes: "ares-icon", components: [
					{kind: "onyx.IconButton", src: "assets/images/code_editor.png", ontap: "closeDesignerAction"},
					{kind: "onyx.Tooltip", content: "Code editor"}
				]}
			]},
			{name: "codePreviewDecorator", kind: "onyx.TooltipDecorator", classes: "ares-icon", components: [
				{kind: "onyx.IconButton", src: "../project-view/assets/images/project_view_preview.png", ontap: "doSavePreviewAction"},
				{kind: "onyx.Tooltip", name:"previewTooltip", content: "Preview"}
			]},
			{classes:"ares-logo-container", components:[
				{name:"logo", kind:"Ares.Logo"}
			]}
		]},
		{
			name: "bottomBar",
			kind: "DocumentToolbar",
			classes: "ares-bottom-bar"
		},
		{
			kind: "Panels",
			arrangerKind: "CarouselArranger",
			draggable: false,
			classes:"enyo-fit ares-panels",
			onTransitionStart : "stopPanelEvent",
			onTransitionFinish: "stopPanelEvent",
			ondragstart	      : "stopPanelEvent",
			ondrag            : "stopPanelEvent",
			ondragfinish      : "stopPanelEvent",
			components: [
				{components: [
					{kind: "Phobos"}
				]},
				{components: [
					{kind: "Deimos", onCloseDesigner: "closeDesigner"}
				]}
			]
		}
	],
	events: {
		onRegisterMe: "",
		onMovePanel:"",
		onSavePreviewAction:"",
		onDesignerBroken: "",
		onFileEdited:"_fileEdited"
	},
	published: {
		panelIndex: 2,
		aceActive: true
	},
	handlers: {
		onAceFocus: "aceFocus"
	},
	create: function() {
		this.inherited(arguments);
		this.doRegisterMe({name:"developmentPanel", reference:this});
	},
	activePanel : function(){
		this.doMovePanel({panelIndex:this.panelIndex});
	},
	stopPanelEvent: function(){
		return true;
	},
	fileMenuItemSelected: function(inSender, inEvent) {
		ComponentsRegistry.getComponent("phobos").fileMenuItemSelected(inSender, inEvent);
	},
	editorSettings: function(){
		ComponentsRegistry.getComponent("phobos").editorSettings();
	},
	newKindAction: function() {
		ComponentsRegistry.getComponent("phobos").newKindAction();
	},
	kindSelected: function(inSender, inEvent) {
		ComponentsRegistry.getComponent("deimos").kindSelected(inSender, inEvent);
	},
	designerAction: function() {
		if(ComponentsRegistry.getComponent("phobos").editorUserSyntaxError() !== 0)
		{
			this.userSyntaxErrorPop();
		}
		else
		{
			ComponentsRegistry.getComponent("phobos").designerAction();
			this.manageControls(true);
		}
	},
	enableDesignerButton: function(enable) {
		this.$.designerButton.setShowing(enable);
		this.$.designerButtonBroken.setShowing(! enable);
	},
	userSyntaxErrorPop: function(){
		this.doError({msg: $L("Designer cannot work on a file with a syntax error. Please fix the error highlighted in code editor before launching the designer."), title: $L("Syntax Error")});
	},
	closeDesignerAction: function(){
		ComponentsRegistry.getComponent("deimos").closeDesignerAction();
		this.aceFocus();
	},
	/**
	 * Change controls on the panel top toolbar
	 *
	 * @private
	 * @param {boolean} designer, designer = true if designer's controls should be available
	 */
	manageControls: function(designer){
		this.setAceActive(!designer);
		this.$.editorControls.setShowing(!designer);
		this.$.deimosControls.setShowing(designer);
		this.$.toolbar.resized();
	},
	switchGrabberDirection: function(active){
		this.$.aresGrabberDirection.switchGrabberDirection(active);
	},
	addPreviewTooltip: function(message){
		this.$.previewTooltip.setContent(message);
	},
	updateDeimosLabel: function(edited) {
		if (edited) {
			this.$.docLabel.setContent("Deimos *");
		} else {
			this.$.docLabel.setContent("Deimos");
		}
		this.$.toolbar.resized();
	},
	aceFocus: function(){
		if(this.getAceActive()){
			ComponentsRegistry.getComponent("phobos").focusEditor();
		}
	},
	showErrorTooltip: function(inSender, inEvent){
		this.$.designerTooltipBroken.reset("Designer");
		this.$.designerButtonBroken.setDisabled(false);
		this.$.designerTooltipBroken.raise(inEvent);
	},
	resetErrorTooltip: function(){
		this.$.designerTooltipBroken.reset("Designer");
		this.$.designerButtonBroken.setDisabled(true);
	},
	getErrorFromDesignerBroken: function(){
		return this.$.designerTooltipBroken.error;
	},
	_fileEdited: function(){
		ComponentsRegistry.getComponent("developmentController")._fileEdited();
	}
});

enyo.kind({
	name: "Ares.DevelopmentController",
	kind: "enyo.Component",

	events: {
		onRegisterMe: "",
		onNewActiveDocument: "", // to preserve legacy in Ares.js
	},

	debug: false,

	create: function() {
		this.inherited(arguments);

		// Setup this.trace() function according to this.debug value
		ares.setupTraceLogger(this);

		this.doRegisterMe({name:"developmentController", reference:this});
	},

	activeDocument: null,

	switchToDocument: function(newDoc) {
		// safety net
		if ( ! newDoc ) {
			if  (this.debug) { throw("File ID " + newDoc + " not found in cache!");}
			else             { alert("File ID not found in cache!");}
			return;
		}

		var oldDoc = this.activeDocument ; // may be undef when a project is closed
		var newName = newDoc.getProjectData().getName() ;
		this.trace("switch " + (oldDoc ? "from " + oldDoc.getId() + " " : " ")
				   + "to " + newDoc.getId() );

		//select project if the file(d) comes from another project then the previous file
		if (!oldDoc || oldDoc.getProjectData().getName() !== newName){
			this.trace("also switch project "
					   + (oldDoc ? "from " + oldDoc.getProjectData().getName()  + " " : " ")
					   + ' to ' + newDoc.getProjectData().getName());
			var project = Ares.Workspace.projects.get(newDoc.getProjectData().id);
			// switch document is done in the callback
			ComponentsRegistry.getComponent("projectList")
				.selectInProjectList(project, this._switchDoc.bind(this,newDoc));
		}
		else {
			this._switchDoc(newDoc);
		}

	},

	// switch Phobos or Deimos to new document
	_switchDoc: function(newDoc) {
		var oldDoc = this.activeDocument ;
		var currentIF = newDoc.getCurrentIF();
		this.trace("switch " + (oldDoc ? "from " + oldDoc.getId()  + " " : " ")
				   + ' to ' + newDoc.getId() + " IF is " + currentIF );
		// We no longer save the data as the ACE edit session will keep the data for us
		if (!oldDoc || newDoc !== oldDoc) {
			ComponentsRegistry.getComponent("phobos").openDoc(newDoc);
		}
		this.activeDocument = newDoc;
		var developmentPanel = ComponentsRegistry.getComponent("developmentPanel");
		developmentPanel.addPreviewTooltip("Preview " + newDoc.getProjectData().id);

		if (currentIF === 'code') {
			developmentPanel.$.panels.setIndex(this.phobosViewIndex);
			developmentPanel.manageControls(false);
		} else {
			ComponentsRegistry.getComponent("phobos").designerAction();
			developmentPanel.manageControls(true);
		}
		this._fileEdited();
		ComponentsRegistry.getComponent("documentToolbar").activateFileWithId(newDoc.getId());
		this.doNewActiveDocument({ doc: this.activeDocument} );
	},
	_fileEdited: function() {
		ComponentsRegistry.getComponent("developmentPanel").updateDeimosLabel(this.activeDocument.getEdited());
	},

});

/**
	Ares.FileMenu extends _onyx.MenuDecorator_. This contains the various drop-down options (save, close, etc.) in our file menu
*/
enyo.kind({
	name: "Ares.FileMenu",
	kind: "onyx.MenuDecorator",
	classes:"aresmenu ares-right-margin ares-left-margin",
	events: {
		onAceFocus: ""
	},
	components: [
		{tag:"button", content: "File"},
		{kind: "onyx.Menu", floating: true, classes:"sub-aresmenu", maxHeight: "100%", components: [
			{name: "saveButton", value: "saveDocAction", classes:"aresmenu-button", components: [
				{kind: "onyx.IconButton", src: "$phobos/assets/images/menu-icon-save-darken.png"},
				{content: $L("Save")}
			]},
			{name: "saveAsButton", value: "saveAsDocAction", classes:"aresmenu-button", components: [
				{kind: "onyx.IconButton", src: "$phobos/assets/images/menu-icon-save-darken.png"},
				{content: $L("Save as...")}
			]},
			{classes: "onyx-menu-divider"},
			{name: "closeButton", value: "closeDocAction", classes:"aresmenu-button", components: [
				{kind: "onyx.IconButton", src: "$phobos/assets/images/menu-icon-stop.png"},
				{content: $L("Close")}
			]},
			{name: "closeAllButton", value: "closeAllDocAction", classes:"aresmenu-button", components: [
				{kind: "onyx.IconButton", src: "$phobos/assets/images/menu-icon-stop.png"},
				{content: $L("Close All")}
			]}
		]}
	]
});
<|endoftext|>


<commit_before>AFRAME.registerComponent('shape-swap', {
  schema: {
    on: {type: 'string'},
    target: {type: 'selector'},
    shape: {type: 'string'},
    size: {type: 'string'}
  },

  init: function () {
    var data = this.data;
    var el = this.el;

    el.addEventListener(data.on, function () {
      data.target.setAttribute('geometry', {primitive: data.shape, size: data.size});
    });
  }
});
<commit_msg>fixed sizes<commit_after>AFRAME.registerComponent('shape-swap', {
  schema: {
    on: {type: 'string'},
    target: {type: 'selector'},
    shape: {type: 'string'},
    size: {type: 'string'}
  },

  init: function () {
    var data = this.data;
    var el = this.el;

    el.addEventListener(data.on, function () {
      var size = data.size.split(" ");
      var width = size[0];
      var height = size[1];
      var depth = size[2];

      data.target.setAttribute('geometry', {primitive: data.shape, width: width, depth: depth, height: height});
    });
  }
});
<|endoftext|>


<commit_before>/*
    Copyright (c) 2007 rPath, Inc.
    All Rights Reserved
*/

var RDT_STRING = 0;
var RDT_BOOL = 1;
var RDT_INT = 2;
var RDT_ENUM = 3;
var RDT_TROVE = 4;

var builds = new Array();
var uniqId = 0;

function Build(baseId, data, hideOnCancel) {
    this.baseId = baseId;
    this.data = data;
    this.hideOnCancel = hideOnCancel;
    bindMethods(this);

    for(key in this.data) {
        if(this.data.hasOwnProperty(key))
            this.settings[key] = this.data[key][1];
    }
}

Build.prototype.settings = new Array();

Build.prototype.createRow = function(key, dataRow) {
    var tr = TR();

    var name = this.baseId + key;
    switch(dataRow[0]) {

    case RDT_STRING:
    case RDT_INT:
        appendChildNodes(tr, TD({}, LABEL({'for': name}, dataRow[2])));
        appendChildNodes(tr, TD({}, INPUT({'class': 'text', 'type': 'text', 'name': name, 'id': name, 'value': dataRow[1]})));
        break;
    case RDT_BOOL:
        var td = TD();
        appendChildNodes(td, INPUT({'class': 'reversed', 'value': '1', 'id': name, 'name': name, 'type': 'checkbox'}));
        appendChildNodes(td, LABEL({'for': name}, dataRow[2]));
        appendChildNodes(tr, TD({}), td);
        break;
    case RDT_ENUM:
        appendChildNodes(tr, TD({}, LABEL({'for': name}, dataRow[2])));
        var select = SELECT({'name': name, 'id': name});
        logDebug(dataRow[3]);
        for(enumPrompt in dataRow[3]) {
            var optionDict = {'value': dataRow[3][enumPrompt]};
            if(dataRow[1] == dataRow[3][enumPrompt]) {
                optionDict['selected'] = 'selected';
            }
            appendChildNodes(select, OPTION(optionDict, enumPrompt));
        }

        appendChildNodes(tr, TD({}, select));
        break;
    default:
    }
    return tr;
}

Build.prototype.createEditor = function() {
    var table = TABLE({'class': 'buildDefs', 'id': 'edit_' + this.baseId});
    hideElement(table);
    for(var key in this.data) {
        if(this.data.hasOwnProperty(key))
            appendChildNodes(table, this.createRow(key, this.data[key]));
    }

    var cancel = BUTTON({'style':'margin-right: 24px;'}, "Cancel");
    var save = BUTTON({}, "Save");

    connect(cancel, "onclick", this.cancel);
    connect(save, "onclick", this.save);

    appendChildNodes(table, TR({'class': 'dialogButtons'}, TD({'colspan':'2'},
        save, cancel)));

    this.editor = table;
}

Build.prototype.cancel = function() {
    if(this.hideOnCancel) {
        hideElement(this.editor);
    } else {
        templateDiv = DIV({'id': 'newType'});
        $("newBuildType").disabled = false;
        $("newBuildButton").disabled = false;

        swapDOM(this.editor, templateDiv);
    }
}

Build.prototype.save = function() {
    var buildSettings = new Array();

    // this is much harder than it should be
    // in python, it would look like this:
    // buildSettings = [dict([(d[0], d[1][1]) for d in build.data.items()]) for build in builds]
    //
    dataArray = map(function(x) { return x.data }, builds);
    for(i in dataArray) {
        if(dataArray.hasOwnProperty(i)) {
            d = {};
            for(j in dataArray[i]) {
                if(dataArray[i].hasOwnProperty(j)) {
                    d[j] = dataArray[i][j][1];
                }
            }
            buildSettings = buildSettings.concat(d);
        }
    }

    replaceChildNodes($('showJson'), buildSettings.toJSONString());
    this.cancel();
}

function addNew() {
    uniqId++;

    x = $("newBuildType");
    buildType = x.options[x.selectedIndex].value;
    newBuild = new Build(uniqId, defaultBuildOpts[buildType], false);
    $("newBuildType").disabled = true;
    $("newBuildButton").disabled = true;

    newBuild.createEditor();
    showElement(newBuild.editor);
    swapDOM($("newType"), newBuild.editor);
}

function showEdit(baseId) {
    showElement($(baseId));
}

function addExisting(baseId, data) {
    newBuild = new Build(baseId, defaultBuildOpts[data['type']], true);
    newBuild.createEditor();
    swapDOM($('edit_' + baseId), newBuild.editor);
    builds = builds.concat(newBuild);
    uniqId = baseId;
1;3B
}
<commit_msg>generalize hideOnCancel param for builddefs.js<commit_after>/*
    Copyright (c) 2007 rPath, Inc.
    All Rights Reserved
*/

var RDT_STRING = 0;
var RDT_BOOL = 1;
var RDT_INT = 2;
var RDT_ENUM = 3;
var RDT_TROVE = 4;

var builds = new Array();
var uniqId = 0;

function Build(baseId, data, buildType, existing) {
    this.baseId = baseId;
    this.data = data;
    this.buildType = buildType;
    this.existing = existing;
    bindMethods(this);

    for(key in this.data) {
        if(this.data.hasOwnProperty(key))
            this.settings[key] = this.data[key][1];
    }
}

Build.prototype.settings = new Array();

Build.prototype.createRow = function(key, dataRow) {
    var tr = TR();

    var name = this.baseId + key;
    switch(dataRow[0]) {

    case RDT_STRING:
    case RDT_INT:
        appendChildNodes(tr, TD({}, LABEL({'for': name}, dataRow[2])));
        appendChildNodes(tr, TD({}, INPUT({'class': 'text', 'type': 'text', 'name': name, 'id': name, 'value': dataRow[1]})));
        break;
    case RDT_BOOL:
        var td = TD();
        appendChildNodes(td, INPUT({'class': 'reversed', 'value': '1', 'id': name, 'name': name, 'type': 'checkbox'}));
        appendChildNodes(td, LABEL({'for': name}, dataRow[2]));
        appendChildNodes(tr, TD({}), td);
        break;
    case RDT_ENUM:
        appendChildNodes(tr, TD({}, LABEL({'for': name}, dataRow[2])));
        var select = SELECT({'name': name, 'id': name});
        logDebug(dataRow[3]);
        for(enumPrompt in dataRow[3]) {
            var optionDict = {'value': dataRow[3][enumPrompt]};
            if(dataRow[1] == dataRow[3][enumPrompt]) {
                optionDict['selected'] = 'selected';
            }
            appendChildNodes(select, OPTION(optionDict, enumPrompt));
        }

        appendChildNodes(tr, TD({}, select));
        break;
    default:
    }
    return tr;
}

Build.prototype.createEditor = function() {
    var table = TABLE({'class': 'buildDefs', 'id': 'edit_' + this.baseId});
    hideElement(table);
    for(var key in this.data) {
        if(this.data.hasOwnProperty(key))
            appendChildNodes(table, this.createRow(key, this.data[key]));
    }

    var cancel = BUTTON({'style':'margin-right: 24px;'}, "Cancel");
    var save = BUTTON({}, "Save");

    connect(cancel, "onclick", this.cancel);
    connect(save, "onclick", this.save);

    appendChildNodes(table, TR({'class': 'dialogButtons'}, TD({'colspan':'2'},
        save, cancel)));

    this.editor = table;
}

Build.prototype.cancel = function() {
    if(this.existing) {
        hideElement(this.editor);
    } else {
        templateDiv = DIV({'id': 'newType'});
        $("newBuildType").disabled = false;
        $("newBuildButton").disabled = false;

        swapDOM(this.editor, templateDiv);
    }
}

Build.prototype.save = function() {
    var buildSettings = new Array();

    if(!this.existing) {
        builds = builds.concat(this);
    }

    // this is much harder than it should be
    // in python, it would look like this:
    // buildSettings = [dict([(d[0], d[1][1]) for d in build.data.items()]) for build in builds]
    //
    dataArray = map(function(x) { return x.data }, builds);
    for(i in dataArray) {
        if(dataArray.hasOwnProperty(i)) {
            d = {};
            for(j in dataArray[i]) {
                if(dataArray[i].hasOwnProperty(j)) {
                    d[j] = dataArray[i][j][1];
                }
            }
            buildSettings = buildSettings.concat(d);
        }
    }

    replaceChildNodes($('showJson'), buildSettings.toJSONString());
    this.cancel();
}

function addNew() {
    uniqId++;

    x = $("newBuildType");
    buildType = x.options[x.selectedIndex].value;
    newBuild = new Build(uniqId, defaultBuildOpts[buildType], false);
    $("newBuildType").disabled = true;
    $("newBuildButton").disabled = true;

    newBuild.createEditor();
    showElement(newBuild.editor);
    swapDOM($("newType"), newBuild.editor);
}

function showEdit(baseId) {
    showElement($(baseId));
}

function addExisting(baseId, data) {
    newBuild = new Build(baseId, defaultBuildOpts[data['type']], true);
    newBuild.createEditor();
    swapDOM($('edit_' + baseId), newBuild.editor);
    builds = builds.concat(newBuild);
    uniqId = baseId;
}
<|endoftext|>


<commit_before>/* export Toggles */

/* globals $, jQuery */
class Toggles {

    /**
     * Construct Toggles
     * @return {Toggles}
     */
    constructor(adminController) {

        adminController
            .onRefreshUi((e, domElement) => {
                this.init(domElement);
            })
            .onDestroyUi((e, domElement) => {
                this.destroy(domElement);
            });

        return this;
    }

    // --------------------------------------------------------------------------

    /**
     * Inits Toggles
     * @param {HTMLElement} domElement
     * @returns {Toggles}
     */
    init(domElement) {
        $('.form-bool:not(.toggled)', domElement)
            .each(function() {
                $(this)
                    .data(
                        'instance',
                        new ToggleInstance($(this))
                    );
            });

        return this;
    }

    // --------------------------------------------------------------------------

    /**
     * Destroys Toggle instances contained within the given DOM element
     * @param domElement
     * @returns {Wysiwyg}
     */
    destroy(domElement) {
        $('.form-bool.toggled', domElement)
            .each((index, element) => {
                $(element)
                    .data('instance')
                    .destroy();
            });
        return this;
    }
}

class ToggleInstance {

    /**
     * Construct ToggleInstance
     * @param container
     */
    constructor(container) {

        this.container = container;
        this.checkbox = this.container.next('input[type=checkbox]');
        this.is_readonly = this.checkbox.hasClass('readonly');
        this.width = this.checkbox.data('toggle-width') || '100px';
        this.height = this.checkbox.data('toggle-height') || '30px';
        this.text_on = this.checkbox.data('text-on') || 'ON';
        this.text_off = this.checkbox.data('text-off') || 'OFF';

        this.checkbox.hide();
        this.container
            .addClass('toggled')
            .css({
                'width': this.width,
                'height': this.height,
                'text-align': 'center'
            })
            .toggles({
                'checkbox': this.checkbox,
                'click': !this.is_readonly,
                'drag': !this.is_readonly,
                'clicker': this.checkbox,
                'on': this.checkbox.is(':checked'),
                'text': {
                    'on': this.text_on,
                    'off': this.text_off
                }
            })
            .on('toggle', (e, value) => {
                //  Proxy the toggle event to the checkbox as well
                this.checkbox.trigger('toggle', [value]);
            });
    }

    // --------------------------------------------------------------------------

    destroy() {
        this.container
            .empty()
            .removeClass('toggled')
            .removeAttr('style');
        this.checkbox
            .show();
    }
}

export default Toggles;
<commit_msg>Triggering a `change` event when a boolean is toggled<commit_after>/* export Toggles */

/* globals $, jQuery */
class Toggles {

    /**
     * Construct Toggles
     * @return {Toggles}
     */
    constructor(adminController) {

        adminController
            .onRefreshUi((e, domElement) => {
                this.init(domElement);
            })
            .onDestroyUi((e, domElement) => {
                this.destroy(domElement);
            });

        return this;
    }

    // --------------------------------------------------------------------------

    /**
     * Inits Toggles
     * @param {HTMLElement} domElement
     * @returns {Toggles}
     */
    init(domElement) {
        $('.form-bool:not(.toggled)', domElement)
            .each(function() {
                $(this)
                    .data(
                        'instance',
                        new ToggleInstance($(this))
                    );
            });

        return this;
    }

    // --------------------------------------------------------------------------

    /**
     * Destroys Toggle instances contained within the given DOM element
     * @param domElement
     * @returns {Wysiwyg}
     */
    destroy(domElement) {
        $('.form-bool.toggled', domElement)
            .each((index, element) => {
                $(element)
                    .data('instance')
                    .destroy();
            });
        return this;
    }
}

class ToggleInstance {

    /**
     * Construct ToggleInstance
     * @param container
     */
    constructor(container) {

        this.container = container;
        this.checkbox = this.container.next('input[type=checkbox]');
        this.is_readonly = this.checkbox.hasClass('readonly');
        this.width = this.checkbox.data('toggle-width') || '100px';
        this.height = this.checkbox.data('toggle-height') || '30px';
        this.text_on = this.checkbox.data('text-on') || 'ON';
        this.text_off = this.checkbox.data('text-off') || 'OFF';

        this.checkbox.hide();
        this.container
            .addClass('toggled')
            .css({
                'width': this.width,
                'height': this.height,
                'text-align': 'center'
            })
            .toggles({
                'checkbox': this.checkbox,
                'click': !this.is_readonly,
                'drag': !this.is_readonly,
                'clicker': this.checkbox,
                'on': this.checkbox.is(':checked'),
                'text': {
                    'on': this.text_on,
                    'off': this.text_off
                }
            })
            .on('toggle', (e, value) => {
                //  Proxy the toggle event to the checkbox as well
                this.checkbox.trigger('toggle', [value]).trigger('change');
            });
    }

    // --------------------------------------------------------------------------

    destroy() {
        this.container
            .empty()
            .removeClass('toggled')
            .removeAttr('style');
        this.checkbox
            .show();
    }
}

export default Toggles;
<|endoftext|>


<commit_before>class Travel {
    constructor (game) {
        this.game = game
    }

    init(player, road, map) {

		this.player = player
        this.map = map

		console.log("cf=" + road.cf.name + ",co=" + road.co.name + ",player.cityName=" + player.cityName);
		if ( road.cf.name == player.cityName ) {
			this.comingFrom = road.co;
			this.goingTo = road.cf;
		} else {
			this.comingFrom = road.cf;
			this.goingTo = road.co;
		}

		//pick up packages
		while ( this.comingFrom.packages.length > 0 && player.packages.length < player.stats.carryingCapacity ) {
			this.player.packages.push(this.comingFrom.packages.pop());
		}

		//deliver packages
		this.events = this.generateEvents(road.treachery, road.length)
		for ( var idx in player.packages ) {
			if ( player.packages[idx].destination == this.goingTo.name ) {
				this.events.push(new TravelEvent({
					text: "You deliver a package to " + this.goingTo.name + ".",
					money: player.packages[idx].bounty
				}));
				player.packages.splice(idx,1); //remove 1 element from player.packages, starting at element idx. neat!
			}
		}

    }

    preload () {
        this.game.load.image('t-sky', 'assets/sprites/travel-sky-1.png')
        this.game.load.image('t-bg', 'assets/sprites/travel-bg-1.png')
        this.game.load.image('t-info', 'assets/sprites/travel-info.png')
    }
    create () {

        this.sky = this.game.add.sprite(0, 0, 't-sky')
        this.sky.scale.setTo(4, 4)
        this.sky.smoothed = false

        this.background = this.game.add.sprite(0, 0, 't-bg')
        this.background.scale.setTo(4, 4)
        this.background.smoothed = false

        this.info = this.game.add.sprite(0, 0, 't-info')
        this.info.scale.setTo(4, 4)
        this.info.smoothed = false

        this.infoText = this.game.add.text(
				80,
				480,
				'You and your jockey leave ' + this.comingFrom.name + '...',
				{ font: 'Inconsolata, monospace', fill: '#5a3404', stroke: '#333333', fontSize: '30px', wordWrap: true, wordWrapWidth: 800 }
		);

        this.horse = this.game.add.sprite(120, 160, 'horse', 0)
        this.horse.animations.add('running')
        this.horse.animations.play('running', 30, true)
        this.horse.scale.x *= -1
        this.horse.scale.setTo(-2, 2)

        this.interval = Math.floor(this.game.camera.width / (this.events.length + 1))
        this.intervalIndex = 1 // 1-indexed

        this.game.input.keyboard.onUpCallback = function (e) {
            if(this.horse.x < this.interval * this.intervalIndex) return

            if(e.keyCode === Phaser.Key.SPACEBAR) {
                this.intervalIndex++
                this.horse.animations.play('running', 30, true)
            }
        }.bind(this)
        this.game.input.onTap.add(function (e) {
            if(this.horse.x < this.interval * this.intervalIndex) return

            this.horse.animations.play('running', 30, true)
            this.intervalIndex++
        }, this);

        this.timer = this.game.time.create(false)
        this.timer.loop(Start.FADE_TIMEOUT, this.goToOverworld.bind(this))

        this.overlay = this.game.add.graphics(0, 0)
        this.overlay.opacity = 0
    }
    update () {
        if(this.horse.x < this.interval * this.intervalIndex) {
            if(this.intervalIndex - 1 === this.events.length + 1) {
                if(this.overlay.opacity === 0)
                    this.goToOverworld()
                else return
            }
            this.horse.x += 4
            this.background.x -= 8
            this.sky.x -= 4
        }
        else {
            if(this.horse.animations.getAnimation('running').isPlaying) {
                if(typeof this.events[this.intervalIndex - 1] !== 'undefined') {
                    var event = this.events[this.intervalIndex - 1]
                    this.infoText.text = event.text

                    console.log(this.player)
                    console.log(event.effects)

                    if(typeof event.effects.health !== 'undefined')
                        this.player.health += event.effects.health
                    if(typeof event.effects.money !== 'undefined')
                        this.player.money += event.effects.money

                    if(this.player.health < 0)
                        this.game.state.start('game-over')
                    console.log(this.player)
                }
                else if(this.intervalIndex - 1 === this.events.length)
                    this.infoText.text = '...and the lonely road gives way to ' + this.goingTo.name  + '.'

                this.horse.animations.stop()
            }
        }
    }
    render () {
        this.overlay.clear()
        this.overlay.beginFill(0x000000, this.overlay.opacity)
        this.overlay.moveTo(0, 0)
        this.overlay.drawRect(0, 0, this.camera.width, this.camera.height)
        this.overlay.endFill()
    }
	generateEvents(treachery, weeks) {
		if ( typeof weeks === 'undefined' ) {
			weeks = 1;
		}

		var res = Array();

		for ( var i=0; i<weeks; i++ ) {
			//bandits
			if ( Math.random() < 0.05 ) {
				res.push(new TravelEvent({
					text: "\"Stick 'em up! This is a stick up!\"",
					health: this.player.stats.health * -0.1,
					money: this.player.money * -0.8
				}));
			}

			//snake bite
			if ( Math.random() < 0.20 ) {
				res.push(new TravelEvent({
					text: "You were bitten by a snake!",
					health: this.player.stats.health * -0.1
				}));
			}

			//trip
			if ( Math.random() < 0.20 ) {
				res.push(new TravelEvent({
					text: "You tripped due to your jockey's negligence.",
					health: this.player.stats.health * -0.05
				}));
			}

			//drop money
			if ( Math.random() < 0.10 ) {
				res.push(new TravelEvent({
					text: "Your jockey clumsily dropped some money on the ground.",
					money: this.player.money * 0.95
				}));
			}

			//rock lobster
			if ( Math.random() < 0.01 ) {
				res.push(new TravelEvent({
					text: "You ran into a rock... but it wasn't a rock!",
					health: this.player.stats.health * -0.02
				}));
			}
		}

		return res;

	}

    goToOverworld () {

        this.horse.animations.stop()

        if(this.overlay.opacity >= 1) {
            this.game.input.keyboard.onUpCallback = function () {}
            this.game.input.mouse.mouseUpCallback = function () {}
            this.game.state.start('overworld', true, false, this.map, this.player)
        }
        else this.overlay.opacity += 0.1

        this.timer.start()
    }
}
<commit_msg>don't drop anti-matter money on the ground<commit_after>class Travel {
    constructor (game) {
        this.game = game
    }

    init(player, road, map) {

		this.player = player
        this.map = map

		console.log("cf=" + road.cf.name + ",co=" + road.co.name + ",player.cityName=" + player.cityName);
		if ( road.cf.name == player.cityName ) {
			this.comingFrom = road.co;
			this.goingTo = road.cf;
		} else {
			this.comingFrom = road.cf;
			this.goingTo = road.co;
		}

		//pick up packages
		while ( this.comingFrom.packages.length > 0 && player.packages.length < player.stats.carryingCapacity ) {
			this.player.packages.push(this.comingFrom.packages.pop());
		}

		//deliver packages
		this.events = this.generateEvents(road.treachery, road.length)
		for ( var idx in player.packages ) {
			if ( player.packages[idx].destination == this.goingTo.name ) {
				this.events.push(new TravelEvent({
					text: "You deliver a package to " + this.goingTo.name + ".",
					money: player.packages[idx].bounty
				}));
				player.packages.splice(idx,1); //remove 1 element from player.packages, starting at element idx. neat!
			}
		}

    }

    preload () {
        this.game.load.image('t-sky', 'assets/sprites/travel-sky-1.png')
        this.game.load.image('t-bg', 'assets/sprites/travel-bg-1.png')
        this.game.load.image('t-info', 'assets/sprites/travel-info.png')
    }
    create () {

        this.sky = this.game.add.sprite(0, 0, 't-sky')
        this.sky.scale.setTo(4, 4)
        this.sky.smoothed = false

        this.background = this.game.add.sprite(0, 0, 't-bg')
        this.background.scale.setTo(4, 4)
        this.background.smoothed = false

        this.info = this.game.add.sprite(0, 0, 't-info')
        this.info.scale.setTo(4, 4)
        this.info.smoothed = false

        this.infoText = this.game.add.text(
				80,
				480,
				'You and your jockey leave ' + this.comingFrom.name + '...',
				{ font: 'Inconsolata, monospace', fill: '#5a3404', stroke: '#333333', fontSize: '30px', wordWrap: true, wordWrapWidth: 800 }
		);

        this.horse = this.game.add.sprite(120, 160, 'horse', 0)
        this.horse.animations.add('running')
        this.horse.animations.play('running', 30, true)
        this.horse.scale.x *= -1
        this.horse.scale.setTo(-2, 2)

        this.interval = Math.floor(this.game.camera.width / (this.events.length + 1))
        this.intervalIndex = 1 // 1-indexed

        this.game.input.keyboard.onUpCallback = function (e) {
            if(this.horse.x < this.interval * this.intervalIndex) return

            if(e.keyCode === Phaser.Key.SPACEBAR) {
                this.intervalIndex++
                this.horse.animations.play('running', 30, true)
            }
        }.bind(this)
        this.game.input.onTap.add(function (e) {
            if(this.horse.x < this.interval * this.intervalIndex) return

            this.horse.animations.play('running', 30, true)
            this.intervalIndex++
        }, this);

        this.timer = this.game.time.create(false)
        this.timer.loop(Start.FADE_TIMEOUT, this.goToOverworld.bind(this))

        this.overlay = this.game.add.graphics(0, 0)
        this.overlay.opacity = 0
    }
    update () {
        if(this.horse.x < this.interval * this.intervalIndex) {
            if(this.intervalIndex - 1 === this.events.length + 1) {
                if(this.overlay.opacity === 0)
                    this.goToOverworld()
                else return
            }
            this.horse.x += 4
            this.background.x -= 8
            this.sky.x -= 4
        }
        else {
            if(this.horse.animations.getAnimation('running').isPlaying) {
                if(typeof this.events[this.intervalIndex - 1] !== 'undefined') {
                    var event = this.events[this.intervalIndex - 1]
                    this.infoText.text = event.text

                    console.log(this.player)
                    console.log(event.effects)

                    if(typeof event.effects.health !== 'undefined')
                        this.player.health += event.effects.health
                    if(typeof event.effects.money !== 'undefined')
                        this.player.money += event.effects.money

                    if(this.player.health < 0)
                        this.game.state.start('game-over')
                    console.log(this.player)
                }
                else if(this.intervalIndex - 1 === this.events.length)
                    this.infoText.text = '...and the lonely road gives way to ' + this.goingTo.name  + '.'

                this.horse.animations.stop()
            }
        }
    }
    render () {
        this.overlay.clear()
        this.overlay.beginFill(0x000000, this.overlay.opacity)
        this.overlay.moveTo(0, 0)
        this.overlay.drawRect(0, 0, this.camera.width, this.camera.height)
        this.overlay.endFill()
    }
	generateEvents(treachery, weeks) {
		if ( typeof weeks === 'undefined' ) {
			weeks = 1;
		}

		var res = Array();

		for ( var i=0; i<weeks; i++ ) {
			//bandits
			if ( Math.random() < 0.05 ) {
				res.push(new TravelEvent({
					text: "\"Stick 'em up! This is a stick up!\"",
					health: this.player.stats.health * -0.1,
					money: this.player.money * -0.8
				}));
			}

			//snake bite
			if ( Math.random() < 0.20 ) {
				res.push(new TravelEvent({
					text: "You were bitten by a snake!",
					health: this.player.stats.health * -0.1
				}));
			}

			//trip
			if ( Math.random() < 0.20 ) {
				res.push(new TravelEvent({
					text: "You tripped due to your jockey's negligence.",
					health: this.player.stats.health * -0.05
				}));
			}

			//drop money
			if ( Math.random() < 0.10 ) {
				res.push(new TravelEvent({
					text: "Your jockey clumsily dropped some money on the ground.",
					money: this.player.money * -0.05
				}));
			}

			//rock lobster
			if ( Math.random() < 0.01 ) {
				res.push(new TravelEvent({
					text: "You ran into a rock... but it wasn't a rock!",
					health: this.player.stats.health * -0.02
				}));
			}
		}

		return res;

	}

    goToOverworld () {

        this.horse.animations.stop()

        if(this.overlay.opacity >= 1) {
            this.game.input.keyboard.onUpCallback = function () {}
            this.game.input.mouse.mouseUpCallback = function () {}
            this.game.state.start('overworld', true, false, this.map, this.player)
        }
        else this.overlay.opacity += 0.1

        this.timer.start()
    }
}
<|endoftext|>


<commit_before>'use strict'

import * as types from '../constants/ActionTypes'

function findIndex (list, id) {
  let i = 0
  // TODO: most efficient search algo in production or use hashmap for exampe
  for (; i < list.length; i++) {
    if (list[i].id === id) break
  }
  return i
}

function pages (state = {
  isFetching: false,
  isCreating: false,
  isToggling: false,
  isDeleting: false,
  deletingPageId: -1,
  togglingPageId: '',
  createFormInputNameValue: '',
  items: []
}, action) {
  let index = null

  switch (action.type) {
    case types.REQUEST_PAGES:
      return Object.assign({}, state, {
        isFetching: true
      })
    case types.RECEIVE_PAGES:
      return Object.assign({}, state, {
        isFetching: false,
        items: action.pages
      })
    case types.CREATE_PAGE_REQUEST:
      return Object.assign({}, state, {
        createFormInputNameValue: action.name,
        isCreating: true
      })
    case types.CREATE_PAGE_FAILURE:
      return Object.assign({}, state, {
        isCreating: false
      })
    case types.CREATE_PAGE_SUCCESS:
      return Object.assign({}, state, {
        isCreating: false,
        createFormInputNameValue: '',
        items: [
          ...state.items,
          action.page
        ]
      })
    case types.TOGGLE_PUBLISH_REQUEST:
      return Object.assign({}, state, {
        togglingPageId: action.id,
        isToggling: true
      })
    case types.TOGGLE_PUBLISH_FAILURE:
      return Object.assign({}, state, {
        togglingPageId: '',
        isToggling: false
      })
    case types.TOGGLE_PUBLISH_SUCCESS:
      index = findIndex(state.items, action.page.id)
      return Object.assign({}, state, {
        togglingPageId: '',
        isToggling: false,
        items: [
          ...state.items.slice(0, index),
          action.page,
          ...state.items.slice(index + 1)
        ]
      })
    case types.DELETE_PAGE_REQUEST:
      return Object.assign({}, state, {
        deletingPageId: action.id,
        isDeleting: true
      })
    case types.DELETE_PAGE_FAILURE:
      return Object.assign({}, state, {
        deletingPageId: '',
        isDeleting: false
      })
    case types.DELETE_PAGE_SUCCESS:
      index = findIndex(state.items, action.page.id)
      return Object.assign({}, state, {
        deletingPageId: '',
        isDeleting: false,
        items: [
          ...state.items.slice(0, index),
          ...state.items.slice(index + 1)
        ]
      })
    default:
      return state
  }
}

export default pages
<commit_msg>Fix React PropsType deletingPageId cast issue<commit_after>'use strict'

import * as types from '../constants/ActionTypes'

function findIndex (list, id) {
  let i = 0
  // TODO: most efficient search algo in production or use hashmap for exampe
  for (; i < list.length; i++) {
    if (list[i].id === id) break
  }
  return i
}

function pages (state = {
  isFetching: false,
  isCreating: false,
  isToggling: false,
  isDeleting: false,
  deletingPageId: -1,
  togglingPageId: '',
  createFormInputNameValue: '',
  items: []
}, action) {
  let index = null

  switch (action.type) {
    case types.REQUEST_PAGES:
      return Object.assign({}, state, {
        isFetching: true
      })
    case types.RECEIVE_PAGES:
      return Object.assign({}, state, {
        isFetching: false,
        items: action.pages
      })
    case types.CREATE_PAGE_REQUEST:
      return Object.assign({}, state, {
        createFormInputNameValue: action.name,
        isCreating: true
      })
    case types.CREATE_PAGE_FAILURE:
      return Object.assign({}, state, {
        isCreating: false
      })
    case types.CREATE_PAGE_SUCCESS:
      return Object.assign({}, state, {
        isCreating: false,
        createFormInputNameValue: '',
        items: [
          ...state.items,
          action.page
        ]
      })
    case types.TOGGLE_PUBLISH_REQUEST:
      return Object.assign({}, state, {
        togglingPageId: action.id,
        isToggling: true
      })
    case types.TOGGLE_PUBLISH_FAILURE:
      return Object.assign({}, state, {
        togglingPageId: '',
        isToggling: false
      })
    case types.TOGGLE_PUBLISH_SUCCESS:
      index = findIndex(state.items, action.page.id)
      return Object.assign({}, state, {
        togglingPageId: '',
        isToggling: false,
        items: [
          ...state.items.slice(0, index),
          action.page,
          ...state.items.slice(index + 1)
        ]
      })
    case types.DELETE_PAGE_REQUEST:
      return Object.assign({}, state, {
        deletingPageId: action.id,
        isDeleting: true
      })
    case types.DELETE_PAGE_FAILURE:
      return Object.assign({}, state, {
        deletingPageId: -1,
        isDeleting: false
      })
    case types.DELETE_PAGE_SUCCESS:
      index = findIndex(state.items, action.page.id)
      return Object.assign({}, state, {
        deletingPageId: -1,
        isDeleting: false,
        items: [
          ...state.items.slice(0, index),
          ...state.items.slice(index + 1)
        ]
      })
    default:
      return state
  }
}

export default pages
<|endoftext|>


<commit_before>const Promise = require('bluebird')
const models = require('../../models')
const secrets = require('../../config/secrets')
const url = require('url')
const requestPromise = require('request-promise')
const roleExists = require('../roles').roleExists
const { userExists } = require('../users')
const memberExists = require('../members').memberExists

module.exports = Promise.method(function taskFetch (taskParams) {
  return models.Task.findOne({
    where: {
      id: taskParams.id
    },
    include: [
      models.User,
      {
        model: models.Order,
        include: [models.User]
      },
      {
        model: models.Assign,
        include: [models.User]
      },
      {
        model: models.Member,
        include: [models.User, models.Role]
      },
      {
        model: models.Offer,
        include: [models.User, models.Task]
      },
      {
        model: models.History
      }
    ]
  })
    .then(data => {
      const githubClientId = secrets.github.id
      const githubClientSecret = secrets.github.secret
      const issueUrl = data.dataValues.url
      const splitIssueUrl = url.parse(issueUrl).path.split('/')
      const userOrCompany = splitIssueUrl[1]
      const projectName = splitIssueUrl[2]
      const issueId = splitIssueUrl[4]

      switch (data.dataValues.provider) {
        case 'github':
          return requestPromise({
            uri: `https://api.github.com/repos/${userOrCompany}/${projectName}/issues/${issueId}?client_id=${githubClientId}&client_secret=${githubClientSecret}`,
            headers: {
              'User-Agent':
                'octonode/0.3 (https://github.com/pksunkara/octonode) terminal/0.0'
            }
          })
            .then(async response => {
              const issueDataJsonGithub = JSON.parse(response)

              const assigned = await models.Assign.findOne(
                {
                  where: {
                    id: data.assigned
                  },
                  include: [models.User]
                }
              ).catch(e => {})

              const role = await roleExists({ name: 'company_owner' })
              if (role.dataValues && role.dataValues.id) {
                const userInfo = await requestPromise({
                  uri: `https://api.github.com/users/${userOrCompany}?client_id=${githubClientId}&client_secret=${githubClientSecret}`,
                  headers: {
                    'User-Agent': 'octonode/0.3 (https://github.com/pksunkara/octonode) terminal/0.0'
                  }
                })
                const userInfoJSON = JSON.parse(userInfo)
                const userExist = await userExists({ email: userInfoJSON.email })
                if (userExist.dataValues && userExist.dataValues.id) {
                  const memberExist = await memberExists({ userId: userExist.dataValues.id, taskId: data.id })
                  if (memberExist.dataValues && memberExist.dataValues.id) {
                    // alerady member
                  }
                  else {
                    // add member
                    const task = await models.Task.findOne({
                      where: {
                        id: data.id
                      }
                    })
                    await task.createMember({ userId: userExist.dataValues.id, roleId: role.dataValues.id })
                  }
                }
                else {
                  // send an email
                }
              }

              const repoInfo = await requestPromise({
                uri: `${issueDataJsonGithub.repository_url}?client_id=${githubClientId}&client_secret=${githubClientSecret}`,
                headers: {
                  'User-Agent': 'octonode/0.3 (https://github.com/pksunkara/octonode) terminal/0.0'
                }
              })
              const repoInfoJSON = JSON.parse(repoInfo)
              const repoUrl = repoInfoJSON.html_url
              const ownerUrl = repoInfoJSON.owner.html_url

              const responseGithub = {
                id: data.dataValues.id,
                url: issueUrl,
                title: data.dataValues.title,
                value: data.dataValues.value || 0,
                deadline: data.dataValues.deadline,
                level: data.dataValues.level,
                status: data.dataValues.status,
                assigned: data.dataValues.assigned,
                assignedUser: assigned && assigned.dataValues.User.dataValues,
                userId: data.dataValues.userId,
                paid: data.dataValues.paid,
                transfer_id: data.dataValues.transfer_id,
                provider: data.dataValues.provider,
                metadata: {
                  id: issueId,
                  user: userOrCompany,
                  company: userOrCompany,
                  projectName: projectName,
                  repoUrl: repoUrl,
                  ownerUrl: ownerUrl,
                  labels: issueDataJsonGithub.labels,
                  issue: issueDataJsonGithub
                },
                orders: data.dataValues.Orders,
                assigns: data.dataValues.Assigns,
                members: data.dataValues.Members,
                offers: data.dataValues.Offers,
                histories: data.dataValues.Histories

              }

              if (!data.title && data.title !== issueDataJsonGithub.title) {
                /* eslint-disable no-unused-vars */
                data
                  .updateAttributes({ title: issueDataJsonGithub.title })
                  .then(task => responseGithub)
              }
              return responseGithub
            })
            .catch(e => {
              // eslint-disable-next-line no-console
              console.log('github response error')
              // eslint-disable-next-line no-console
              console.log(e)
              return data.dataValues
            })

        case 'bitbucket':
          return requestPromise({
            uri: `https://api.bitbucket.org/2.0/repositories/${userOrCompany}/${projectName}/issues/${issueId}`
          })
            .then(response => {
              const issueDataJsonBitbucket = JSON.parse(response)
              const responseBitbucket = {
                id: data.dataValues.id,
                url: issueUrl,
                title: data.dataValues.title,
                value: data.dataValues.value || 0,
                deadline: data.dataValues.deadline,
                status: data.dataValues.status,
                assigned: data.dataValues.assigned,
                userId: data.dataValues.userId,
                paid: data.dataValues.paid,
                transfer_id: data.dataValues.transfer_id,
                provider: data.dataValues.provider,
                metadata: {
                  id: issueId,
                  user: userOrCompany,
                  company: userOrCompany,
                  projectName: projectName,
                  provider: data.provider,
                  issue: {
                    state: issueDataJsonBitbucket.status,
                    body: issueDataJsonBitbucket.content.raw,
                    user: {
                      login: issueDataJsonBitbucket.reporter.username,
                      avatar_url: issueDataJsonBitbucket.reporter.links.avatar.href
                    }
                  }
                },
                orders: data.dataValues.Orders,
                assigns: data.dataValues.Assigns,
                members: data.dataValues.Members,
                offers: data.dataValues.Offers
              }

              if (!data.title && data.title !== issueDataJsonBitbucket.title) {
                /* eslint-disable no-unused-vars */
                data
                  .updateAttributes({ title: issueDataJsonBitbucket.title })
                  .then(task => responseBitbucket)
              }
              return responseBitbucket
            })
            .catch(e => {
              // eslint-disable-next-line no-console
              console.log('github response error')
              // eslint-disable-next-line no-console
              console.log(e)
              return data.dataValues
            })

        default:
          return data.dataValues
      }
    })
    .catch(error => {
      // eslint-disable-next-line no-console
      console.log(error)
      return false
    })
})
<commit_msg>changing the way we call user exists to try to fix an error<commit_after>const Promise = require('bluebird')
const models = require('../../models')
const secrets = require('../../config/secrets')
const url = require('url')
const requestPromise = require('request-promise')
const roleExists = require('../roles').roleExists
const { userExists } = require('../users')
const memberExists = require('../members').memberExists

module.exports = Promise.method(function taskFetch (taskParams) {
  return models.Task.findOne({
    where: {
      id: taskParams.id
    },
    include: [
      models.User,
      {
        model: models.Order,
        include: [models.User]
      },
      {
        model: models.Assign,
        include: [models.User]
      },
      {
        model: models.Member,
        include: [models.User, models.Role]
      },
      {
        model: models.Offer,
        include: [models.User, models.Task]
      },
      {
        model: models.History
      }
    ]
  })
    .then(data => {
      const githubClientId = secrets.github.id
      const githubClientSecret = secrets.github.secret
      const issueUrl = data.dataValues.url
      const splitIssueUrl = url.parse(issueUrl).path.split('/')
      const userOrCompany = splitIssueUrl[1]
      const projectName = splitIssueUrl[2]
      const issueId = splitIssueUrl[4]

      switch (data.dataValues.provider) {
        case 'github':
          return requestPromise({
            uri: `https://api.github.com/repos/${userOrCompany}/${projectName}/issues/${issueId}?client_id=${githubClientId}&client_secret=${githubClientSecret}`,
            headers: {
              'User-Agent':
                'octonode/0.3 (https://github.com/pksunkara/octonode) terminal/0.0'
            }
          })
            .then(async response => {
              const issueDataJsonGithub = JSON.parse(response)

              const assigned = await models.Assign.findOne(
                {
                  where: {
                    id: data.assigned
                  },
                  include: [models.User]
                }
              ).catch(e => {})

              const role = await roleExists({ name: 'company_owner' })
              if (role.dataValues && role.dataValues.id) {
                const userInfo = await requestPromise({
                  uri: `https://api.github.com/users/${userOrCompany}?client_id=${githubClientId}&client_secret=${githubClientSecret}`,
                  headers: {
                    'User-Agent': 'octonode/0.3 (https://github.com/pksunkara/octonode) terminal/0.0'
                  }
                })
                const userInfoJSON = JSON.parse(userInfo)
                const userExist = userExists && await userExists({ email: userInfoJSON.email })
                if (userExist.dataValues && userExist.dataValues.id) {
                  const memberExist = await memberExists({ userId: userExist.dataValues.id, taskId: data.id })
                  if (memberExist.dataValues && memberExist.dataValues.id) {
                    // alerady member
                  }
                  else {
                    // add member
                    const task = await models.Task.findOne({
                      where: {
                        id: data.id
                      }
                    })
                    await task.createMember({ userId: userExist.dataValues.id, roleId: role.dataValues.id })
                  }
                }
                else {
                  // send an email
                }
              }

              const repoInfo = await requestPromise({
                uri: `${issueDataJsonGithub.repository_url}?client_id=${githubClientId}&client_secret=${githubClientSecret}`,
                headers: {
                  'User-Agent': 'octonode/0.3 (https://github.com/pksunkara/octonode) terminal/0.0'
                }
              })
              const repoInfoJSON = JSON.parse(repoInfo)
              const repoUrl = repoInfoJSON.html_url
              const ownerUrl = repoInfoJSON.owner.html_url

              const responseGithub = {
                id: data.dataValues.id,
                url: issueUrl,
                title: data.dataValues.title,
                value: data.dataValues.value || 0,
                deadline: data.dataValues.deadline,
                level: data.dataValues.level,
                status: data.dataValues.status,
                assigned: data.dataValues.assigned,
                assignedUser: assigned && assigned.dataValues.User.dataValues,
                userId: data.dataValues.userId,
                paid: data.dataValues.paid,
                transfer_id: data.dataValues.transfer_id,
                provider: data.dataValues.provider,
                metadata: {
                  id: issueId,
                  user: userOrCompany,
                  company: userOrCompany,
                  projectName: projectName,
                  repoUrl: repoUrl,
                  ownerUrl: ownerUrl,
                  labels: issueDataJsonGithub.labels,
                  issue: issueDataJsonGithub
                },
                orders: data.dataValues.Orders,
                assigns: data.dataValues.Assigns,
                members: data.dataValues.Members,
                offers: data.dataValues.Offers,
                histories: data.dataValues.Histories

              }

              if (!data.title && data.title !== issueDataJsonGithub.title) {
                /* eslint-disable no-unused-vars */
                data
                  .updateAttributes({ title: issueDataJsonGithub.title })
                  .then(task => responseGithub)
              }
              return responseGithub
            })
            .catch(e => {
              // eslint-disable-next-line no-console
              console.log('github response error')
              // eslint-disable-next-line no-console
              console.log(e)
              return data.dataValues
            })

        case 'bitbucket':
          return requestPromise({
            uri: `https://api.bitbucket.org/2.0/repositories/${userOrCompany}/${projectName}/issues/${issueId}`
          })
            .then(response => {
              const issueDataJsonBitbucket = JSON.parse(response)
              const responseBitbucket = {
                id: data.dataValues.id,
                url: issueUrl,
                title: data.dataValues.title,
                value: data.dataValues.value || 0,
                deadline: data.dataValues.deadline,
                status: data.dataValues.status,
                assigned: data.dataValues.assigned,
                userId: data.dataValues.userId,
                paid: data.dataValues.paid,
                transfer_id: data.dataValues.transfer_id,
                provider: data.dataValues.provider,
                metadata: {
                  id: issueId,
                  user: userOrCompany,
                  company: userOrCompany,
                  projectName: projectName,
                  provider: data.provider,
                  issue: {
                    state: issueDataJsonBitbucket.status,
                    body: issueDataJsonBitbucket.content.raw,
                    user: {
                      login: issueDataJsonBitbucket.reporter.username,
                      avatar_url: issueDataJsonBitbucket.reporter.links.avatar.href
                    }
                  }
                },
                orders: data.dataValues.Orders,
                assigns: data.dataValues.Assigns,
                members: data.dataValues.Members,
                offers: data.dataValues.Offers
              }

              if (!data.title && data.title !== issueDataJsonBitbucket.title) {
                /* eslint-disable no-unused-vars */
                data
                  .updateAttributes({ title: issueDataJsonBitbucket.title })
                  .then(task => responseBitbucket)
              }
              return responseBitbucket
            })
            .catch(e => {
              // eslint-disable-next-line no-console
              console.log('github response error')
              // eslint-disable-next-line no-console
              console.log(e)
              return data.dataValues
            })

        default:
          return data.dataValues
      }
    })
    .catch(error => {
      // eslint-disable-next-line no-console
      console.log(error)
      return false
    })
})
<|endoftext|>