<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================
sc_require('views/button') ;
sc_require('views/separator') ;

/**
  @class SC.MenuItemView
  @extends SC.ButtonView
  @since SproutCore 1.0
*/
SC.MenuItemView = SC.View.extend( SC.ContentDisplay,
/** @scope SC.MenuItemView.prototype */{

  classNames: ['sc-menu-item'],

  /**
    @private
    @property
    @type {Boolean}
  */
  acceptsFirstResponder: YES,

  // ..........................................................
  // KEY PROPERTIES
  //
  /**
    The content object the menu view will display.

    @type Object
  */
  content: null,

  /**
    This returns true if the child view is a menu list view.
    This property can be over written to have other child views as well.

    @type Boolean
  */
  isSubMenuViewVisible: null,

  /**
    This property specifies whether this menu item is currently in focus

    @type Boolean
  */
  hasMouseExited: NO,

  /**
    This menu item's submenu, if it exists.

    @type SC.MenuView
  */
  subMenu: function() {
    var content = this.get('content'), menuItems;

    if (!content) return null;

    menuItems = content.get( this.get('parentMenu').itemSubMenuKey );
    if (menuItems) {
      if (SC.kindOf(menuItems, SC.MenuPane)) {
        return menuItems;
      } else {
        return SC.MenuPane.create({
          layout: { width: 200 },
          items: menuItems,
          isModal: NO,
          isSubMenu: YES,
          rootMenu: this.get('rootMenu') || this
        });
      }
    }

    return null;
  }.property('content').cacheable(),

  /**
    Whether or not this menu item has a submenu.

    @type Boolean
  */
  hasSubMenu: function() {
    return !!this.get('subMenu');
  }.property('subMenu').cacheable(),

  /**
    Fills the passed html-array with strings that can be joined to form the
    innerHTML of the receiver element.  Also populates an array of classNames
    to set on the outer element.

    @param {SC.RenderContext} context
    @param {Boolean} firstTime
    @returns {void}
  */
  render: function(context, firstTime) {
    var content = this.get('content') ;
    var key, val ;
    var menu = this.get('parentMenu');
    var itemWidth = this.get('itemWidth') || menu.layout.width ;
    var itemHeight = this.get('itemHeight') || 20 ;
    this.set('itemWidth',itemWidth) ;
    this.set('itemHeight',itemHeight) ;

    // Disable the menu item only if isEnabled is NO
    // if (content.get(menu.itemIsEnabledKey) === NO) {
    //   context.addClass('disabled') ;
    // }

    context = context.begin('a').attr('href', 'javascript:');

    if (content.get(menu.itemSeparatorKey)) {
      context.push('');
      context.addClass('disabled');
    } else {
      val = content.get(menu.itemIconKey);
      if (val) {
        this.renderImage(context, val);
        context.addClass('has-icon');
      }

      val = content.get(menu.itemTitleKey) || '';
      if (SC.typeOf(val) !== SC.T_STRING) val = val.toString();
      // TODO check localization setting
      this.renderLabel(context, val.loc());

      if (content.get(menu.itemCheckboxKey)) {
        context.push('

');
      }

      if (this.get('hasSubMenu')) {
        this.renderBranch(context);
      }

      val = content.get(menu.itemShortCutKey);
      if (val) {
        this.renderShortcut(context, val);
      }
    }

    context = context.end();

    //         // handle short cut keys
    //         if (this.getDelegateProperty('shortCutKey', del)) {
    //           key = this.getDelegateProperty('shortCutKey', del) ;
    //           val = (key && content) ? (content.get ? content.get(key) : content[key]) : null ;
    //           if (val) {
    //             this.renderShortcut(ic, val) ;
    //             ic.addClass('shortcutkey') ;
    //           }
    //         }
    //       }
    //     }
    //     ic.end() ;
  },

  /**
   Generates the image used to represent the image icon. override this to
   return your own custom HTML

   @param {SC.RenderContext} context the render context
   @param {String} the source path of the image
   @returns {void}
  */
  renderImage: function(context, image) {
    // get a class name and url to include if relevant

    var url, className ;
    if (image && SC.ImageView.valueIsUrl(image)) {
      url = image ;
      className = '' ;
    } else {
      className = image ;
      url = SC.BLANK_IMAGE_URL;
    }
    // generate the img element...
    context.begin('img').addClass('image').addClass(className).attr('src', url).end() ;
  },

  /**
   Generates the label used to represent the menu item. override this to
   return your own custom HTML

   @param {SC.RenderContext} context the render context
   @param {String} menu item name
   @returns {void}
  */

  renderLabel: function(context, label) {
    context.push(""+label+"") ;
  },

  /**
   Generates the string used to represent the branch arrow. override this to
   return your own custom HTML

   @param {SC.RenderContext} context the render context
   @returns {void}
  */

  renderBranch: function(context) {
    context.push('>') ;
  },

  /**
   Generates the string used to represent the short cut keys. override this to
   return your own custom HTML

   @param {SC.RenderContext} context the render context
   @param {String} the shortcut key string to be displayed with menu item name
   @returns {void}
  */
  renderShortcut: function(context, shortcut) {
    context.push('' + shortcut + '') ;
  },

  /**
    This method is used to fetch the Menu Item View to which the
    Parent Menu Pane is anchored
    to

    @param {}
    @returns MenuPane
  */
  getAnchor: function() {
    var anchor = this.get('anchor') ;
    if(anchor && anchor.kindOf && anchor.kindOf(SC.MenuItemView)) return anchor ;
    return null ;
  },

  isCurrent: NO,

  /**
    This method checks if the menu item is a separator.

    @param {}
    @returns Boolean
  */
  isSeparator: function() {
    return this.getContentProperty('itemSeparatorKey') === NO;
  }.property().cacheable('content'),

  /**
    Checks if a menu is a sub menu, during branching.

    @param {}
    @returns MenuPane
  */
  isSubMenuAMenuPane: function() {
    var subMenu = this.get('subMenu');
    if(subMenu && subMenu.kindOf(SC.MenuPane)) return subMenu ;
    return NO ;
  },

  /**
    This method will check whether the current Menu Item is still
    selected and then create a submenu accordignly.

    @param {}
    @returns void
  */
  showSubMenu: function() {
    var subMenu = this.get('subMenu') ;
    if(subMenu) {
      subMenu.set('anchor', this) ;
      subMenu.popup(this,[0,0,0]) ;
    }
  },

  isEnabled: function() {
    return this.getContentProperty('itemIsEnabledKey') !== NO;
  }.property().cacheable('content'),

  getContentProperty: function(property) {
    var content = this.get('content'),
        menu = this.get('parentMenu');

    if (content) {
      return content.get(menu.get(property));
    }
  },

  //..........................................
  //Mouse Events Handling
  //..........................................

  // to check the 'isMouseDown' property of the anchor
  isAnchorMouseDown: NO,

  mouseUp: function(evt) {
    // SproutCore's event system will deliver the mouseUp event to the view
    // that got the mouseDown event, but for menus we want to track the mouse,
    // so we'll do our own dispatching.
    var menu = this.get('parentMenu'), currentMenuItem, action;

    if (menu) {
      currentMenuItem = menu.get('currentMenuItem') ;
      currentMenuItem.performAction();
    }

    return YES ;
  },

  performAction: function(skipFlash) {
    var action = this.getContentProperty('itemActionKey'),
        target = this.getContentProperty('itemTargetKey'), menu;

    this._flashCounter = 0;
    if (skipFlash) {
      this.getPath('pane.rootResponder').sendAction(action, target, this, this.get('pane'));

      menu = this.get('parentMenu');
      if (menu.get('isSubMenu')) menu.get('rootPane').remove();
      else menu.remove();
    } else {
      this.invokeLater(this.flashHighlight, 50);
    }
  },

  flashHighlight: function() {
    var flashCounter = this._flashCounter, layer = this.$();
    if (flashCounter % 2 === 0) {
      layer.addClass('focus');
    } else {
      layer.removeClass('focus');
    }

    if (flashCounter > 4) {
      this.performAction(YES);
    } else {
      this.invokeLater(this.flashHighlight, 75);
      this._flashCounter++;
    }
  },

  /** @private*/
  mouseDown: function(evt) {
    return YES ;
  },

  /** @private
    This has been over ridden from button view to prevent calling of render
    method (When isActive property is changed).
    Also based on whether the menu item has a sub Branch we create a sub Menu

    @returns Boolean
  */
  mouseEntered: function(evt) {
    var menu = this.get('parentMenu'), content = this.get('content');
    menu.set('mouseHasEntered', YES);
    menu.setIfChanged('currentMenuItem', this);

    if(this.get('hasSubMenu')) {
      this.invokeLater(this.showSubMenu(),100) ;
    }
	  return YES ;
  },

  /** @private
    Set the focus based on whether the current Menu item is selected or not.

    @returns Boolean
  */
  mouseExited: function(evt) {
    var subMenu, parentMenu;

    if (this.get('hasSubMenu')) {
      subMenu = this.get('subMenu');
      this.invokeLater(this.checkMouseLocation, 200);
    } else {
      parentMenu = this.get('parentMenu');

      if (parentMenu.get('currentMenuItem') === this) {
        parentMenu.set('currentMenuItem', null);
      }
    }

    return YES ;
  },

  checkMouseLocation: function() {
    var subMenu = this.get('subMenu'), parentMenu = this.get('parentMenu');
    if (!subMenu.get('mouseHasEntered') && (parentMenu.get('currentMenuItem') === this || parentMenu.get('currentMenuItem') === null)) {
      parentMenu.get('previousMenuItem').$().removeClass('focus');
      subMenu.remove();
    }
  },

  /** @private
    Call the moveUp function on the parent Menu

    @returns Boolean
  */
  moveUp: function(sender,evt) {
    var menu = this.get('parentMenu') ;
    if(menu) {
      menu.moveUp(this) ;
    }
    return YES ;
  },

  /** @private
    Call the moveDown function on the parent Menu

    @returns Boolean
  */
  moveDown: function(sender,evt) {
    var menu = this.get('parentMenu') ;
    if(menu) {
      menu.moveDown(this) ;
    }
    return YES ;
  },

  /** @private
    Call the function to create a branch

    @returns Boolean
  */
  moveRight: function(sender,evt) {
    this.createSubMenu() ;
    return YES ;
  },

  /** @private*/
  keyDown: function(evt) {
    return this.interpretKeyEvents(evt) ;
  },

  /** @private*/
  keyUp: function(evt) {
    return YES ;
  },

  /** @private*/
  cancel: function(evt) {
    this.loseFocus() ;
    var menu = this.get('parentMenu') ;
    if (menu) menu.remove() ;
    var pane = menu.getPath('anchor.pane') ;
    if (pane) pane.becomeKeyPane() ;
    return YES ;
  },

  /** @private*/
  didBecomeFirstResponder: function(responder) {
    if (responder !== this) return;
    var parentMenu = this.get('parentMenu') ;
    if(parentMenu) {
      parentMenu.set('currentSelectedMenuItem', this) ;
    }
  },

  /** @private*/
  willLoseFirstResponder: function(responder) {
    if (responder !== this) return;
    // this.$().removeClass('focus') ;
    var parentMenu = this.get('parentMenu') ;
    if(parentMenu) {
      parentMenu.set('currentSelectedMenuItem', null) ;
      parentMenu.set('previousSelectedMenuItem', this) ;
    }
  },

  /** @private*/
  insertNewline: function(sender, evt) {
    this.mouseUp(evt) ;
  },

  /**
    Close the parent Menu and remove the focus of the current Selected
    Menu Item

    @returns void
  */
  closeParent: function() {
    this.$().removeClass('focus') ;
    var menu = this.get('parentMenu') ;
    if(menu) {
      menu.remove() ;
    }
  },

  /** @private*/
  clickInside: function(frame, evt) {
    return SC.pointInRect({ x: evt.pageX, y: evt.pageY }, frame) ;
  }

}) ;
<commit_msg>Make sure we turn isModal off and set the rootMenu property on submenus, even if they've created the menu pane for us ahead of time.<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================
sc_require('views/button') ;
sc_require('views/separator') ;

/**
  @class SC.MenuItemView
  @extends SC.ButtonView
  @since SproutCore 1.0
*/
SC.MenuItemView = SC.View.extend( SC.ContentDisplay,
/** @scope SC.MenuItemView.prototype */{

  classNames: ['sc-menu-item'],

  /**
    @private
    @property
    @type {Boolean}
  */
  acceptsFirstResponder: YES,

  // ..........................................................
  // KEY PROPERTIES
  //
  /**
    The content object the menu view will display.

    @type Object
  */
  content: null,

  /**
    This returns true if the child view is a menu list view.
    This property can be over written to have other child views as well.

    @type Boolean
  */
  isSubMenuViewVisible: null,

  /**
    This property specifies whether this menu item is currently in focus

    @type Boolean
  */
  hasMouseExited: NO,

  /**
    This menu item's submenu, if it exists.

    @type SC.MenuView
  */
  subMenu: function() {
    var content = this.get('content'), menuItems;

    if (!content) return null;

    menuItems = content.get( this.get('parentMenu').itemSubMenuKey );
    if (menuItems) {
      if (SC.kindOf(menuItems, SC.MenuPane)) {
        menuItems.set('isModal', NO);
        menuItems.set('rootMenu', this.get('rootMenu') || this);
        return menuItems;
      } else {
        return SC.MenuPane.create({
          layout: { width: 200 },
          items: menuItems,
          isModal: NO,
          isSubMenu: YES,
          rootMenu: this.get('rootMenu') || this
        });
      }
    }

    return null;
  }.property('content').cacheable(),

  /**
    Whether or not this menu item has a submenu.

    @type Boolean
  */
  hasSubMenu: function() {
    return !!this.get('subMenu');
  }.property('subMenu').cacheable(),

  /**
    Fills the passed html-array with strings that can be joined to form the
    innerHTML of the receiver element.  Also populates an array of classNames
    to set on the outer element.

    @param {SC.RenderContext} context
    @param {Boolean} firstTime
    @returns {void}
  */
  render: function(context, firstTime) {
    var content = this.get('content') ;
    var key, val ;
    var menu = this.get('parentMenu');
    var itemWidth = this.get('itemWidth') || menu.layout.width ;
    var itemHeight = this.get('itemHeight') || 20 ;
    this.set('itemWidth',itemWidth) ;
    this.set('itemHeight',itemHeight) ;

    // Disable the menu item only if isEnabled is NO
    // if (content.get(menu.itemIsEnabledKey) === NO) {
    //   context.addClass('disabled') ;
    // }

    context = context.begin('a').attr('href', 'javascript:');

    if (content.get(menu.itemSeparatorKey)) {
      context.push('');
      context.addClass('disabled');
    } else {
      val = content.get(menu.itemIconKey);
      if (val) {
        this.renderImage(context, val);
        context.addClass('has-icon');
      }

      val = content.get(menu.itemTitleKey) || '';
      if (SC.typeOf(val) !== SC.T_STRING) val = val.toString();
      // TODO check localization setting
      this.renderLabel(context, val.loc());

      if (content.get(menu.itemCheckboxKey)) {
        context.push('

');
      }

      if (this.get('hasSubMenu')) {
        this.renderBranch(context);
      }

      val = content.get(menu.itemShortCutKey);
      if (val) {
        this.renderShortcut(context, val);
      }
    }

    context = context.end();

    //         // handle short cut keys
    //         if (this.getDelegateProperty('shortCutKey', del)) {
    //           key = this.getDelegateProperty('shortCutKey', del) ;
    //           val = (key && content) ? (content.get ? content.get(key) : content[key]) : null ;
    //           if (val) {
    //             this.renderShortcut(ic, val) ;
    //             ic.addClass('shortcutkey') ;
    //           }
    //         }
    //       }
    //     }
    //     ic.end() ;
  },

  /**
   Generates the image used to represent the image icon. override this to
   return your own custom HTML

   @param {SC.RenderContext} context the render context
   @param {String} the source path of the image
   @returns {void}
  */
  renderImage: function(context, image) {
    // get a class name and url to include if relevant

    var url, className ;
    if (image && SC.ImageView.valueIsUrl(image)) {
      url = image ;
      className = '' ;
    } else {
      className = image ;
      url = SC.BLANK_IMAGE_URL;
    }
    // generate the img element...
    context.begin('img').addClass('image').addClass(className).attr('src', url).end() ;
  },

  /**
   Generates the label used to represent the menu item. override this to
   return your own custom HTML

   @param {SC.RenderContext} context the render context
   @param {String} menu item name
   @returns {void}
  */

  renderLabel: function(context, label) {
    context.push(""+label+"") ;
  },

  /**
   Generates the string used to represent the branch arrow. override this to
   return your own custom HTML

   @param {SC.RenderContext} context the render context
   @returns {void}
  */

  renderBranch: function(context) {
    context.push('>') ;
  },

  /**
   Generates the string used to represent the short cut keys. override this to
   return your own custom HTML

   @param {SC.RenderContext} context the render context
   @param {String} the shortcut key string to be displayed with menu item name
   @returns {void}
  */
  renderShortcut: function(context, shortcut) {
    context.push('' + shortcut + '') ;
  },

  /**
    This method is used to fetch the Menu Item View to which the
    Parent Menu Pane is anchored
    to

    @param {}
    @returns MenuPane
  */
  getAnchor: function() {
    var anchor = this.get('anchor') ;
    if(anchor && anchor.kindOf && anchor.kindOf(SC.MenuItemView)) return anchor ;
    return null ;
  },

  isCurrent: NO,

  /**
    This method checks if the menu item is a separator.

    @param {}
    @returns Boolean
  */
  isSeparator: function() {
    return this.getContentProperty('itemSeparatorKey') === NO;
  }.property().cacheable('content'),

  /**
    Checks if a menu is a sub menu, during branching.

    @param {}
    @returns MenuPane
  */
  isSubMenuAMenuPane: function() {
    var subMenu = this.get('subMenu');
    if(subMenu && subMenu.kindOf(SC.MenuPane)) return subMenu ;
    return NO ;
  },

  /**
    This method will check whether the current Menu Item is still
    selected and then create a submenu accordignly.

    @param {}
    @returns void
  */
  showSubMenu: function() {
    var subMenu = this.get('subMenu') ;
    if(subMenu) {
      subMenu.set('anchor', this) ;
      subMenu.popup(this,[0,0,0]) ;
    }
  },

  isEnabled: function() {
    return this.getContentProperty('itemIsEnabledKey') !== NO;
  }.property().cacheable('content'),

  getContentProperty: function(property) {
    var content = this.get('content'),
        menu = this.get('parentMenu');

    if (content) {
      return content.get(menu.get(property));
    }
  },

  //..........................................
  //Mouse Events Handling
  //..........................................

  // to check the 'isMouseDown' property of the anchor
  isAnchorMouseDown: NO,

  mouseUp: function(evt) {
    // SproutCore's event system will deliver the mouseUp event to the view
    // that got the mouseDown event, but for menus we want to track the mouse,
    // so we'll do our own dispatching.
    var menu = this.get('parentMenu'), currentMenuItem, action;

    if (menu) {
      currentMenuItem = menu.get('currentMenuItem') ;
      currentMenuItem.performAction();
    }

    return YES ;
  },

  performAction: function(skipFlash) {
    var action = this.getContentProperty('itemActionKey'),
        target = this.getContentProperty('itemTargetKey'), menu;

    this._flashCounter = 0;
    if (skipFlash) {
      this.getPath('pane.rootResponder').sendAction(action, target, this, this.get('pane'));

      menu = this.get('parentMenu');
      if (menu.get('isSubMenu')) menu.get('rootPane').remove();
      else menu.remove();
    } else {
      this.invokeLater(this.flashHighlight, 50);
    }
  },

  flashHighlight: function() {
    var flashCounter = this._flashCounter, layer = this.$();
    if (flashCounter % 2 === 0) {
      layer.addClass('focus');
    } else {
      layer.removeClass('focus');
    }

    if (flashCounter > 4) {
      this.performAction(YES);
    } else {
      this.invokeLater(this.flashHighlight, 75);
      this._flashCounter++;
    }
  },

  /** @private*/
  mouseDown: function(evt) {
    return YES ;
  },

  /** @private
    This has been over ridden from button view to prevent calling of render
    method (When isActive property is changed).
    Also based on whether the menu item has a sub Branch we create a sub Menu

    @returns Boolean
  */
  mouseEntered: function(evt) {
    var menu = this.get('parentMenu'), content = this.get('content');
    menu.set('mouseHasEntered', YES);
    menu.setIfChanged('currentMenuItem', this);

    if(this.get('hasSubMenu')) {
      this.invokeLater(this.showSubMenu(),100) ;
    }
	  return YES ;
  },

  /** @private
    Set the focus based on whether the current Menu item is selected or not.

    @returns Boolean
  */
  mouseExited: function(evt) {
    var subMenu, parentMenu;

    if (this.get('hasSubMenu')) {
      subMenu = this.get('subMenu');
      this.invokeLater(this.checkMouseLocation, 200);
    } else {
      parentMenu = this.get('parentMenu');

      if (parentMenu.get('currentMenuItem') === this) {
        parentMenu.set('currentMenuItem', null);
      }
    }

    return YES ;
  },

  checkMouseLocation: function() {
    var subMenu = this.get('subMenu'), parentMenu = this.get('parentMenu');
    if (!subMenu.get('mouseHasEntered') && (parentMenu.get('currentMenuItem') === this || parentMenu.get('currentMenuItem') === null)) {
      parentMenu.get('previousMenuItem').$().removeClass('focus');
      subMenu.remove();
    }
  },

  /** @private
    Call the moveUp function on the parent Menu

    @returns Boolean
  */
  moveUp: function(sender,evt) {
    var menu = this.get('parentMenu') ;
    if(menu) {
      menu.moveUp(this) ;
    }
    return YES ;
  },

  /** @private
    Call the moveDown function on the parent Menu

    @returns Boolean
  */
  moveDown: function(sender,evt) {
    var menu = this.get('parentMenu') ;
    if(menu) {
      menu.moveDown(this) ;
    }
    return YES ;
  },

  /** @private
    Call the function to create a branch

    @returns Boolean
  */
  moveRight: function(sender,evt) {
    this.createSubMenu() ;
    return YES ;
  },

  /** @private*/
  keyDown: function(evt) {
    return this.interpretKeyEvents(evt) ;
  },

  /** @private*/
  keyUp: function(evt) {
    return YES ;
  },

  /** @private*/
  cancel: function(evt) {
    this.loseFocus() ;
    var menu = this.get('parentMenu') ;
    if (menu) menu.remove() ;
    var pane = menu.getPath('anchor.pane') ;
    if (pane) pane.becomeKeyPane() ;
    return YES ;
  },

  /** @private*/
  didBecomeFirstResponder: function(responder) {
    if (responder !== this) return;
    var parentMenu = this.get('parentMenu') ;
    if(parentMenu) {
      parentMenu.set('currentSelectedMenuItem', this) ;
    }
  },

  /** @private*/
  willLoseFirstResponder: function(responder) {
    if (responder !== this) return;
    // this.$().removeClass('focus') ;
    var parentMenu = this.get('parentMenu') ;
    if(parentMenu) {
      parentMenu.set('currentSelectedMenuItem', null) ;
      parentMenu.set('previousSelectedMenuItem', this) ;
    }
  },

  /** @private*/
  insertNewline: function(sender, evt) {
    this.mouseUp(evt) ;
  },

  /**
    Close the parent Menu and remove the focus of the current Selected
    Menu Item

    @returns void
  */
  closeParent: function() {
    this.$().removeClass('focus') ;
    var menu = this.get('parentMenu') ;
    if(menu) {
      menu.remove() ;
    }
  },

  /** @private*/
  clickInside: function(frame, evt) {
    return SC.pointInRect({ x: evt.pageX, y: evt.pageY }, frame) ;
  }

}) ;
<|endoftext|>


<commit_before>Template.components_index.helpers({
//  accounts: function(){
//    return EthAccounts.find({});
//  }
	'coinbase': function(){
		return web3.eth.coinbase;
	},

  contracts: function(){
    { _id: 100 }; // 動作テスト用
//    return Contracts.find({}); //Contracts collectionから全て取得
  }
});

// 購入ボタンを押した時のイベント
Template.components_index.events({
    'click .btn-success': function(event) {
    event.preventDefault();
    var abi = MultiplyContract.abi;
    var contract_address = "0xcf69fcc3c34933191c54de8901d3c440db6d74fc";
    var cnt = web3.eth.contract(abi).at(contract_address);
    var result = cnt.Respond.sendTransaction(web3.eth.accounts[0], 100000, {from: web3.eth.accounts[0], gas:500000});
    console.log(result);
    // get the id(account, abi) of pushed
    // send transaction to contract by using web3
    }
});
<commit_msg>change confirm of transaction from console to alert<commit_after>Template.components_index.helpers({
//  accounts: function(){
//    return EthAccounts.find({});
//  }
	'coinbase': function(){
		return web3.eth.coinbase;
	},

  contracts: function(){
    { _id: 100 }; // 動作テスト用
//    return Contracts.find({}); //Contracts collectionから全て取得
  }
});

// 購入ボタンを押した時のイベント
Template.components_index.events({
    'click .btn-success': function(event) {
    event.preventDefault();
    var abi = MultiplyContract.abi;
    var contract_address = "0xcf69fcc3c34933191c54de8901d3c440db6d74fc";
    var cnt = web3.eth.contract(abi).at(contract_address);
    var result = cnt.Respond.sendTransaction(web3.eth.accounts[0], 100000, {from: web3.eth.accounts[0], gas:500000});
    alert( "購入が完了しました!!\nトランザクションアドレスは" + result );
    // get the id(account, abi) of pushed
    // send transaction to contract by using web3
    }
});
<|endoftext|>


<commit_before>'use strict';

var Dashboard = angular.module('Dashboard', ['ngCookies', 'DashboardConstantsModule', 'ServiceModule']);

Dashboard.config(['$httpProvider', function($httpProvider) {
    var $cookies;
    angular.injector(['ngCookies']).invoke(function(_$cookies_) {
        $cookies = _$cookies_;
    });

    var userTeamToken = angular.fromJson($cookies.user_team_token);
    if (userTeamToken != undefined) {
        $httpProvider.defaults.headers.common.Authorization = userTeamToken.token_type + ' ' + userTeamToken.access_token;
    }

    $httpProvider.defaults.headers.common.contentType = 'application/json';
}]);

Dashboard.controller('Login', function($scope, $window, $location, $cookieStore, Utils, DashboardConstants, DataService) {
    $scope.initLogin = function() {
        // DataService.checkAuthentication();
    };

    $scope.authenticate_dashboard = function() {
        var params = {
            'user_email' : $scope.email,
            'password' : $scope.password,
            'team_key' : $scope.teamkey
        };

        DataService.makeHTTPCall("account.dashboard.authenticate", params, function(data) {
            data['email'] = params.user_email;
            Utils.storeUserDataInCookies(data);
            if (data.authenticated) {
                $window.location.href = $location.absUrl().replace('login.html', 'feed.html');
            }
        });
    };
});

Dashboard.controller('Feed', function($scope, $window, $location, $cookieStore, $sce, Utils, DataService, ComStyleGetter, DashboardConstants) {
    $scope.noTeamNotesText = "No Notes";

    $scope.imageBaseURL = DashboardConstants.imageURL[DashboardConstants.serverURLKey];
    $scope.display_name = $cookieStore.get('user_display_name');
    $scope.email = $cookieStore.get('user_email');
    $scope.image_url = $cookieStore.get('user_image_url');

    $scope.showSignoutButton = "none";
    $scope.signoutArrowValue = false;

    $scope.imageWidth = 0;
    $scope.imageHeight = 0;
    $scope.borderWidth = 4;

    $scope.signoutButtonClicked = function() {
        if (logout_button.style.display === "none") {
            $scope.showSignoutButton = "block";
            $scope.signoutArrowValue = true;
        } else {
            $scope.showSignoutButton = "none";
            $scope.signoutArrowValue = false;
        }
    };

    $scope.signoutDashboard = function() {
        $window.location.href = $location.absUrl().replace('feed.html' , 'login.html');
        Utils.removeUserDataCookies();
    };

    $scope.initLogin = function() {
        // DataService.checkAuthentication();
    };

    DataService.makeHTTPCall("appinfo.appinfo.get", {
        team_key : $cookieStore.get('team_key')
    }, function(data) {
        $scope.appInfo = data;
    }, function(status) {
        if (status == 401) {
            $window.location.href = $location.absUrl().replace('feed.html' , 'login.html');
            Utils.removeUserDataCookies();
        }
    });

    $scope.showLocalDateTime = function(datetime) {
        return new Date(datetime);
    };

    $scope.showProperDeviceName = function(device_model) {
        if (device_model in DashboardConstants.deviceList) {
            device_model = DashboardConstants.deviceList[device_model];
        }

        return device_model;
    };

    $scope.parseForTagsMentionsLinks = function(text, tagged_users_detail) {
        text = Utils.replaceURLWithLink(text);
        text = Utils.replaceEmailWithName(text, tagged_users_detail);
        text = Utils.replaceHashTagWithLink(text);
        text = $sce.trustAsHtml(text);
        return text;
    };

    $scope.getAnnoById = function(anno_id) {
        var annoData = {};

        if ($scope.annoList.length) {
            var annoDataList = $scope.annoList.filter(function(anno) {
                return anno.id === anno_id;
            });

            if (annoDataList.length) {
                annoData = annoDataList[0];
            }
        }

        return annoData;
    };

    DataService.makeHTTPCall("anno.anno.dashboard.list", {
        outcome : 'cursor,has_more,anno_list'
    }, function(data) {
        $scope.annoList = data.anno_list;
        console.log($scope.annoList);
    }, function(status) {
        if (status == 401) {
            $window.location.href = $location.absUrl().replace('feed.html' , 'login.html');
            Utils.removeUserDataCookies();
        }
    });

    $scope.screenshotLoad = function (event) {
        var anno_item = Utils.findAncestor(event.currentTarget, 'anno-item');
        var imgDetailScreenshot = anno_item.querySelector(".imgDetailScreenshot");
        angular.element(imgDetailScreenshot).css('display', '');

        var self = this;
        require(["anno/draw/Surface"], function(Surface) {
            self.imageWidth = parseInt(ComStyleGetter.getComStyle(imgDetailScreenshot).width, 10);
            self.imageHeight = parseInt(ComStyleGetter.getComStyle(imgDetailScreenshot).height, 10);
            // self.borderWidth = Math.floor(self.imageWidth * 0.02);

            var surface = new Surface({
                container : anno_item.querySelector(".gfxCanvasContainer"),
                width : 500,
                height : 500,
                editable : false,
                borderWidth : 0
            });

            self.applyAnnoLevelColor(anno_item, imgDetailScreenshot);
            self.redrawShapes(anno_item.dataset.annoId, surface);
        });
    };

    $scope.applyAnnoLevelColor = function (anno_item, imgDetailScreenshot) {
        var screenshotContainer = anno_item.querySelector(".screenshotContainer");
        angular.element(screenshotContainer).css({
            width : (this.imageWidth - this.borderWidth * 2) + 'px',
            height : (this.imageHeight - this.borderWidth * 2) + 'px',
            'border-color' : DashboardConstants.borderColor,
            'border-style' : 'solid',
            'border-width' : this.borderWidth + 'px'
        });

        angular.element(imgDetailScreenshot).css({ width : '100%', height : '100%' });
    };

    $scope.redrawShapes = function(anno_id, surface) {
        var annoData = $scope.getAnnoById(anno_id);
        var lineStrokeStyle = { color: DashboardConstants.borderColor, width: 3 };

        if (angular.isObject(annoData)) {
            var elementsObject = angular.fromJson(annoData.draw_elements);
            surface.show();
            angular.element(surface.container).css({'border': this.borderWidth + 'px solid transparent', left: '0px',top: '0px'});
            surface.borderWidth = this.borderWidth;
            surface.setDimensions(this.imageWidth - this.borderWidth * 2, this.imageHeight - this.borderWidth * 2);
            surface.parse(elementsObject, lineStrokeStyle);
        }
    };

    $scope.editTeamNotes = function(event) {
        $scope.team_notes_save = "Save";
        var anno_item = Utils.findAncestor(event.currentTarget, 'anno-item'),
            teamNotesTextNode = anno_item.querySelector('.team-notes'),
            teamNotesTextInput = anno_item.querySelector('.anno-team-notes-edittext');

        if (teamNotesTextNode.style.display !== "none") {
            teamNotesTextNode.style.display = "none";
            teamNotesTextInput.style.display = "block";
        } else {
            teamNotesTextNode.style.display = "block";
            teamNotesTextInput.style.display = "none";
        }

        if (teamNotesTextNode.innerText !== $scope.noTeamNotesText) {
            teamNotesTextInput.querySelector('textarea').value = teamNotesTextNode.innerText;
        }
    };

    $scope.saveTeamNotes = function(event) {
        if (event.type === "keydown" && event.keyCode !== 13) return;
        $scope.team_notes_save = "Saving...";
        var anno_item = Utils.findAncestor(event.currentTarget, 'anno-item'),
            teamNotesTextNode = anno_item.querySelector('.team-notes'),
            teamNotesTextInput = anno_item.querySelector('.anno-team-notes-edittext'),
            anno_id = anno_item.dataset.annoId;

        var teamNotes = teamNotesTextInput.querySelector('textarea').value.trim();
        if (teamNotes.length) {
            var anno_item = $scope.getAnnoById(anno_id);
            anno_item.team_notes = teamNotes;
            DataService.makeHTTPCall("anno.anno.teamnotes.insert", {
                id: anno_id,
                team_notes: teamNotes
            }, function(data) {
                anno_item.team_notes_metadata.tags = data.tags;
                $scope.team_notes_save = "Saved";
                setTimeout(function() {
                    teamNotesTextNode.style.display = "block";
                    teamNotesTextInput.style.display = "none";
                }, 1000);
            });
        }
    };

    $scope.postComment = function(event) {
        if (event.type === "keydown" && event.keyCode !== 13) return;
        var anno_item = Utils.findAncestor(event.currentTarget, 'anno-item'),
            postCommentTextarea = anno_item.querySelector('.post-comment').querySelector('textarea'),
            anno_id = anno_item.dataset.annoId;

        var comment = postCommentTextarea.value.trim();
        if (comment.length) {
            DataService.makeHTTPCall("followup.followup.insert", {
                anno_id : anno_id,
                comment : comment
            }, function(data) {
                postCommentTextarea.value = "";
                var latestComment = {
                    id : data.id,
                    anno_id : data.anno_id,
                    comment : data.comment,
                    created : data.created,
                    creator : data.creator
                };
                $scope.getAnnoById(anno_id).followup_list.push(latestComment);
            });
        }
    };
});
<commit_msg>[Dashboard] Fix: redeclaration of anno_item<commit_after>'use strict';

var Dashboard = angular.module('Dashboard', ['ngCookies', 'DashboardConstantsModule', 'ServiceModule']);

Dashboard.config(['$httpProvider', function($httpProvider) {
    var $cookies;
    angular.injector(['ngCookies']).invoke(function(_$cookies_) {
        $cookies = _$cookies_;
    });

    var userTeamToken = angular.fromJson($cookies.user_team_token);
    if (userTeamToken != undefined) {
        $httpProvider.defaults.headers.common.Authorization = userTeamToken.token_type + ' ' + userTeamToken.access_token;
    }

    $httpProvider.defaults.headers.common.contentType = 'application/json';
}]);

Dashboard.controller('Login', function($scope, $window, $location, $cookieStore, Utils, DashboardConstants, DataService) {
    $scope.initLogin = function() {
        // DataService.checkAuthentication();
    };

    $scope.authenticate_dashboard = function() {
        var params = {
            'user_email' : $scope.email,
            'password' : $scope.password,
            'team_key' : $scope.teamkey
        };

        DataService.makeHTTPCall("account.dashboard.authenticate", params, function(data) {
            data['email'] = params.user_email;
            Utils.storeUserDataInCookies(data);
            if (data.authenticated) {
                $window.location.href = $location.absUrl().replace('login.html', 'feed.html');
            }
        });
    };
});

Dashboard.controller('Feed', function($scope, $window, $location, $cookieStore, $sce, Utils, DataService, ComStyleGetter, DashboardConstants) {
    $scope.noTeamNotesText = "No Notes";

    $scope.imageBaseURL = DashboardConstants.imageURL[DashboardConstants.serverURLKey];
    $scope.display_name = $cookieStore.get('user_display_name');
    $scope.email = $cookieStore.get('user_email');
    $scope.image_url = $cookieStore.get('user_image_url');

    $scope.showSignoutButton = "none";
    $scope.signoutArrowValue = false;

    $scope.imageWidth = 0;
    $scope.imageHeight = 0;
    $scope.borderWidth = 4;

    $scope.signoutButtonClicked = function() {
        if (logout_button.style.display === "none") {
            $scope.showSignoutButton = "block";
            $scope.signoutArrowValue = true;
        } else {
            $scope.showSignoutButton = "none";
            $scope.signoutArrowValue = false;
        }
    };

    $scope.signoutDashboard = function() {
        $window.location.href = $location.absUrl().replace('feed.html' , 'login.html');
        Utils.removeUserDataCookies();
    };

    $scope.initLogin = function() {
        // DataService.checkAuthentication();
    };

    DataService.makeHTTPCall("appinfo.appinfo.get", {
        team_key : $cookieStore.get('team_key')
    }, function(data) {
        $scope.appInfo = data;
    }, function(status) {
        if (status == 401) {
            $window.location.href = $location.absUrl().replace('feed.html' , 'login.html');
            Utils.removeUserDataCookies();
        }
    });

    $scope.showLocalDateTime = function(datetime) {
        return new Date(datetime);
    };

    $scope.showProperDeviceName = function(device_model) {
        if (device_model in DashboardConstants.deviceList) {
            device_model = DashboardConstants.deviceList[device_model];
        }

        return device_model;
    };

    $scope.parseForTagsMentionsLinks = function(text, tagged_users_detail) {
        text = Utils.replaceURLWithLink(text);
        text = Utils.replaceEmailWithName(text, tagged_users_detail);
        text = Utils.replaceHashTagWithLink(text);
        text = $sce.trustAsHtml(text);
        return text;
    };

    $scope.getAnnoById = function(anno_id) {
        var annoData = {};

        if ($scope.annoList.length) {
            var annoDataList = $scope.annoList.filter(function(anno) {
                return anno.id === anno_id;
            });

            if (annoDataList.length) {
                annoData = annoDataList[0];
            }
        }

        return annoData;
    };

    DataService.makeHTTPCall("anno.anno.dashboard.list", {
        outcome : 'cursor,has_more,anno_list'
    }, function(data) {
        $scope.annoList = data.anno_list;
        console.log($scope.annoList);
    }, function(status) {
        if (status == 401) {
            $window.location.href = $location.absUrl().replace('feed.html' , 'login.html');
            Utils.removeUserDataCookies();
        }
    });

    $scope.screenshotLoad = function (event) {
        var anno_item = Utils.findAncestor(event.currentTarget, 'anno-item');
        var imgDetailScreenshot = anno_item.querySelector(".imgDetailScreenshot");
        angular.element(imgDetailScreenshot).css('display', '');

        var self = this;
        require(["anno/draw/Surface"], function(Surface) {
            self.imageWidth = parseInt(ComStyleGetter.getComStyle(imgDetailScreenshot).width, 10);
            self.imageHeight = parseInt(ComStyleGetter.getComStyle(imgDetailScreenshot).height, 10);
            // self.borderWidth = Math.floor(self.imageWidth * 0.02);

            var surface = new Surface({
                container : anno_item.querySelector(".gfxCanvasContainer"),
                width : 500,
                height : 500,
                editable : false,
                borderWidth : 0
            });

            self.applyAnnoLevelColor(anno_item, imgDetailScreenshot);
            self.redrawShapes(anno_item.dataset.annoId, surface);
        });
    };

    $scope.applyAnnoLevelColor = function (anno_item, imgDetailScreenshot) {
        var screenshotContainer = anno_item.querySelector(".screenshotContainer");
        angular.element(screenshotContainer).css({
            width : (this.imageWidth - this.borderWidth * 2) + 'px',
            height : (this.imageHeight - this.borderWidth * 2) + 'px',
            'border-color' : DashboardConstants.borderColor,
            'border-style' : 'solid',
            'border-width' : this.borderWidth + 'px'
        });

        angular.element(imgDetailScreenshot).css({ width : '100%', height : '100%' });
    };

    $scope.redrawShapes = function(anno_id, surface) {
        var annoData = $scope.getAnnoById(anno_id);
        var lineStrokeStyle = { color: DashboardConstants.borderColor, width: 3 };

        if (angular.isObject(annoData)) {
            var elementsObject = angular.fromJson(annoData.draw_elements);
            surface.show();
            angular.element(surface.container).css({'border': this.borderWidth + 'px solid transparent', left: '0px',top: '0px'});
            surface.borderWidth = this.borderWidth;
            surface.setDimensions(this.imageWidth - this.borderWidth * 2, this.imageHeight - this.borderWidth * 2);
            surface.parse(elementsObject, lineStrokeStyle);
        }
    };

    $scope.editTeamNotes = function(event) {
        $scope.team_notes_save = "Save";
        var anno_item = Utils.findAncestor(event.currentTarget, 'anno-item'),
            teamNotesTextNode = anno_item.querySelector('.team-notes'),
            teamNotesTextInput = anno_item.querySelector('.anno-team-notes-edittext');

        if (teamNotesTextNode.style.display !== "none") {
            teamNotesTextNode.style.display = "none";
            teamNotesTextInput.style.display = "block";
        } else {
            teamNotesTextNode.style.display = "block";
            teamNotesTextInput.style.display = "none";
        }

        if (teamNotesTextNode.innerText !== $scope.noTeamNotesText) {
            teamNotesTextInput.querySelector('textarea').value = teamNotesTextNode.innerText;
        }
    };

    $scope.saveTeamNotes = function(event) {
        if (event.type === "keydown" && event.keyCode !== 13) return;
        $scope.team_notes_save = "Saving...";
        var anno_item = Utils.findAncestor(event.currentTarget, 'anno-item'),
            teamNotesTextNode = anno_item.querySelector('.team-notes'),
            teamNotesTextInput = anno_item.querySelector('.anno-team-notes-edittext'),
            anno_id = anno_item.dataset.annoId;

        var teamNotes = teamNotesTextInput.querySelector('textarea').value.trim();
        if (teamNotes.length) {
            var anno_item_data = $scope.getAnnoById(anno_id);
            anno_item_data.team_notes = teamNotes;
            DataService.makeHTTPCall("anno.anno.teamnotes.insert", {
                id: anno_id,
                team_notes: teamNotes
            }, function(data) {
                anno_item_data.team_notes_metadata.tags = data.tags;
                $scope.team_notes_save = "Saved";
                setTimeout(function() {
                    teamNotesTextNode.style.display = "block";
                    teamNotesTextInput.style.display = "none";
                }, 1000);
            });
        }
    };

    $scope.postComment = function(event) {
        if (event.type === "keydown" && event.keyCode !== 13) return;
        var anno_item = Utils.findAncestor(event.currentTarget, 'anno-item'),
            postCommentTextarea = anno_item.querySelector('.post-comment').querySelector('textarea'),
            anno_id = anno_item.dataset.annoId;

        var comment = postCommentTextarea.value.trim();
        if (comment.length) {
            DataService.makeHTTPCall("followup.followup.insert", {
                anno_id : anno_id,
                comment : comment
            }, function(data) {
                postCommentTextarea.value = "";
                var latestComment = {
                    id : data.id,
                    anno_id : data.anno_id,
                    comment : data.comment,
                    created : data.created,
                    creator : data.creator
                };
                $scope.getAnnoById(anno_id).followup_list.push(latestComment);
            });
        }
    };
});
<|endoftext|>


<commit_before>(function(){
  var inputValidators = function(inputId) {
    var nameValidator = function(name) {
      return name.trim().length > 0;
    };
    var emailValidator = function(email) {
      // http://stackoverflow.com/a/46181/543875
      var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
      return re.test(email);
    };
    var passwordValidator = function(password) {
      return password.length > 7;
    };
    var passwordMatchValidator = function(password2) {
      var password1 = document.getElementById("password2ID").value;
      return passwordValidator(password1) && (password1 === password2);
    };

    var validators = {};
    validators["firstNameID"] = nameValidator;
    validators["lastNameID"] = nameValidator;
    validators["email"] = emailValidator;
    validators["password1ID"] = passwordValidator;
    validators["password2ID"] = passwordMatchValidator;

    var input = document.getElementById(inputId);
    var validator = input ? validators[inputId] : null;
    return validator ? validator(input.value) : false;
  };

  var passwordController = new PasswordController();
  var formController = new FormController(inputValidators);
  formController.init();
}());<commit_msg>Fixed: used wrong password to make sure passwords match<commit_after>(function(){
  var inputValidators = function(inputId) {
    var nameValidator = function(name) {
      return name.trim().length > 0;
    };
    var emailValidator = function(email) {
      // http://stackoverflow.com/a/46181/543875
      var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
      return re.test(email);
    };
    var passwordValidator = function(password) {
      return password.length > 7;
    };
    var passwordMatchValidator = function(password2) {
      var password1 = document.getElementById("password1ID").value;
      return passwordValidator(password1) && (password1 === password2);
    };

    var validators = {};
    validators["firstNameID"] = nameValidator;
    validators["lastNameID"] = nameValidator;
    validators["email"] = emailValidator;
    validators["password1ID"] = passwordValidator;
    validators["password2ID"] = passwordMatchValidator;

    var input = document.getElementById(inputId);
    var validator = input ? validators[inputId] : null;
    return validator ? validator(input.value) : false;
  };

  var passwordController = new PasswordController();
  var formController = new FormController(inputValidators);
  formController.init();
}());<|endoftext|>


<commit_before>module.exports = function(sails) {

	/**
	 * Module dependencies.
	 */

	var _		= require('lodash'),
	interpret	= require('./interpreter/interpret')(sails),
	getVerb		= require('./interpreter/getVerb');

	/**
	 * Fired after a socket is connected
	 */

	return function onConnect (socket) {
		sails.log.verbose('A socket.io client ('+ socket.id + ') connected successfully!');

		// Legacy support of `message`
		mapRoute('message');

		// Verb support
		mapRoute('get');
		mapRoute('post');
		mapRoute('put');
		mapRoute('delete');
		mapRoute('options');

		// Map a socket message to the router
		function mapRoute (messageName) {
			socket.on(messageName, function (socketReq, callback) {

				sails.log.verbose('Routing message over socket: ', socketReq);

				callback = callback || function noCallback(body, status) {
					sails.log.error('No callback specified!');
				};

				var verb = getVerb(socketReq, messageName);

				// Translate socket.io message to an Express-looking request
				interpret(socketReq, callback, socket, verb, function requestBuilt (err, request) {
					if (err) {
						sails.log.error(err);
						return;
					}

					// Route socket.io request
					sails.emit('router:request', request.req, request.res);
				});

			});
		}
	};

};
<commit_msg>Maybe fixed socket/test error routing?<commit_after>module.exports = function(sails) {

	/**
	 * Module dependencies.
	 */

	var _		= require('lodash'),
	interpret	= require('./interpreter/interpret')(sails),
	getVerb		= require('./interpreter/getVerb');

	/**
	 * Fired after a socket is connected
	 */

	return function onConnect (socket) {
		sails.log.verbose('A socket.io client ('+ socket.id + ') connected successfully!');

		// Legacy support of `message`
		mapRoute('message');

		// Verb support
		mapRoute('get');
		mapRoute('post');
		mapRoute('put');
		mapRoute('delete');

		// Map a socket message to the router
		function mapRoute (messageName) {
			socket.on(messageName, function (socketReq, callback) {

				sails.log.verbose('Routing message over socket: ', socketReq);

				callback = callback || function noCallback(body, status) {
					sails.log.error('No callback specified!');
				};

				var verb = getVerb(socketReq, messageName);

				// Translate socket.io message to an Express-looking request
				interpret(socketReq, callback, socket, verb, function requestBuilt (err, request) {
					if (err) {
						sails.log.error(err);
						return;
					}

					// Route socket.io request
					sails.emit('router:request', request.req, request.res);
				});

			});
		}
	};

};
<|endoftext|>


<commit_before>export * from 'fela/lib/plugins/logger'
<commit_msg>unbundle fela-plugin-logger<commit_after>/* @flow */
/* eslint-disable no-console */

type Type = 1 | 2 | 3 | 4 | 5

function addLogger(style: Object, type: Type): Object {
  if (process.env.NODE_ENV !== 'production') {
    console.log(type, { ...style })
  }

  return style
}

export default () => addLogger
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: See license.txt

frappe.provide("frappe.activity");

frappe.pages['activity'].on_page_load = function(wrapper) {
	var me = this;

	frappe.ui.make_app_page({
		parent: wrapper,
		single_column: true
	});

	me.page = wrapper.page;
	me.page.set_title(__("Activity"));

	frappe.model.with_doctype("Communication", function() {
		me.page.list = new frappe.ui.BaseList({
			hide_refresh: true,
			page: me.page,
			method: 'frappe.desk.page.activity.activity.get_feed',
			parent: $("

").appendTo(me.page.main),
			render_view: function (values) {
				var me = this;
				wrapper = me.page.main.find(".result-list").get(0)
				values.map(function (value) {
					var row = $('
')
						.data("data", value)
						.appendTo($(wrapper)).get(0);
					new frappe.activity.Feed(row, value);
				});
			},
			show_filters: true,
			doctype: "Communication",
			get_args: function() {
				if (frappe.route_options && frappe.route_options.show_likes) {
					delete frappe.route_options.show_likes;
					return {
						show_likes: true
					}
				} else {
					return {}
				}
			}
		});

		me.page.list.run();

		me.page.set_primary_action(__("Refresh"), function() {
			me.page.list.filter_list.clear_filters();
			me.page.list.run();
		}, "octicon octicon-sync");
	});

	frappe.activity.render_heatmap(me.page);

	me.page.main.on("click", ".activity-message", function() {
		var link_doctype = $(this).attr("data-link-doctype"),
			link_name = $(this).attr("data-link-name"),
			doctype = $(this).attr("data-doctype"),
			docname = $(this).attr("data-docname");

		if (doctype && docname) {
			if (link_doctype && link_name) {
				frappe.route_options = {
					scroll_to: { "doctype": doctype, "name": docname }
				}
			}

			frappe.set_route(["Form", link_doctype || doctype, link_name || docname]);
		}
	});

	// Build Report Button
	if(frappe.boot.user.can_get_report.indexOf("Feed")!=-1) {
		this.page.add_menu_item(__('Build Report'), function() {
			frappe.set_route('Report', "Feed");
		}, 'fa fa-th')
	}

	this.page.add_menu_item(__('Authentication Log'), function() {
		frappe.route_options = {
			"user": frappe.session.user
		}

		frappe.set_route('Report', "Authentication Log");
	}, 'fa fa-th')

	this.page.add_menu_item(__('Show Likes'), function() {
		frappe.route_options = {
			show_likes: true
		};
		me.page.list.run();
	}, 'octicon octicon-heart');
};

frappe.pages['activity'].on_page_show = function() {
	frappe.breadcrumbs.add("Desk");
}

frappe.activity.last_feed_date = false;
frappe.activity.Feed = Class.extend({
	init: function(row, data) {
		this.scrub_data(data);
		this.add_date_separator(row, data);
		if(!data.add_class)
			data.add_class = "label-default";

		data.link = "";
		if (data.link_doctype && data.link_name) {
			data.link = frappe.format(data.link_name, {fieldtype: "Link", options: data.link_doctype},
				{label: __(data.link_doctype) + " " + __(data.link_name)});

		} else if (data.feed_type==="Comment" && data.comment_type==="Comment") {
			// hack for backward compatiblity
			data.link_doctype = data.reference_doctype;
			data.link_name = data.reference_name;
			data.reference_doctype = "Communication";
			data.reference_name = data.name;

			data.link = frappe.format(data.link_name, {fieldtype: "Link", options: data.link_doctype},
				{label: __(data.link_doctype) + " " + __(data.link_name)});

		} else if (data.reference_doctype && data.reference_name) {
			data.link = frappe.format(data.reference_name, {fieldtype: "Link", options: data.reference_doctype},
				{label: __(data.reference_doctype) + " " + __(data.reference_name)});
		}

		$(row)
			.append(frappe.render_template("activity_row", data))
			.find("a").addClass("grey");
	},
	scrub_data: function(data) {
		data.by = frappe.user.full_name(data.owner);
		data.avatar = frappe.avatar(data.owner);

		data.icon = "fa fa-flag";

		// color for comment
		data.add_class = {
			"Comment": "label-danger",
			"Assignment": "label-warning",
			"Login": "label-default"
		}[data.comment_type || data.communication_medium] || "label-info"

		data.when = comment_when(data.creation);
		data.feed_type = data.comment_type || data.communication_medium;
	},
	add_date_separator: function(row, data) {
		var date = frappe.datetime.str_to_obj(data.creation);
		var last = frappe.activity.last_feed_date;

		if((last && frappe.datetime.obj_to_str(last) != frappe.datetime.obj_to_str(date)) || (!last)) {
			var diff = frappe.datetime.get_day_diff(frappe.datetime.get_today(), frappe.datetime.obj_to_str(date));
			var pdate;
			if(diff < 1) {
				pdate = 'Today';
			} else if(diff < 2) {
				pdate = 'Yesterday';
			} else {
				pdate = frappe.datetime.global_date_format(date);
			}
			data.date_sep = pdate;
			data.date_class = pdate=='Today' ? "date-indicator blue" : "date-indicator";
		} else {
			data.date_sep = null;
			data.date_class = "";
		}
		frappe.activity.last_feed_date = date;
	}
});

frappe.activity.render_heatmap = function(page) {
	var me = this;
	$('
\

\

').prependTo(page.main);

	frappe.call({
		method: "frappe.desk.page.activity.activity.get_heatmap_data",
		callback: function(r) {
			if(r.message) {
				var heatmap = new frappe.chart.HeatMap({
					parent: ".heatmap",
					type: 'heatmap',
					height: 100,
					start: new Date(moment().subtract(1, 'year').toDate()),
					count_label: "actions",
					discrete_domains: 0
				});

				heatmap.update(r.message);
			}
		}
	})
}<commit_msg>revised according to latest merge<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: See license.txt

frappe.provide("frappe.activity");

frappe.pages['activity'].on_page_load = function(wrapper) {
	var me = this;

	frappe.ui.make_app_page({
		parent: wrapper,
		single_column: true
	});

	me.page = wrapper.page;
	me.page.set_title(__("Activity"));

	frappe.model.with_doctype("Communication", function() {
		me.page.list = new frappe.ui.BaseList({
			hide_refresh: true,
			page: me.page,
			method: 'frappe.desk.page.activity.activity.get_feed',
			parent: $("

").appendTo(me.page.main),
			render_view: function (values) {
				var me = this;
				wrapper = me.page.main.find(".result-list").get(0)
				values.map(function (value) {
					var row = $('
')
						.data("data", value)
						.appendTo($(wrapper)).get(0);
					new frappe.activity.Feed(row, value);
				});
			},
			show_filters: true,
			doctype: "Communication",
			get_args: function() {
				if (frappe.route_options && frappe.route_options.show_likes) {
					delete frappe.route_options.show_likes;
					return {
						show_likes: true
					}
				} else {
					return {}
				}
			}
		});

		me.page.list.run();

		me.page.set_primary_action(__("Refresh"), function() {
			me.page.list.filter_list.clear_filters();
			me.page.list.run();
		}, "octicon octicon-sync");
	});

	frappe.activity.render_heatmap(me.page);

	me.page.main.on("click", ".activity-message", function() {
		var link_doctype = $(this).attr("data-link-doctype"),
			link_name = $(this).attr("data-link-name"),
			doctype = $(this).attr("data-doctype"),
			docname = $(this).attr("data-docname");

		if (doctype && docname) {
			if (link_doctype && link_name) {
				frappe.route_options = {
					scroll_to: { "doctype": doctype, "name": docname }
				}
			}

			frappe.set_route(["Form", link_doctype || doctype, link_name || docname]);
		}
	});

	// Build Report Button
	if(frappe.boot.user.can_get_report.indexOf("Feed")!=-1) {
		this.page.add_menu_item(__('Build Report'), function() {
			frappe.set_route('Report', "Feed");
		}, 'fa fa-th')
	}

	this.page.add_menu_item(__('Authentication Log'), function() {
		frappe.route_options = {
			"user": frappe.session.user
		}

		frappe.set_route('Report', "Authentication Log");
	}, 'fa fa-th')

	this.page.add_menu_item(__('Show Likes'), function() {
		frappe.route_options = {
			show_likes: true
		};
		me.page.list.run();
	}, 'octicon octicon-heart');
};

frappe.pages['activity'].on_page_show = function() {
	frappe.breadcrumbs.add("Desk");
}

frappe.activity.last_feed_date = false;
frappe.activity.Feed = Class.extend({
	init: function(row, data) {
		this.scrub_data(data);
		this.add_date_separator(row, data);
		if(!data.add_class)
			data.add_class = "label-default";

		data.link = "";
		if (data.link_doctype && data.link_name) {
			data.link = frappe.format(data.link_name, {fieldtype: "Link", options: data.link_doctype},
				{label: __(data.link_doctype) + " " + __(data.link_name)});

		} else if (data.feed_type==="Comment" && data.comment_type==="Comment") {
			// hack for backward compatiblity
			data.link_doctype = data.reference_doctype;
			data.link_name = data.reference_name;
			data.reference_doctype = "Communication";
			data.reference_name = data.name;

			data.link = frappe.format(data.link_name, {fieldtype: "Link", options: data.link_doctype},
				{label: __(data.link_doctype) + " " + __(data.link_name)});

		} else if (data.reference_doctype && data.reference_name) {
			data.link = frappe.format(data.reference_name, {fieldtype: "Link", options: data.reference_doctype},
				{label: __(data.reference_doctype) + " " + __(data.reference_name)});
		}

		$(row)
			.append(frappe.render_template("activity_row", data))
			.find("a").addClass("grey");
	},
	scrub_data: function(data) {
		data.by = frappe.user.full_name(data.owner);
		data.avatar = frappe.avatar(data.owner);

		data.icon = "fa fa-flag";

		// color for comment
		data.add_class = {
			"Comment": "label-danger",
			"Assignment": "label-warning",
			"Login": "label-default"
		}[data.comment_type || data.communication_medium] || "label-info"

		data.when = comment_when(data.creation);
		data.feed_type = data.comment_type || data.communication_medium;
	},
	add_date_separator: function(row, data) {
		var date = frappe.datetime.str_to_obj(data.creation);
		var last = frappe.activity.last_feed_date;

		if((last && frappe.datetime.obj_to_str(last) != frappe.datetime.obj_to_str(date)) || (!last)) {
			var diff = frappe.datetime.get_day_diff(frappe.datetime.get_today(), frappe.datetime.obj_to_str(date));
			var pdate;
			if(diff < 1) {
				pdate = 'Today';
			} else if(diff < 2) {
				pdate = 'Yesterday';
			} else {
				pdate = frappe.datetime.global_date_format(date);
			}
			data.date_sep = pdate;
			data.date_class = pdate=='Today' ? "date-indicator blue" : "date-indicator";
		} else {
			data.date_sep = null;
			data.date_class = "";
		}
		frappe.activity.last_feed_date = date;
	}
});

frappe.activity.render_heatmap = function(page) {
	var me = this;
	$('
\

\

').prependTo(page.main);

	frappe.call({
		method: "frappe.desk.page.activity.activity.get_heatmap_data",
		callback: function(r) {
			if(r.message) {
				var heatmap = new Chart({
					parent: ".heatmap",
					type: 'heatmap',
					height: 100,
					start: new Date(moment().subtract(1, 'year').toDate()),
					count_label: "actions",
					discrete_domains: 0
				});

				heatmap.update(r.message);
			}
		}
	})
}<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, vars: true, white: true, plusplus: true*/
/*global Backbone, $, _, window, templateEngine, GraphViewerUI */
/*global require*/
(function() {

  "use strict";

  window.GraphView = Backbone.View.extend({
    el: '#content',

    template: templateEngine.createTemplate("graphView.ejs"),

    initialize: function () {
      this.newLineTmpl = templateEngine.createTemplate("graphViewGroupByEntry.ejs");
      this.graphs = [];
      this.i = 1;
    },

    events: {
      "click input[type='radio'][name='loadtype']": "toggleLoadtypeDisplay",
      "click #createViewer": "createViewer",
      "click #add_group_by": "insertNewAttrLine",
      "click input[type='radio'][name='colour']": "toggleColourDisplay",
      "click .gv_internal_remove_line": "removeAttrLine"
    },

    removeAttrLine: function(e) {
      var g = $(e.currentTarget)
        .parent()
        .parent(),
        set = g.parent();
      set.get(0).removeChild(g.get(0));
    },

    insertNewAttrLine: function() {
      this.i++;
      var next = this.newLineTmpl.render({id: this.i});
      $("#group_by_list").append(next);
    },

    toggleLoadtypeDisplay: function() {
      var selected = $("input[type='radio'][name='loadtype']:checked").attr("id");
      if (selected === "collections") {
        $("#collection_config").css("display", "block");
        $("#graph_config").css("display", "none");
      } else {
        $("#collection_config").css("display", "none");
        $("#graph_config").css("display", "block");
      }
    },

    toggleColourDisplay: function() {
      var selected = $("input[type='radio'][name='colour']:checked").attr("id");
      if (selected === "samecolour") {
        $("#colourAttribute_config").css("display", "none");
        return;
      }
      $("#colourAttribute_config").css("display", "block");
    },

    createViewer: function() {
      var ecol,
        ncol,
        aaconfig,
        undirected,
        randomStart,
        groupByAttribute,
        label,
        color,
        config,
        sameColor,
        width,
        self = this;

      undirected = !!$("#undirected").attr("checked");
      label = $("#nodeLabel").val();
      sameColor = $("input[type='radio'][name='colour']:checked").attr("id") === "samecolour";
      if (sameColor) {
        color = label;
      } else {
        color = $("#nodeColor").val();
      }
      randomStart = !!$("#randomStart").attr("checked");

      var graphName;
      var selected = $("input[type='radio'][name='loadtype']:checked").attr("id");
      if (selected === "collections") {
        // selected two individual collections
        ecol = $("#edgeCollection").val();
        ncol = $("#nodeCollection").val();
      }
      else {
        // selected a "graph"
        graphName = $("#graphSelected").val();
        console.log(graphName);
        var graph = _.find(this.graphs, function(g) { return g._key === graphName; });

        if (graph) {
          ecol = graph.edges;
          ncol = graph.vertices;
        }
        console.log(ecol, ncol);
      }

      groupByAttribute = [];
      $("#group_by_list input").each(function() {
        var a = $(this).val();
        if (a) {
          groupByAttribute.push(a);
        }
      });

      aaconfig = {
        type: "arango",
        nodeCollection: ncol,
        edgeCollection: ecol,
        undirected: undirected,
        graph: graphName,
        baseUrl: require("internal").arango.databasePrefix("/")
      };

      if (groupByAttribute.length > 0) {
        aaconfig.prioList = groupByAttribute;
      }

      if (label !== undefined && label !== "") {
        config = {
          nodeShaper: {
            label: label
          }
        };
      }
      if (color !== undefined && color !== "") {
        config.nodeShaper = config.nodeShaper || {};
        config.nodeShaper.color = {
          type: "attribute",
          key: color
        };
      }
      width = this.width || $("#content").width();

      $("#background").remove();
      if (randomStart) {
        $.ajax({
          cache: false,
          type: 'PUT',
          url: '/_api/simple/any',
          data: JSON.stringify({
            collection: ncol
          }),
          contentType: "application/json",
          success: function(data) {
            self.ui = new GraphViewerUI($("#content")[0],
                                        aaconfig,
                                        width,
                                        680,
                                        config,
                                        (data.document && data.document._id));
          }
        });
      } else {
        self.ui = new GraphViewerUI($("#content")[0], aaconfig, width, 680, config);
      }
    },

    handleResize: function(w) {
      this.width = w;
      if (this.ui) {
        this.ui.changeWidth(w);
      }
    },

    render: function() {
      var self = this;
      $.ajax({
        cache: false,
        type: 'GET',
        url: "/_api/graph",
        contentType: "application/json",
        success: function(data) {
          self.graphs = data.graphs;
          $(self.el).html(self.template.render({
            col: self.collection,
            gs: _.pluck(self.graphs, "_key")
          }));
          delete self.ui;
        }
      });
      return this;
    }

  });
}());
<commit_msg>Removed debug output<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, vars: true, white: true, plusplus: true*/
/*global Backbone, $, _, window, templateEngine, GraphViewerUI */
/*global require*/
(function() {

  "use strict";

  window.GraphView = Backbone.View.extend({
    el: '#content',

    template: templateEngine.createTemplate("graphView.ejs"),

    initialize: function () {
      this.newLineTmpl = templateEngine.createTemplate("graphViewGroupByEntry.ejs");
      this.graphs = [];
      this.i = 1;
    },

    events: {
      "click input[type='radio'][name='loadtype']": "toggleLoadtypeDisplay",
      "click #createViewer": "createViewer",
      "click #add_group_by": "insertNewAttrLine",
      "click input[type='radio'][name='colour']": "toggleColourDisplay",
      "click .gv_internal_remove_line": "removeAttrLine"
    },

    removeAttrLine: function(e) {
      var g = $(e.currentTarget)
        .parent()
        .parent(),
        set = g.parent();
      set.get(0).removeChild(g.get(0));
    },

    insertNewAttrLine: function() {
      this.i++;
      var next = this.newLineTmpl.render({id: this.i});
      $("#group_by_list").append(next);
    },

    toggleLoadtypeDisplay: function() {
      var selected = $("input[type='radio'][name='loadtype']:checked").attr("id");
      if (selected === "collections") {
        $("#collection_config").css("display", "block");
        $("#graph_config").css("display", "none");
      } else {
        $("#collection_config").css("display", "none");
        $("#graph_config").css("display", "block");
      }
    },

    toggleColourDisplay: function() {
      var selected = $("input[type='radio'][name='colour']:checked").attr("id");
      if (selected === "samecolour") {
        $("#colourAttribute_config").css("display", "none");
        return;
      }
      $("#colourAttribute_config").css("display", "block");
    },

    createViewer: function() {
      var ecol,
        ncol,
        aaconfig,
        undirected,
        randomStart,
        groupByAttribute,
        label,
        color,
        config,
        sameColor,
        width,
        self = this;

      undirected = !!$("#undirected").attr("checked");
      label = $("#nodeLabel").val();
      sameColor = $("input[type='radio'][name='colour']:checked").attr("id") === "samecolour";
      if (sameColor) {
        color = label;
      } else {
        color = $("#nodeColor").val();
      }
      randomStart = !!$("#randomStart").attr("checked");

      var graphName;
      var selected = $("input[type='radio'][name='loadtype']:checked").attr("id");
      if (selected === "collections") {
        // selected two individual collections
        ecol = $("#edgeCollection").val();
        ncol = $("#nodeCollection").val();
      }
      else {
        // selected a "graph"
        graphName = $("#graphSelected").val();
        var graph = _.find(this.graphs, function(g) { return g._key === graphName; });
        if (graph) {
          ecol = graph.edges;
          ncol = graph.vertices;
        }
      }

      groupByAttribute = [];
      $("#group_by_list input").each(function() {
        var a = $(this).val();
        if (a) {
          groupByAttribute.push(a);
        }
      });

      aaconfig = {
        type: "arango",
        nodeCollection: ncol,
        edgeCollection: ecol,
        undirected: undirected,
        graph: graphName,
        baseUrl: require("internal").arango.databasePrefix("/")
      };

      if (groupByAttribute.length > 0) {
        aaconfig.prioList = groupByAttribute;
      }

      if (label !== undefined && label !== "") {
        config = {
          nodeShaper: {
            label: label
          }
        };
      }
      if (color !== undefined && color !== "") {
        config.nodeShaper = config.nodeShaper || {};
        config.nodeShaper.color = {
          type: "attribute",
          key: color
        };
      }
      width = this.width || $("#content").width();

      $("#background").remove();
      if (randomStart) {
        $.ajax({
          cache: false,
          type: 'PUT',
          url: '/_api/simple/any',
          data: JSON.stringify({
            collection: ncol
          }),
          contentType: "application/json",
          success: function(data) {
            self.ui = new GraphViewerUI($("#content")[0],
                                        aaconfig,
                                        width,
                                        680,
                                        config,
                                        (data.document && data.document._id));
          }
        });
      } else {
        self.ui = new GraphViewerUI($("#content")[0], aaconfig, width, 680, config);
      }
    },

    handleResize: function(w) {
      this.width = w;
      if (this.ui) {
        this.ui.changeWidth(w);
      }
    },

    render: function() {
      var self = this;
      $.ajax({
        cache: false,
        type: 'GET',
        url: "/_api/graph",
        contentType: "application/json",
        success: function(data) {
          self.graphs = data.graphs;
          $(self.el).html(self.template.render({
            col: self.collection,
            gs: _.pluck(self.graphs, "_key")
          }));
          delete self.ui;
        }
      });
      return this;
    }

  });
}());
<|endoftext|>


<commit_before>$(document).ready(function(){
    'use strict';

    // This is the js that powers the search box
    $(':input[name=filter]').on('input', function() {
        // Get value just typed into textbox -- see .toLowerCase()
        var val = this.value.toLowerCase();

        // Find all .user-profile divs
        $('#app-grid').find('.app-tile')
            // Find those that should be visible
            .filter(function() {
                return $(this).data('id').toLowerCase().indexOf( val ) > -1;
            })
            // Make them visible
            .show()
            // Now go back and get only the visible ones
            .end().filter(':visible')
            // Filter only those for which typed value 'val' does not match the `data-id` value
            .filter(function() {
                return $(this).data('id').toLowerCase().indexOf( val ) === -1;
            })
            // Fade those out
            .fadeOut();
    });

    // Search input: Highlight, Align, Focus
    var filter = $(':input[name=filter]');
    $(filter).focus();
    $('.filter .mui-textfield').addClass('yellow-border');
    $('.filter img').addClass('yellow-border');
    $('svg.clear').addClass('yellow-border');
    $(filter).focusin(function() {
        $(filter).css('text-align', 'left');
    });
    $(filter).on('focusin mouseover', function() {
        $('.filter .mui-textfield').addClass('yellow-border');
        $('.filter img').addClass('yellow-border');
        $('svg.clear').addClass('yellow-border');
    });
    $(filter).mouseout(function() {
        var focus = $(filter).is(':focus');
        if (!focus) {
            $('.filter .mui-textfield').removeClass('yellow-border');
            $('.filter img').removeClass('yellow-border');
            $('svg.clear').removeClass('yellow-border');
        }
    });
    $(filter).focusout(function() {
        $('.filter .mui-textfield').removeClass('yellow-border');
        $('.filter img').removeClass('yellow-border');
        $('svg.clear').removeClass('yellow-border');
        if ($(filter).val() == '') {
            $(filter).css('text-align', 'center');
        } else {
            $(filter).css('text-align', 'left');
        }
    });

    // Clear the search
    $('svg.clear').click(function() {
        $(filter).val('');
        $('#app-grid').find('.app-tile').show();
        $(filter).css('text-align', 'center');
    });

    // Search input mobile: Align
    var filter_mobile = $('.search-mobile :input[name=filter]');
    $(filter_mobile).focusin(function() {
        $(filter_mobile).css('text-align', 'left');
    });
    $(filter_mobile).focusout(function() {
        if ($(filter_mobile).val() == '') {
            $(filter_mobile).css('text-align', 'center');
        } else {
            $(filter_mobile).css('text-align', 'left');
        }
    });

    // Highlight app tiles
    $('a.app-tile').hover(
        function() {
            $(this).find('.app-logo').addClass('yellow-border');
        },
        function() {
            $(this).find('.app-logo').removeClass('yellow-border');
        }
    );

    // Mobile search toggle
    $('.search-button button').click(function() {
        // Make sure user menu is hidden
        $('.user-menu').hide();
        $('.menu').removeClass('enabled');
        // Make sure we have the right logo and menu placement
        $('.logo-large').show();
        $('.logo-small').addClass('mui--hidden-xs');
        $('.mui-appbar').removeClass('menu-enabled');
        $('.search-button').removeClass('menu-enabled');
        // Show search input and invert button
        $('.search-mobile').fadeToggle();
        $('.search-button').toggleClass('invert');
    });

    // Toggle user menu
    $('.menu').click(function() {
        $('.user-menu').toggle();
        $('.menu').toggleClass('enabled');

        // If search-button is visible it's mobile viewport
        if ($('.search-button').is(':visible')) {
            // Make sure search input is hidden
            $('.search-mobile').hide();
            $('.search-button').removeClass('invert');
            // Toggle logo size and menu
            $('.logo-large').toggle();
            $('.logo-small').toggleClass('mui--hidden-xs');
            $('.mui-appbar').toggleClass('menu-enabled');
            $('.search-button').toggleClass('menu-enabled');
        }
    });
    $('.content').click(function() {
        $('.user-menu').hide();
        $('.menu').removeClass('enabled');
    });

    // Nightly alert
    if (window.navigator.userAgent.indexOf('Firefox') < 0) {
        $('#alert-nightly').show();
    }

    // Alerts ack
    $('#submit-alert').click(function() {
        var alert_id = $('#submit-alert').data('alert-id');
        $.ajax({
            url: '/alert/' + alert_id,
            type: 'POST',
            dataType   : 'json',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify({ 'alert_action': 'acknowledge' })
        });
    });

    // Escalate alert
    $('#escalate-alert').click(function() {
        var alert_id = $('#submit-alert').data('alert-id');
        $.ajax({
            url: '/alert/' + alert_id,
            type: 'POST',
            dataType   : 'json',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify({ 'alert_action': 'escalate' })
        });
    });

    // False Positive alert
    $('#false-positive-alert').click(function() {
        var alert_id = $('#submit-alert').data('alert-id');
        $.ajax({
            url: '/alert/' + alert_id,
            type: 'POST',
            dataType   : 'json',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify({ 'alert_action': 'false-positive' })
        });
    });

    // Alerts close button
    $('.closebtn').click(function() {
        $(this).parent('div').parent('.alert').slideUp();
    });
});
<commit_msg>Manage focus when opening search field<commit_after>$(document).ready(function(){
    'use strict';

    // This is the js that powers the search box
    $(':input[name=filter]').on('input', function() {
        // Get value just typed into textbox -- see .toLowerCase()
        var val = this.value.toLowerCase();

        // Find all .user-profile divs
        $('#app-grid').find('.app-tile')
            // Find those that should be visible
            .filter(function() {
                return $(this).data('id').toLowerCase().indexOf( val ) > -1;
            })
            // Make them visible
            .show()
            // Now go back and get only the visible ones
            .end().filter(':visible')
            // Filter only those for which typed value 'val' does not match the `data-id` value
            .filter(function() {
                return $(this).data('id').toLowerCase().indexOf( val ) === -1;
            })
            // Fade those out
            .fadeOut();
    });

    // Search input: Highlight, Align, Focus
    var filter = $(':input[name=filter]');
    $(filter).focus();
    $('.filter .mui-textfield').addClass('yellow-border');
    $('.filter img').addClass('yellow-border');
    $('svg.clear').addClass('yellow-border');
    $(filter).focusin(function() {
        $(filter).css('text-align', 'left');
    });
    $(filter).on('focusin mouseover', function() {
        $('.filter .mui-textfield').addClass('yellow-border');
        $('.filter img').addClass('yellow-border');
        $('svg.clear').addClass('yellow-border');
    });
    $(filter).mouseout(function() {
        var focus = $(filter).is(':focus');
        if (!focus) {
            $('.filter .mui-textfield').removeClass('yellow-border');
            $('.filter img').removeClass('yellow-border');
            $('svg.clear').removeClass('yellow-border');
        }
    });
    $(filter).focusout(function() {
        $('.filter .mui-textfield').removeClass('yellow-border');
        $('.filter img').removeClass('yellow-border');
        $('svg.clear').removeClass('yellow-border');
        if ($(filter).val() == '') {
            $(filter).css('text-align', 'center');
        } else {
            $(filter).css('text-align', 'left');
        }
    });

    // Clear the search
    $('svg.clear').click(function() {
        $(filter).val('');
        $('#app-grid').find('.app-tile').show();
        $(filter).css('text-align', 'center');
    });

    // Search input mobile: Align
    var filter_mobile = $('.search-mobile :input[name=filter]');
    $(filter_mobile).focusin(function() {
        $(filter_mobile).css('text-align', 'left');
    });
    $(filter_mobile).focusout(function() {
        if ($(filter_mobile).val() == '') {
            $(filter_mobile).css('text-align', 'center');
        } else {
            $(filter_mobile).css('text-align', 'left');
        }
    });

    // Highlight app tiles
    $('a.app-tile').hover(
        function() {
            $(this).find('.app-logo').addClass('yellow-border');
        },
        function() {
            $(this).find('.app-logo').removeClass('yellow-border');
        }
    );

    // Mobile search toggle
    $('.search-button button').click(function() {
        // Make sure user menu is hidden
        $('.user-menu').hide();
        $('.menu').removeClass('enabled');
        // Make sure we have the right logo and menu placement
        $('.logo-large').show();
        $('.logo-small').addClass('mui--hidden-xs');
        $('.mui-appbar').removeClass('menu-enabled');
        $('.search-button').removeClass('menu-enabled');
        // Show search input and invert button
        if ( $('.search-mobile').is(':visible')) {
            $('.search-mobile').fadeOut();
            $('.search-button').removeClass('invert');
            $('.search-button button:first').focus();
        }
        else {
            $('.search-mobile').fadeIn();
            $('.search-button').addClass('invert');
            $('.search-mobile input:first').focus();
        }
    });

    // Toggle user menu
    $('.menu').click(function() {
        $('.user-menu').toggle();
        $('.menu').toggleClass('enabled');

        // If search-button is visible it's mobile viewport
        if ($('.search-button').is(':visible')) {
            // Make sure search input is hidden
            $('.search-mobile').hide();
            $('.search-button').removeClass('invert');
            // Toggle logo size and menu
            $('.logo-large').toggle();
            $('.logo-small').toggleClass('mui--hidden-xs');
            $('.mui-appbar').toggleClass('menu-enabled');
            $('.search-button').toggleClass('menu-enabled');
        }
    });
    $('.content').click(function() {
        $('.user-menu').hide();
        $('.menu').removeClass('enabled');
    });

    // Nightly alert
    if (window.navigator.userAgent.indexOf('Firefox') < 0) {
        $('#alert-nightly').show();
    }

    // Alerts ack
    $('#submit-alert').click(function() {
        var alert_id = $('#submit-alert').data('alert-id');
        $.ajax({
            url: '/alert/' + alert_id,
            type: 'POST',
            dataType   : 'json',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify({ 'alert_action': 'acknowledge' })
        });
    });

    // Escalate alert
    $('#escalate-alert').click(function() {
        var alert_id = $('#submit-alert').data('alert-id');
        $.ajax({
            url: '/alert/' + alert_id,
            type: 'POST',
            dataType   : 'json',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify({ 'alert_action': 'escalate' })
        });
    });

    // False Positive alert
    $('#false-positive-alert').click(function() {
        var alert_id = $('#submit-alert').data('alert-id');
        $.ajax({
            url: '/alert/' + alert_id,
            type: 'POST',
            dataType   : 'json',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify({ 'alert_action': 'false-positive' })
        });
    });

    // Alerts close button
    $('.closebtn').click(function() {
        $(this).parent('div').parent('.alert').slideUp();
    });
});
<|endoftext|>


<commit_before>'use strict';

var cp = require('child_process');
var os = require('os');

if (os.type() === 'Linux') {
  cp.exec('cd pngdefry\/source && make && mv pngdefry ..\/bin\/linux', {});
}
<commit_msg>create linux dir<commit_after>'use strict';

var cp = require('child_process');
var os = require('os');

if (os.type() === 'Linux') {
  cp.exec('mkdir -p pngdefry\/bin\/linux && cd pngdefry\/source && make &&  && mv pngdefry ..\/bin\/linux', {});
}
<|endoftext|>


<commit_before>import DI from '@uikit/di';
import getContextShape from './getContextShape';
import Validator from './Validator';
import Store from './Store';

export default (
  FormComponent,
  { name = 'form', schema, errorCodes = {} } = {},
  mapStateToProps,
) => {
  const hasMapStateToProps = typeof mapStateToProps === 'function';
  const Component = DI.get('@uikit/PureComponent');

  return class FormContainer extends Component {
    constructor(props, ...args) {
      super(props, ...args);

      let validator;

      if (schema) {
        validator = new Validator();
        validator.schema = schema;
      }

      this.form = new Store({
        ...this._storeConfing,
        name,
        validator,
        errorCodes,
      });

      this._getFormName = () => name;

      this.state = hasMapStateToProps
        ? mapStateToProps(form, { ...props }) || {}
        : {};

      this.onSubmit = this.onSubmit.bind(this);
    }

    static childContextTypes = {
      formState: getContextShape(),
    };

    getChildContext() {
      return {
        formState: {
          getValues: () => {
            return this.getStore().getValues();
          },
          getChanges: () => {
            return this.getStore().getChanges();
          },
          getErrors() {
            return this.getStore().getErrors();
          },
          getErrorText() {
            return this.getStore().getErrorText();
          },
          registerCallback: callback => {
            return this.getStore().registerCallback(callback);
          },
          isValid: () => {
            return this.getStore().isValid();
          },
          isDisabled: () => {
            return this.getStore().isFormDisabled();
          },
          isDirty: () => {
            return !!Object.keys(this.getStore().getChanges() || {}).length;
          },
          setValues: values => {
            this.getStore().setValues(values);
          },
          showError: (name, errorText) => {
            this.getStore().showFieldError(name, errorText);
          },
          getStore: () => {
            return this.getStore();
          },
          disableForm: () => {
            this.getStore().setDisabledStatus(true);
          },
          enableForm: () => {
            this.getStore().setDisabledStatus(false);
          },
          submit: () => {
            this.getStore().markAsSubmitted();
          },
        },
      };
    }

    getStore() {
      if (!this.form) {
        throw new Error(
          `Form error: form state does't exist, you must check component unmount status in asynchronous function`,
        );
      }

      return this.form;
    }

    componentDidMount() {
      const store = this.getStore();

      this._unregister = store._dispatcher.register(() => {
        if (hasMapStateToProps) {
          const newProps = mapStateToProps(this.form, {
            ...(this.props || {}),
          });

          if (newProps) {
            this.setState(newProps);
          }
        }
      });
    }

    componentWillUnmount() {
      this.form = null;

      this._unregister && this._unregister();
    }

    onSubmit() {
      const { onSubmit } = this.props;

      this.getStore().markAsSubmitted();
      onSubmit && onSubmit();
    }

    render() {
      const createElement = DI.get('@uikit/createElement');
      return createElement(FormComponent, {
        ...this.props,
        ...this.state,
        onSubmit: this.onSubmit,
        form: this.getChildContext().formState,
      });
    }
  };
};
<commit_msg>fix bug<commit_after>import DI from '@uikit/di';
import getContextShape from './getContextShape';
import Validator from './Validator';
import Store from './Store';

export default (
  FormComponent,
  { name = 'form', schema, errorCodes = {} } = {},
  mapStateToProps,
) => {
  const hasMapStateToProps = typeof mapStateToProps === 'function';
  const Component = DI.get('@uikit/PureComponent');

  return class FormContainer extends Component {
    constructor(props, ...args) {
      super(props, ...args);

      let validator;

      if (schema) {
        validator = new Validator();
        validator.schema = schema;
      }

      this.form = new Store({
        ...this._storeConfing,
        name,
        validator,
        errorCodes,
      });

      this._getFormName = () => name;

      this.state = hasMapStateToProps
        ? mapStateToProps(this.form, { ...props }) || {}
        : {};

      this.onSubmit = this.onSubmit.bind(this);
    }

    static childContextTypes = {
      formState: getContextShape(),
    };

    getChildContext() {
      return {
        formState: {
          getValues: () => {
            return this.getStore().getValues();
          },
          getChanges: () => {
            return this.getStore().getChanges();
          },
          getErrors() {
            return this.getStore().getErrors();
          },
          getErrorText() {
            return this.getStore().getErrorText();
          },
          registerCallback: callback => {
            return this.getStore().registerCallback(callback);
          },
          isValid: () => {
            return this.getStore().isValid();
          },
          isDisabled: () => {
            return this.getStore().isFormDisabled();
          },
          isDirty: () => {
            return !!Object.keys(this.getStore().getChanges() || {}).length;
          },
          setValues: values => {
            this.getStore().setValues(values);
          },
          showError: (name, errorText) => {
            this.getStore().showFieldError(name, errorText);
          },
          getStore: () => {
            return this.getStore();
          },
          disableForm: () => {
            this.getStore().setDisabledStatus(true);
          },
          enableForm: () => {
            this.getStore().setDisabledStatus(false);
          },
          submit: () => {
            this.getStore().markAsSubmitted();
          },
        },
      };
    }

    getStore() {
      if (!this.form) {
        throw new Error(
          `Form error: form state does't exist, you must check component unmount status in asynchronous function`,
        );
      }

      return this.form;
    }

    componentDidMount() {
      const store = this.getStore();

      this._unregister = store._dispatcher.register(() => {
        if (hasMapStateToProps) {
          const newProps = mapStateToProps(this.form, {
            ...(this.props || {}),
          });

          if (newProps) {
            this.setState(newProps);
          }
        }
      });
    }

    componentWillUnmount() {
      this.form = null;

      this._unregister && this._unregister();
    }

    onSubmit() {
      const { onSubmit } = this.props;

      this.getStore().markAsSubmitted();
      onSubmit && onSubmit();
    }

    render() {
      const createElement = DI.get('@uikit/createElement');
      return createElement(FormComponent, {
        ...this.props,
        ...this.state,
        onSubmit: this.onSubmit,
        form: this.getChildContext().formState,
      });
    }
  };
};
<|endoftext|>