<commit_before>/*:
 * @plugindesc This plugin applies the lighting effect. <RS_SimpleLight>
 * @author biud436
 *
 * @help
 *
 * This plugin commands allows you to enable or disable a lantern.
 *
 * RS_SimpleLight Enable
 * RS_SimpleLight Disable
 *
 * ===============================================================
 * Version Log
 * ===============================================================
 * 2016.02.13 (v1.0.0) - First Release
 * 2018.12.30 (v1.1.0) :
 * - Now it is supported in RPG Maker MV v1.6.1.
 * (I've been rewritten shader for RPG Maker MV v1.6.1)
 */

var Imported = Imported || {};
Imported.RS_SimpleLight = true;

var RS = RS || {};
RS.SimpleLight = RS.SimpleLight || {};

(function($) {

  'use strict';

  var parameters = $plugins.filter(function(i) {
    return i.description.contains("<RS_SimpleLight>");
  });

  parameters = (parameters.length > 0) && parameters[0].parameters;

  PIXI.SimpleLightFilter = function(options) {

    var vertexSrc = [
      'attribute vec2 aVertexPosition;',
      'attribute vec2 aTextureCoord;',

      'uniform mat3 projectionMatrix;',

      'varying vec2 vTextureCoord;',

      'void main(void){',
      '    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);',
      '    vTextureCoord = aTextureCoord;',
      '}'
    ].join('\n');

    var fragmentSrc = `

    precision mediump float;

    const float PI = 3.14159265359;
    const float TWO_PI = 6.28318530718;

    uniform vec2 u_resolution;
    uniform int u_dir;
    uniform float u_size;
    uniform vec2 u_position;
    uniform mat4 u_color;

    varying vec2 vTextureCoord;
    uniform sampler2D uSampler;

    uniform vec4 filterArea;
    uniform vec4 filterClamp;

    vec2 get_player_offset(int d) {
        vec2 offset = vec2(0.0);
        if(d == 2) {
            offset = vec2(0.0, 1.0) * 0.688;
        } else if(d == 4) {
            offset = vec2(-1.0, 0.0) * 0.792;
        } else if(d == 6) {
            offset = vec2(1.0, 0.0) * 0.656;
        } else if(d == 8) {
            offset = vec2(0.0, -1.0) * 0.760;
        }
        return offset;
    }

    float get_player_direction(int d) {
        float angle = PI;
        if(d == 8) {
            angle = PI;
        } else if(d == 6) {
            angle = 0.5235987755982988;
        } else if(d == 4) {
            angle = 1.5707963267948966;
        } else if(d == 2) {
            angle = TWO_PI;
        }
        return angle;
    }

    // Reference to
    // https://thebookofshaders.com/07/

    void main(void){
        vec2 st = (gl_FragCoord.xy - u_position) / u_resolution;
        // st.x *= u_resolution.x / u_resolution.y;
        vec4 baseColor = texture2D(uSampler, vTextureCoord);
        vec4 color = vec4(1.0);
        float d = 0.0;

        int dir = u_dir;

        vec2 offset = get_player_offset(dir);
        vec2 back_offset = u_position * vec2(1.0, 1.0);

        st *= mat2(2.0, 0.0, 0.0, 2.0);
        st -= back_offset * 2.0;
        st -= offset;

        int N = 3;

        float a = atan(st.x * 1.0, st.y * 1.0) + get_player_direction(dir);
        float r = TWO_PI / float(N);

        d = cos(floor(0.500 + a / r) * r - a ) * length(st * u_size);

        color = vec4(0.1) + vec4( 1.0 - smoothstep(0.128 , 0.378 , d));
        color *= u_color;
        gl_FragColor = baseColor * vec4(color.rgb, 1.0);
    }

    `;

    PIXI.Filter.call( this, vertexSrc, fragmentSrc);

    this.uniforms.u_resolution = [Graphics.boxWidth, Graphics.boxHeight];

    // 2, 4, 6, 8
    this.uniforms.u_dir = 2;
    this.uniforms.u_size = 1.628;
    this.uniforms.u_position = [0.5, 0.5];

    // Tone
    this.uniforms.u_color = [
      1.0, 0.0, 0.0, 0.0,
      0.0, 1.0, 0.0, 0.0,
      0.0, 0.0, 1.0, 0.0,
      0.0, 0.0, 0.0, 1.0
    ];

    this.enabled = true;
    this.resolution = 1;

  };

  PIXI.SimpleLightFilter.prototype = Object.create( PIXI.Filter.prototype );
  PIXI.SimpleLightFilter.prototype.constructor = PIXI.SimpleLightFilter;

  PIXI.SimpleLightFilter.prototype.updatePositionX = function() {
    var value = ( ($gamePlayer.screenX()) / this.uniforms.u_resolution[0]);
    this.uniforms.u_position[0] = value || 0.0;
  };

  PIXI.SimpleLightFilter.prototype.updatePositionY = function() {
    var value = ( ($gamePlayer.screenY()) / this.uniforms.u_resolution[1]);
    this.uniforms.u_position[1] = value || 0.0;
  };

  PIXI.SimpleLightFilter.prototype.updatePosition = function() {
    this.updatePositionX();
    this.updatePositionY();
  };

  PIXI.SimpleLightFilter.prototype.setResolution = function(options) {
    this.uniforms.u_resolution = options;
  };

  PIXI.SimpleLightFilter.prototype.setDirection = function(dir) {
    this.uniforms.u_dir = dir;
  };

  PIXI.SimpleLightFilter.prototype.setSize = function(value) {
    if(value <= 1e-3) value = 1e-3;
    if(value >= 1.000) value = 1.000;
    this.uniforms.u_size = value;
  };

  PIXI.SimpleLightFilter.prototype.setDefaultColorTone = function() {
    this.uniforms.u_color = [
      1.0, 0.0, 0.0, 0.0,
      0.0, 1.0, 0.0, 0.0,
      0.0, 0.0, 1.0, 0.0,
      0.0, 0.0, 0.0, 1.0
    ];
  };

  PIXI.SimpleLightFilter.prototype.setRedColorTone = function() {
    this.uniforms.u_color = [
      0.8, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 1.0
    ];
  };

  /**
   * @param {Array} color
   */
  PIXI.SimpleLightFilter.prototype.setColorTone = function(red, green, blue) {

    var r = parseFloat(red / 255.0);
    var g = parseFloat(green / 255.0);
    var b = parseFloat(blue / 255.0);

    this.uniforms.u_color = [
      r, 0.0, 0.0, 0.0,
      0.0, g, 0.0, 0.0,
      0.0, 0.0, b, 0.0,
      0.0, 0.0, 0.0, 1.0
    ];

  };

  //=================================================================
  // Spriteset_Map
  //=================================================================

  var alias_Spriteset_Map_createUpperLayer = Spriteset_Map.prototype.createUpperLayer;
  Spriteset_Map.prototype.createUpperLayer = function() {
    alias_Spriteset_Map_createUpperLayer.call(this);
    this.createSimpleLightFilter();
  };

  Spriteset_Map.prototype.createSimpleLightFilter = function() {
    var isValid = this._simpleLightFilter;
    var target = this._baseSprite;

    if(!isValid) {
      this._simpleLightFilter = new PIXI.SimpleLightFilter();
      if(!target.filters) {
        target.filters = [];
      }
      target.filters = [this._simpleLightFilter].concat(target.filters);
      if(this._simpleLightFilter) {
        this._simpleLightFilter.updatePosition();
      }
    } else {
      if(!target.filters) {
        target.filters = [];
      }
      target.filters = target.filters.filter(function(filter) {
        return filter !== isValid;
      }, this);
    }
  };

  var alias_Spriteset_Map_update = Spriteset_Map.prototype.update;
  Spriteset_Map.prototype.update = function () {
    alias_Spriteset_Map_update.call(this);
    this.updateSimpleLightFilter();
  };

  Spriteset_Map.prototype.updateSimpleLightFilter = function () {
    if(!$gameSystem) return;
    if(!this._simpleLightFilter) return;
    var config = $gameSystem._lightProp;
    var isValid = $gameSystem.enabledLight();
    this._simpleLightFilter.enabled = isValid;
    if(isValid) {
      this._simpleLightFilter.updatePosition();
      this._simpleLightFilter.setSize(config["size"]);
      this._simpleLightFilter.setDirection(config["direction"]);
      this._simpleLightFilter.setResolution(config["resolution"]);
    }
   };

  //======================================================================
  // Game_System
  //======================================================================

  var alias_Game_System_initialize = Game_System.prototype.initialize;
  Game_System.prototype.initialize = function() {
    alias_Game_System_initialize.call(this);
    this.initLightProperty();
  };

  Game_System.prototype.initLightProperty = function () {
    this._lightProp = {
      'light': false,
      'size' : 1.618,
      'direction': 2,
      'resolution': [816, 624]
    };
  };

  Game_System.prototype.updateLightProperty = function () {
    if(!this._lightProp) return;
    this.setLightProperty('direction', $gamePlayer.direction());
    this.setLightProperty('resolution', [Graphics.boxWidth, Graphics.boxHeight]);
  };

  Game_System.prototype.setLightProperty = function (name, value) {
    if(this._lightProp) {
      this._lightProp[name] = value;
      return this._lightProp[name];
    }
    return 0.0;
  };

  Game_System.prototype.enabledLight = function () {
    return this._lightProp['light'] === true;
  };

  var alias_Game_Map_update = Game_Map.prototype.update;
  Game_Map.prototype.update = function(sceneActive) {
    alias_Game_Map_update.call(this, sceneActive);
    $gameSystem.updateLightProperty();
  };

  //-----------------------------------------------------------------------------
  // Game_Interpreter
  //
  //

  var alias_Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
  Game_Interpreter.prototype.pluginCommand = function(command, args) {
      alias_Game_Interpreter_pluginCommand.call(this, command, args);
      if(command === "RS_SimpleLight") {
        switch(args[0]) {
          case 'Enable':
            $gameSystem.setLightProperty('light', true);
            break;
          case 'Disable':
            $gameSystem.setLightProperty('light', false);
            break;
        }
      }
  };

})(RS.SimpleLight);
<commit_msg>v1.1.01<commit_after>/*:
 * @plugindesc This plugin applies the lighting effect. <RS_SimpleLight>
 * @author biud436
 *
 * @help
 *
 * This plugin commands allows you to enable or disable a lantern.
 *
 * RS_SimpleLight Enable
 * RS_SimpleLight Disable
 *
 * ===============================================================
 * Version Log
 * ===============================================================
 * 2016.02.13 (v1.0.0) - First Release
 * 2018.12.30 (v1.1.0) :
 * - Now it is supported in RPG Maker MV v1.6.1.
 * (I've been rewritten shader for RPG Maker MV v1.6.1)
 * 2019.02.24 (v1.1.01) :
 * - Fixed an issue that is not loaded a save file that you saved before using this plugin.
 */

var Imported = Imported || {};
Imported.RS_SimpleLight = true;

var RS = RS || {};
RS.SimpleLight = RS.SimpleLight || {};

(function($) {

  'use strict';

  var parameters = $plugins.filter(function(i) {
    return i.description.contains("<RS_SimpleLight>");
  });

  parameters = (parameters.length > 0) && parameters[0].parameters;

  PIXI.SimpleLightFilter = function(options) {

    var vertexSrc = [
      'attribute vec2 aVertexPosition;',
      'attribute vec2 aTextureCoord;',

      'uniform mat3 projectionMatrix;',

      'varying vec2 vTextureCoord;',

      'void main(void){',
      '    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);',
      '    vTextureCoord = aTextureCoord;',
      '}'
    ].join('\n');

    var fragmentSrc = `

    precision mediump float;

    const float PI = 3.14159265359;
    const float TWO_PI = 6.28318530718;

    uniform vec2 u_resolution;
    uniform int u_dir;
    uniform float u_size;
    uniform vec2 u_position;
    uniform mat4 u_color;

    varying vec2 vTextureCoord;
    uniform sampler2D uSampler;

    uniform vec4 filterArea;
    uniform vec4 filterClamp;

    vec2 get_player_offset(int d) {
        vec2 offset = vec2(0.0);
        if(d == 2) {
            offset = vec2(0.0, 1.0) * 0.688;
        } else if(d == 4) {
            offset = vec2(-1.0, 0.0) * 0.792;
        } else if(d == 6) {
            offset = vec2(1.0, 0.0) * 0.656;
        } else if(d == 8) {
            offset = vec2(0.0, -1.0) * 0.760;
        }
        return offset;
    }

    float get_player_direction(int d) {
        float angle = PI;
        if(d == 8) {
            angle = PI;
        } else if(d == 6) {
            angle = 0.5235987755982988;
        } else if(d == 4) {
            angle = 1.5707963267948966;
        } else if(d == 2) {
            angle = TWO_PI;
        }
        return angle;
    }

    // Reference to
    // https://thebookofshaders.com/07/

    void main(void){
        vec2 st = (gl_FragCoord.xy - u_position) / u_resolution;
        // st.x *= u_resolution.x / u_resolution.y;
        vec4 baseColor = texture2D(uSampler, vTextureCoord);
        vec4 color = vec4(1.0);
        float d = 0.0;

        int dir = u_dir;

        vec2 offset = get_player_offset(dir);
        vec2 back_offset = u_position * vec2(1.0, 1.0);

        st *= mat2(2.0, 0.0, 0.0, 2.0);
        st -= back_offset * 2.0;
        st -= offset;

        int N = 3;

        float a = atan(st.x * 1.0, st.y * 1.0) + get_player_direction(dir);
        float r = TWO_PI / float(N);

        d = cos(floor(0.500 + a / r) * r - a ) * length(st * u_size);

        color = vec4(0.1) + vec4( 1.0 - smoothstep(0.128 , 0.378 , d));
        color *= u_color;
        gl_FragColor = baseColor * vec4(color.rgb, 1.0);
    }

    `;

    PIXI.Filter.call( this, vertexSrc, fragmentSrc);

    this.uniforms.u_resolution = [Graphics.boxWidth, Graphics.boxHeight];

    // 2, 4, 6, 8
    this.uniforms.u_dir = 2;
    this.uniforms.u_size = 1.628;
    this.uniforms.u_position = [0.5, 0.5];

    // Tone
    this.uniforms.u_color = [
      1.0, 0.0, 0.0, 0.0,
      0.0, 1.0, 0.0, 0.0,
      0.0, 0.0, 1.0, 0.0,
      0.0, 0.0, 0.0, 1.0
    ];

    this.enabled = true;
    this.resolution = 1;

  };

  PIXI.SimpleLightFilter.prototype = Object.create( PIXI.Filter.prototype );
  PIXI.SimpleLightFilter.prototype.constructor = PIXI.SimpleLightFilter;

  PIXI.SimpleLightFilter.prototype.updatePositionX = function() {
    var value = ( ($gamePlayer.screenX()) / this.uniforms.u_resolution[0]);
    this.uniforms.u_position[0] = value || 0.0;
  };

  PIXI.SimpleLightFilter.prototype.updatePositionY = function() {
    var value = ( ($gamePlayer.screenY()) / this.uniforms.u_resolution[1]);
    this.uniforms.u_position[1] = value || 0.0;
  };

  PIXI.SimpleLightFilter.prototype.updatePosition = function() {
    this.updatePositionX();
    this.updatePositionY();
  };

  PIXI.SimpleLightFilter.prototype.setResolution = function(options) {
    this.uniforms.u_resolution = options;
  };

  PIXI.SimpleLightFilter.prototype.setDirection = function(dir) {
    this.uniforms.u_dir = dir;
  };

  PIXI.SimpleLightFilter.prototype.setSize = function(value) {
    if(value <= 1e-3) value = 1e-3;
    if(value >= 1.000) value = 1.000;
    this.uniforms.u_size = value;
  };

  PIXI.SimpleLightFilter.prototype.setDefaultColorTone = function() {
    this.uniforms.u_color = [
      1.0, 0.0, 0.0, 0.0,
      0.0, 1.0, 0.0, 0.0,
      0.0, 0.0, 1.0, 0.0,
      0.0, 0.0, 0.0, 1.0
    ];
  };

  PIXI.SimpleLightFilter.prototype.setRedColorTone = function() {
    this.uniforms.u_color = [
      0.8, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 1.0
    ];
  };

  /**
   * @param {Array} color
   */
  PIXI.SimpleLightFilter.prototype.setColorTone = function(red, green, blue) {

    var r = parseFloat(red / 255.0);
    var g = parseFloat(green / 255.0);
    var b = parseFloat(blue / 255.0);

    this.uniforms.u_color = [
      r, 0.0, 0.0, 0.0,
      0.0, g, 0.0, 0.0,
      0.0, 0.0, b, 0.0,
      0.0, 0.0, 0.0, 1.0
    ];

  };

  //=================================================================
  // Spriteset_Map
  //=================================================================

  var alias_Spriteset_Map_createUpperLayer = Spriteset_Map.prototype.createUpperLayer;
  Spriteset_Map.prototype.createUpperLayer = function() {
    alias_Spriteset_Map_createUpperLayer.call(this);
    this.createSimpleLightFilter();
  };

  Spriteset_Map.prototype.createSimpleLightFilter = function() {
    var isValid = this._simpleLightFilter;
    var target = this._baseSprite;

    if(!isValid) {
      this._simpleLightFilter = new PIXI.SimpleLightFilter();
      if(!target.filters) {
        target.filters = [];
      }
      target.filters = [this._simpleLightFilter].concat(target.filters);
      if(this._simpleLightFilter) {
        this._simpleLightFilter.updatePosition();
      }
    } else {
      if(!target.filters) {
        target.filters = [];
      }
      target.filters = target.filters.filter(function(filter) {
        return filter !== isValid;
      }, this);
    }
  };

  var alias_Spriteset_Map_update = Spriteset_Map.prototype.update;
  Spriteset_Map.prototype.update = function () {
    alias_Spriteset_Map_update.call(this);
    this.updateSimpleLightFilter();
  };

  Spriteset_Map.prototype.updateSimpleLightFilter = function () {
    if(!$gameSystem) return;
    if(!this._simpleLightFilter) return;
    var config = $gameSystem._lightProp;
    var isValid = $gameSystem.enabledLight();
    this._simpleLightFilter.enabled = isValid;
    if(isValid) {
      this._simpleLightFilter.updatePosition();
      this._simpleLightFilter.setSize(config["size"]);
      this._simpleLightFilter.setDirection(config["direction"]);
      this._simpleLightFilter.setResolution(config["resolution"]);
    }
   };

  //======================================================================
  // Game_System
  //======================================================================

  var alias_Game_System_initialize = Game_System.prototype.initialize;
  Game_System.prototype.initialize = function() {
    alias_Game_System_initialize.call(this);
    this.initLightProperty();
  };

  Game_System.prototype.initLightProperty = function () {
    this._lightProp = {
      'light': false,
      'size' : 1.618,
      'direction': 2,
      'resolution': [816, 624]
    };
  };

  Game_System.prototype.updateLightProperty = function () {
    if(!this._lightProp) this.initLightProperty();
    this.setLightProperty('direction', $gamePlayer.direction());
    this.setLightProperty('resolution', [Graphics.boxWidth, Graphics.boxHeight]);
  };

  Game_System.prototype.setLightProperty = function (name, value) {
    if(!this._lightProp) this.initLightProperty();
    this._lightProp[name] = value;
    return this._lightProp[name];
  };

  Game_System.prototype.enabledLight = function () {
    if(!this._lightProp) this.initLightProperty();
    return this._lightProp['light'] === true;
  };

  var alias_Game_Map_update = Game_Map.prototype.update;
  Game_Map.prototype.update = function(sceneActive) {
    alias_Game_Map_update.call(this, sceneActive);
    $gameSystem.updateLightProperty();
  };

  //-----------------------------------------------------------------------------
  // Game_Interpreter
  //
  //

  var alias_Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
  Game_Interpreter.prototype.pluginCommand = function(command, args) {
      alias_Game_Interpreter_pluginCommand.call(this, command, args);
      if(command === "RS_SimpleLight") {
        switch(args[0]) {
          case 'Enable':
            $gameSystem.setLightProperty('light', true);
            break;
          case 'Disable':
            $gameSystem.setLightProperty('light', false);
            break;
        }
      }
  };

})(RS.SimpleLight);
<|endoftext|>


<commit_before>// @flow
import React, {Component} from 'react'
import _ from 'lodash'
import type {Props, ItemProps, TabBarButtonProps} from './tab-bar'
import {Box, Icon, Text, NativeTouchableWithoutFeedback} from './index.native'
import {globalStyles, globalColors} from '../styles'

class TabBarItem extends Component<void, ItemProps, void> {
  render () {
    return this.props.children
  }
}

class SimpleTabBarButton extends Component<void, ItemProps, void> {
  render () {
    const selectedColor = this.props.selectedColor || globalColors.blue
    return (
      <Box style={{...stylesTab, ...this.props.style}}>
        <Text type='BodySemibold' style={{...stylesLabel, color: this.props.selected ? globalColors.black_75 : globalColors.black_60}}>
          {this.props.label.toUpperCase()}
        </Text>
        {(!this.props.underlined || this.props.selected) && <Box style={stylesSelectedUnderline(this.props.selected ? selectedColor : 'transparent')} />}
        {!this.props.selected && this.props.underlined && <Box style={stylesUnselectedUnderline} />}
      </Box>
    )
  }
}

class TabBarButton extends Component<void, TabBarButtonProps, void> {
  render () {
    const backgroundColor = this.props.selected ? globalColors.darkBlue4 : globalColors.midnightBlue
    const badgeNumber = this.props.badgeNumber || 0

    return (
      <Box style={{...globalStyles.flexBoxColumn, backgroundColor, ...stylesTabBarButtonIcon, ...this.props.style}}>
        {this.props.source.type === 'icon'
          ? <Icon type={this.props.source.icon} style={{fontSize: 48, width: 80, textAlign: 'center', color: this.props.selected ? globalColors.blue3 : globalColors.blue3_40, ...this.props.styleIcon}} />
          : this.props.source.avatar}
        {badgeNumber > 0 &&
          <Box style={{...styleBadgeOuter, borderColor: backgroundColor, backgroundColor}}>
            <Box style={styleBadge}>
              <Text style={{flex: 0}} type='BadgeNumber'>{badgeNumber}</Text>
            </Box>
          </Box>}
        {!!this.props.label && <Text type='BodySemibold' style={{textAlign: 'center', ...this.props.styleLabel}}>{this.props.label}</Text>}
      </Box>
    )
  }
}

const styleBadgeOuter = {
  borderColor: globalColors.midnightBlue,
  borderWidth: 2,
  borderRadius: 10,
  position: 'absolute',
  top: 10,
  left: 40,
}

const styleBadge = {
  ...globalStyles.flexBoxRow,
  backgroundColor: globalColors.orange,
  borderColor: globalColors.orange,
  borderWidth: 2,
  paddingLeft: 2,
  paddingRight: 2,
  borderRadius: 10,
  flex: 0,
}

class TabBar extends Component {
  props: Props;

  _labels (): Array<React$Element<*>> {
    // TODO: Not sure why I have to wrap the child in a box, but otherwise touches won't work
    return (this.props.children || []).map((item: {props: ItemProps}, i) => {
      const key = item.props.label || _.get(item, 'props.tabBarButton.props.label') || i
      return (
        <NativeTouchableWithoutFeedback key={key} onPress={item.props.onClick || (() => {})}>
          <Box style={item.props.styleContainer}>
            {item.props.tabBarButton || <SimpleTabBarButton {...item.props} />}
          </Box>
        </NativeTouchableWithoutFeedback>
      )
    })
  }

  _content (): any {
    return (this.props.children || []).find(i => i.props.selected)
  }

  render () {
    const tabBarButtons = (
      <Box style={{...globalStyles.flexBoxRow, ...this.props.styleTabBar}}>
        {this._labels()}
      </Box>
    )

    return (
      <Box style={{...stylesContainer, ...this.props.style}}>
        {!this.props.tabBarOnBottom && tabBarButtons}
        {this._content()}
        {this.props.tabBarOnBottom && tabBarButtons}
      </Box>
    )
  }
}

const stylesContainer = {
  ...globalStyles.flexBoxColumn,
}

const stylesTab = {
  ...globalStyles.flexBoxColumn,
  alignItems: 'center',
  justifyContent: 'flex-end',
}

const stylesTabBarButtonIcon = {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center',
}

const stylesLabel = {
  fontSize: 14,
  lineHeight: 20,
  marginTop: 11,
  marginBottom: 11,
}

const stylesSelectedUnderline = color => ({
  height: 3,
  alignSelf: 'stretch',
  backgroundColor: color,
})

const stylesUnselectedUnderline = {
  height: 2,
  marginTop: 1,
  backgroundColor: globalColors.black_10,
  alignSelf: 'stretch',
}

export {
  TabBarItem,
  TabBarButton,
}

export default TabBar
<commit_msg>Fix the alignment of icons in mobile tab bar<commit_after>// @flow
import React, {Component} from 'react'
import _ from 'lodash'
import type {Props, ItemProps, TabBarButtonProps} from './tab-bar'
import {Box, Icon, Text, NativeTouchableWithoutFeedback} from './index.native'
import {globalStyles, globalColors} from '../styles'

class TabBarItem extends Component<void, ItemProps, void> {
  render () {
    return this.props.children
  }
}

class SimpleTabBarButton extends Component<void, ItemProps, void> {
  render () {
    const selectedColor = this.props.selectedColor || globalColors.blue
    return (
      <Box style={{...stylesTab, ...this.props.style}}>
        <Text type='BodySemibold' style={{...stylesLabel, color: this.props.selected ? globalColors.black_75 : globalColors.black_60}}>
          {this.props.label.toUpperCase()}
        </Text>
        {(!this.props.underlined || this.props.selected) && <Box style={stylesSelectedUnderline(this.props.selected ? selectedColor : 'transparent')} />}
        {!this.props.selected && this.props.underlined && <Box style={stylesUnselectedUnderline} />}
      </Box>
    )
  }
}

class TabBarButton extends Component<void, TabBarButtonProps, void> {
  render () {
    const backgroundColor = this.props.selected ? globalColors.darkBlue4 : globalColors.midnightBlue
    const badgeNumber = this.props.badgeNumber || 0

    return (
      <Box style={{...globalStyles.flexBoxColumn, backgroundColor, ...stylesTabBarButtonIcon, ...this.props.style}}>
        {this.props.source.type === 'icon'
          ? <Icon type={this.props.source.icon} style={{fontSize: 48, width: 48, textAlign: 'center', color: this.props.selected ? globalColors.blue3 : globalColors.blue3_40, ...this.props.styleIcon}} />
          : this.props.source.avatar}
        {badgeNumber > 0 &&
          <Box style={{...styleBadgeOuter, borderColor: backgroundColor, backgroundColor}}>
            <Box style={styleBadge}>
              <Text style={{flex: 0}} type='BadgeNumber'>{badgeNumber}</Text>
            </Box>
          </Box>}
        {!!this.props.label && <Text type='BodySemibold' style={{textAlign: 'center', ...this.props.styleLabel}}>{this.props.label}</Text>}
      </Box>
    )
  }
}

const styleBadgeOuter = {
  borderColor: globalColors.midnightBlue,
  borderWidth: 2,
  borderRadius: 10,
  position: 'absolute',
  top: 10,
  left: 40,
}

const styleBadge = {
  ...globalStyles.flexBoxRow,
  backgroundColor: globalColors.orange,
  borderColor: globalColors.orange,
  borderWidth: 2,
  paddingLeft: 2,
  paddingRight: 2,
  borderRadius: 10,
  flex: 0,
}

class TabBar extends Component {
  props: Props;

  _labels (): Array<React$Element<*>> {
    // TODO: Not sure why I have to wrap the child in a box, but otherwise touches won't work
    return (this.props.children || []).map((item: {props: ItemProps}, i) => {
      const key = item.props.label || _.get(item, 'props.tabBarButton.props.label') || i
      return (
        <NativeTouchableWithoutFeedback key={key} onPress={item.props.onClick || (() => {})}>
          <Box style={item.props.styleContainer}>
            {item.props.tabBarButton || <SimpleTabBarButton {...item.props} />}
          </Box>
        </NativeTouchableWithoutFeedback>
      )
    })
  }

  _content (): any {
    return (this.props.children || []).find(i => i.props.selected)
  }

  render () {
    const tabBarButtons = (
      <Box style={{...globalStyles.flexBoxRow, ...this.props.styleTabBar}}>
        {this._labels()}
      </Box>
    )

    return (
      <Box style={{...stylesContainer, ...this.props.style}}>
        {!this.props.tabBarOnBottom && tabBarButtons}
        {this._content()}
        {this.props.tabBarOnBottom && tabBarButtons}
      </Box>
    )
  }
}

const stylesContainer = {
  ...globalStyles.flexBoxColumn,
}

const stylesTab = {
  ...globalStyles.flexBoxColumn,
  alignItems: 'center',
  justifyContent: 'flex-end',
}

const stylesTabBarButtonIcon = {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center',
}

const stylesLabel = {
  fontSize: 14,
  lineHeight: 20,
  marginTop: 11,
  marginBottom: 11,
}

const stylesSelectedUnderline = color => ({
  height: 3,
  alignSelf: 'stretch',
  backgroundColor: color,
})

const stylesUnselectedUnderline = {
  height: 2,
  marginTop: 1,
  backgroundColor: globalColors.black_10,
  alignSelf: 'stretch',
}

export {
  TabBarItem,
  TabBarButton,
}

export default TabBar
<|endoftext|>


<commit_before>// VERSION 1.2.1
Modules.UTILS = true;
Modules.BASEUTILS = true;

// innerText(node) - returns the equivalent of IE's .innerText property of node; essentially returns .textContent stripped of all the script tags
//	node - (xul element) to retrieve text content from
// This process is almost immediate (0-5ms) in normal smaller pages.
// https://bugzilla.mozilla.org/attachment.cgi?id=815787&action=diff, which is already a larger page, takes about 40-50ms.
// Isohunt results, which have a lot of frames, can be a little more than as above.
// Note: an alternative to this would be to crawl through all the childNodes of node and retrive text individually,
// but I found from my tests that this would be almost 50x slower, probably more if taking into account node visibility, which I didn't test for.
this.innerText = function(node) {
	try {
		if(!node || !node.ownerDocument || !(node instanceof node.ownerDocument.defaultView.HTMLElement)) {
			return '';
		}

		// Cloning directly on the same document often triggers new onStateChange events in the browser, which could create endless loops of processing.
		var clone = node.ownerDocument.implementation.createHTMLDocument('').importNode(node, true);
		if(clone.getElementsByTagName) {
			var heads = clone.getElementsByTagName('head');
			while(heads.length > 0) {
				heads[0].remove();
			}
			var scripts = clone.getElementsByTagName('script');
			while(scripts.length > 0) {
				scripts[0].remove();
			}
			var styles = clone.getElementsByTagName('style');
			while(styles.length > 0) {
				styles[0].remove();
			}
		}

		return clone.textContent;
	}
	catch(ex) {
		Cu.reportError(ex);
		return '';
	}
};
<commit_msg>comment<commit_after>// VERSION 1.2.1
Modules.UTILS = true;
Modules.BASEUTILS = true;

// innerText(node) - returns the equivalent of IE's .innerText property of node; essentially returns .textContent stripped of all the script tags
//	node - (xul element) to retrieve text content from
// This process is almost immediate (0-5ms) in normal smaller pages.
// https://bugzilla.mozilla.org/attachment.cgi?id=815787&action=diff, which is already a larger page, takes about 40-50ms.
// Isohunt results, which have a lot of frames, can be a little more than as above.
// Note: an alternative to this would be to crawl through all the childNodes of node and retrive text individually,
// but I found from my tests that this would be almost 50x slower, probably more if taking into account node visibility, which I didn't test for.
// Firefox 45 implements innerText at least, making this obsolete.
this.innerText = function(node) {
	try {
		if(!node || !node.ownerDocument || !(node instanceof node.ownerDocument.defaultView.HTMLElement)) {
			return '';
		}

		// Cloning directly on the same document often triggers new onStateChange events in the browser, which could create endless loops of processing.
		var clone = node.ownerDocument.implementation.createHTMLDocument('').importNode(node, true);
		if(clone.getElementsByTagName) {
			var heads = clone.getElementsByTagName('head');
			while(heads.length > 0) {
				heads[0].remove();
			}
			var scripts = clone.getElementsByTagName('script');
			while(scripts.length > 0) {
				scripts[0].remove();
			}
			var styles = clone.getElementsByTagName('style');
			while(styles.length > 0) {
				styles[0].remove();
			}
		}

		return clone.textContent;
	}
	catch(ex) {
		Cu.reportError(ex);
		return '';
	}
};
<|endoftext|>


<commit_before>module.exports = function (shipit) {
  require('shipit-deploy')(shipit);
  require('shipit-shared')(shipit);

  shipit.initConfig({
    default: {
      workspace: '/tmp/shipit_workspace',
      deployTo: '/home/admin/apps/prerender',
      repositoryUrl: 'git@github.com:fiverr/prerender.git',
      ignores: ['.git', 'node_modules'],
      branch: process.env.BRANCH || 'master',
      keepReleases: 10,
      shallowClone: true,
      shared: {
        dirs: [ 'node_modules', 'log', 'run' ],
      }
    },
    fiverr01: {
      servers: 'admin@fiverr01'
    },
    fiverr02: {
      servers: 'admin@fiverr02'
    }
  });

  function underRelease(cmd) {
  	return 'cd ' + shipit.config.deployTo + "/current " + ' && ' + cmd;
  }

  shipit.blTask('startAppStaging', function () {
       	shipit.remote(underRelease("./control.sh stop staging; ./control.sh start staging"));
  });

  shipit.blTask('startAppProduction', function () {
        shipit.remote(underRelease("./control.sh stop production; ./control.sh start production"));
  });

  shipit.blTask('deployStaging', function () {
       	shipit.start('startAppStaging');
  });

  shipit.blTask('deployProduction', function () {
       	shipit.start('startAppProduction');
  });

  shipit.on("cleaned", function() {
        if (shipit.environment.indexOf("staging") > -1) {
                shipit.start('deployStaging');
        } else {
		shipit.start('deployProduction');
	}
  });
};
<commit_msg>[CONFIG] change servers deployment<commit_after>module.exports = function (shipit) {
  require('shipit-deploy')(shipit);
  require('shipit-shared')(shipit);

  shipit.initConfig({
    default: {
      workspace: '/tmp/shipit_workspace',
      deployTo: '/home/admin/apps/prerender',
      repositoryUrl: 'git@github.com:fiverr/prerender.git',
      ignores: ['.git', 'node_modules'],
      branch: process.env.BRANCH || 'master',
      keepReleases: 10,
      shallowClone: true,
      shared: {
        dirs: [ 'node_modules', 'log', 'run' ],
      }
    },
    fiverr03: {
      servers: 'admin@fiverr03'
    },
    fiverr04: {
      servers: 'admin@fiverr04'
    }
  });

  function underRelease(cmd) {
  	return 'cd ' + shipit.config.deployTo + "/current " + ' && ' + cmd;
  }

  shipit.blTask('startAppStaging', function () {
       	shipit.remote(underRelease("./control.sh stop staging; ./control.sh start staging"));
  });

  shipit.blTask('startAppProduction', function () {
        shipit.remote(underRelease("./control.sh stop production; ./control.sh start production"));
  });

  shipit.blTask('deployStaging', function () {
       	shipit.start('startAppStaging');
  });

  shipit.blTask('deployProduction', function () {
       	shipit.start('startAppProduction');
  });

  shipit.on("cleaned", function() {
        if (shipit.environment.indexOf("staging") > -1) {
                shipit.start('deployStaging');
        } else {
		shipit.start('deployProduction');
	}
  });
};
<|endoftext|>


<commit_before>var Util = {};

Util.createSimpleDataTable = function (input, properties) {
  var rows, i, len, tableProps, rowProps;

  rows = [];
  tableProps = (properties && properties.table) || {};
  rowProps = (properties && properties.row) || {};

  for (i = 0, len = input.length; i < len; i += 1) {
    rows.push(Util.merge(rowProps, { 'title': input[i] }));
  }

  return Ti.UI.createTableView(Util.merge(tableProps, {'data': rows}));
};

Util.buildTabGroup = function (data) {
  var index, length, datum, tabs, window;

  tabs = [];
  for (index = 0, length = data.length;
       index < length;
       index += 1) {
    datum = data[index];

    window = Ti.UI.createWindow({
      'title': datum.title || 'No title',
      'url': datum.url || '',
      'backgroundColor': '#fff'
    });

    tabs.push(Ti.UI.createTab({
      'title': datum.title,
      'icon': datum.icon,
      'window': window
    }));
  }

  return Ti.UI.createTabGroup({
    'tabs': tabs
  });
};

Util.merge = function () {
  var i, len, obj, k, result;
  result = {};
  for (i = 0, len = arguments.length; i < len; i += 1) {
    obj = arguments[i];
    if (obj) {
      for (k in obj) {
        if (obj.hasOwnProperty(k)) {
          result[k] = obj[k];
        }
      }
    }
  }
  return result;
};
<commit_msg>added getUserClubs and setUserClubs<commit_after>var Util = {};

Util.getUserClubs = function(){
	if (Ti.App.Properties.hasProperty('clubs')){
		return Ti.App.Properties.getList('clubs');
	}

};

Util.subscribeToClub = function(clubName){
	var currentClubs;

	if (Ti.App.Properties.hasProperty('clubs')){
		currentClubs = Ti.App.Properties.getList('clubs');
	}

	currentClubs.push(clubName);

	Ti.App.Properties.setList('clubs', currentClubs);
};
Util.createSimpleDataTable = function (input, properties) {
  var rows, i, len, tableProps, rowProps;

  rows = [];
  tableProps = (properties && properties.table) || {};
  rowProps = (properties && properties.row) || {};

  for (i = 0, len = input.length; i < len; i += 1) {
    rows.push(Util.merge(rowProps, { 'title': input[i] }));
  }

  return Ti.UI.createTableView(Util.merge(tableProps, {'data': rows}));
};

Util.buildTabGroup = function (data) {
  var index, length, datum, tabs, window;

  tabs = [];
  for (index = 0, length = data.length;
       index < length;
       index += 1) {
    datum = data[index];

    window = Ti.UI.createWindow({
      'title': datum.title || 'No title',
      'url': datum.url || '',
      'backgroundColor': '#fff'
    });

    tabs.push(Ti.UI.createTab({
      'title': datum.title,
      'icon': datum.icon,
      'window': window
    }));
  }

  return Ti.UI.createTabGroup({
    'tabs': tabs
  });
};

Util.merge = function () {
  var i, len, obj, k, result;
  result = {};
  for (i = 0, len = arguments.length; i < len; i += 1) {
    obj = arguments[i];
    if (obj) {
      for (k in obj) {
        if (obj.hasOwnProperty(k)) {
          result[k] = obj[k];
        }
      }
    }
  }
  return result;
};
<|endoftext|>


<commit_before>

$('#reportrange').daterangepicker(
    {
    	buttonClasses:"btn-inverse",
    	startDate:$('#startDate').val(),
    	endDate:$('#endDate').val(),
    	minDate:Date.today(),
        ranges: {
            'Today': ['today', 'today'],
            'Tomorrow': ['tomorrow', 'tomorrow'],
            'Next weekend': [Date.saturday(),Date.saturday().add({ days: +1 })],
            'Next 7 days': ['today',Date.today().add({ days: +6 })],
            'Next week': [Date.monday().add({ days: +7 }),Date.monday().add({ days: +13 })],
            'Next month': [Date.today().moveToFirstDayOfMonth().add({ months: +1 }), Date.today().moveToLastDayOfMonth().add({ months: +1 })],
        },
        locale: {
        	customRangeLabel:"Custom dates"
        }
    },
    function(start, end) {
    	$('#startDate').val(start.toString('yyyy-MM-dd hh:mm:ss'));
    	$('#endDate').val(end.toString('yyyy-MM-dd hh:mm:ss'));
        $('#reportrange span').html(start.toString('MMMM d, yyyy') + ' - ' + end.toString('MMMM d, yyyy'));
        $('#rangeDateForm').submit();
    }
);

$('.reportrange').daterangepicker(
    {
        buttonClasses:"btn-inverse",
        startDate:$(this).closest('.widget').find('input.startDate').val(),
        endDate:$(this).closest('.widget').find('input.endDate').val(),
        minDate:Date.today(),
        format : 'MM/dd/yyyy hh:mm:ss',
        locale: {
            customRangeLabel:"Custom dates"
        }
    },
    function(start, end) {
        startDateField=this.element.closest('.widget').find('input.startDate');
        endDateField=this.element.closest('.widget').find('input.endDate');

        startDateField.val(start.toString('dd/MM/yyyy hh:mm:ss'));
        endDateField.val(end.toString('dd/MM/yyyy hh:mm:ss'));
        //this.element.css('color','1px solid blue');
        //this.element.find(" ~ .reportrange").css('color','1px solid red');
        this.element.find('span.display').html("From "+start.toString('dd/MM/yyyy hh:mm:ss') + " to " + end.toString('dd/MM/yyyy hh:mm:ss'));
        //$('#rangeDateForm').submit();
    }
);

$('.combobox ul.dropdown-menu li a').click(function() {
    $(this).closest('.combobox').find('input').val($(this).text());
});

$(document).ready(function() {

    pagination();
    initClient();
    initProduct();
    initOffre();
    initSlice();
    initSearch();
    $('select.status').change(function() {
        $(this).closest('form').submit();
    });

    $('#conditionChoices td').click(function() {
        CKEDITOR.instances['caravane_bundle_organicbundle_invoicetype_conditions'].setData($(this).html())
        //$(this).closest('.row-fluid').find("#cke_1_contents").html($(this).html());
    });

    $('table.table-sortable tbody').sortable({
        update:function(ui,item) {

            lis=new Array();
            $(this).find('tr').each(function() {
                lis.push($(this).data('entity'));
            });

            $.post($(this).data('update'),{'list':lis},function(data) {
                //alert(data);
            });

        }
    });

});

function pagination() {
    if($('#CaravaneUiPaginationOb').length>0) {
        ob=$('#CaravaneUiPaginationOb').val();
        tA=ob.split(' ');
        currentOb=tA[0];
        currentSens=tA[1];
        currentSens=='asc'?icon='up':icon='down';
        currentField=$("thead th a[data-orderby='"+currentOb+"']");

        currentField.html(currentField.text()+" ");
        /*currentField.click(function() {
            currentSens=='asc'?currentSens='desc':currentSens='asc';
            document.location=Routing.generate($('#CaravaneUiPaginationRoute').val(),{'type':$('#CaravaneUiPaginationType').val(),'ob':currentOb+" "+currentSens,'page':$('#CaravaneUiPaginationPage').val()});
        });*/
        $("thead th a").click(function() {
            if($(this).data('orderby')==currentOb) {
                currentSens=='asc'?currentSens='desc':currentSens='asc';
            }
            document.location=Routing.generate($('#CaravaneUiPaginationRoute').val(),{'type':$('#CaravaneUiPaginationType').val(),'ob':$(this).data('orderby')+" "+currentSens,'page':$('#CaravaneUiPaginationPage').val()});
        });
    }

    $('table.table-list tbody tr td a i.icon-trash').click(function(e) {
        e.stopPropagation();
        reference=$(this).closest('a').data('rel');
        if(confirm("Are you sure you want to delete "+reference+" ?")) {
            row=$(this).closest('tr');

            deleteUrl=$(this).closest('a').attr('href');
            $.post(deleteUrl,function(data) {
                if(data=="deleted") {
                    row.remove();
                }
            }) ;
            return false;
        }

        return false;
    });

}

function initClient() {
	if($('#caravane_bundle_organicbundle_clienttype_clienttype').val()=='part') {
		$('#cieonly').hide();
	}
	$('div.btn-group button').click(function(){
		//target=$(this).attr('data-target');
		if($(this).attr('data-value')=='part') {
			$('#cieonly').hide();
		}else {
			$('#cieonly').show();
		}
	})
}

function initProduct() {
     $('a.delete_row').click(function() {
        var link=$(this);
        $.post(Routing.generate($(this).attr('data-type')+'_remove_product',{'id':$(this).attr('data-rel'),'productid':$(this).attr('data-target')}),function(data) {
            link.closest('tr').remove();
            window.location.reload();
        });
    });

    $('.add_product_link').click(function(e) {
         e.preventDefault();
         target=$(this).closest('table').find('tbody');
       /* if($(this).data('isoption')) {
            target=$('tbody#options');
        }
        else (
            target=$('tbody#products');
        )*/
        var prototype =$('table tbody#products').data('prototype');
        var index=target.find('tr').length;
        var newForm = prototype.replace(/__name__/g, index);
         target.data('index', index + 1);
         var $newFormLi = $('

').append(newForm);
         target.append($newFormLi);
         target.find('input:hidden').val($(this).data('isoption'));

         $('a.delete_new_row').click(function() {
            $(this).closest('tr').remove();
        });
    });

    $('a.delete_document').click(function() {
        var link=$(this);
        $.post(Routing.generate($(this).attr('data-type')+'_remove_document',{'id':$(this).attr('data-rel'),'documentid':$(this).attr('data-target')}),function(data) {
            link.closest('tr').remove();
           // alert(data);
        });
    });
}

var collectionHolder = $('table tbody.products');

function initSlice() {
    $('.slice').change(function() {
        $(this).closest('tr').find('.price').val('');
    });
    $('.price').change(function() {
        $(this).closest('tr').find('.slice').val('');
    });
    $('.balance').click(function() {
        $(this).closest('tr').find('.slice').val('');
        $(this).closest('tr').find('.price').val($(this).attr('rel'));
        $(this).closest('form').submit();
    });
}

function fillClient2invoice(clientid) {
    fields=new Array()
    $.post(Routing.generate('client_get_data',{'id':clientid}),function(data) {
        data=$.parseJSON(data);
        $.each(data, function(i, item) {

            $('#caravane_bundle_organicbundle_invoicetype_'+i).val(data[i]);
        });
    })
}

function fillClient(clientid,targetField) {
    if($('#clientid').length==0) {
        //$('#mainForm').submit();
        document.location=Routing.generate('client_edit',{'id':clientid});

    }
    entity=$('#mainForm').data('entity');

    fields=new Array();

    $(targetField).val(clientid);

    $.post(Routing.generate('client_get_data',{'id':clientid}),function(data) {
        data=$.parseJSON(data);

        $.each(data, function(i, item) {
            $('#caravane_bundle_organicbundle_'+entity+'type_clientid_'+i).val(data[i]);
            //$('#caravane_bundle_organicbundle_'+entity+'type_clientid_'+i).val(data[i]);
            //$('#caravane_bundle_organicbundle_clienttype_'+i).val(data[i]);
            if(i=='clienttype') {
                if(data[i]=='cie') {
                    $('#cieonly').show();
                }
                else {
                    $('#cieonly').hide();
                }
                $("#caravane_bundle_organicbundle_"+entity+"type_clienttype_widget button").removeClass('active');
                $("#caravane_bundle_organicbundle_"+entity+"type_clienttype_widget button[data-value='"+data[i]+"']").addClass('active');

                //$("#caravane_bundle_organicbundle_"+entity+"type_clientid_name
            }

        });

    })
}

function initOffre() {
    $('.add_slice_link').click(function(e) {
         e.preventDefault();
         target=$(this).closest('table').find('tbody');
       /* if($(this).data('isoption')) {
            target=$('tbody#options');
        }
        else (
            target=$('tbody#products');
        )*/
        var prototype =$('table tbody.slices').data('prototype');
        var index=target.find(':input').length;
        var newForm = prototype.replace(/__name__/g, index);
         target.data('index', index + 1);
         var $newFormLi = $('

').append(newForm);
         target.append($newFormLi);
         target.find('input:hidden').val($(this).data('isoption'));

         $('a.delete_new_row').click(function() {
            $(this).closest('tr').remove();
        });
    });

    $('.add_comment').click(function(e) {
         e.preventDefault();
         target=$(this).closest('div');
       /* if($(this).data('isoption')) {
            target=$('tbody#options');
        }
        else (
            target=$('tbody#products');
        )*/
        var prototype =$(this).data('prototype');
        var index=target.find(':input').length;
        var newForm = prototype.replace(/__name__/g, index);
         target.data('index', index + 1);
         var $newFormLi = $('

').append(newForm);
         target.append($newFormLi);

    });

    $('.openStockModal').click(function() {
        target=$(this).closest('table').find('.products');
        entity=$('#mainForm').data('entity');
        option=$(this).closest('table').data('option');
        $('#stockModal').modal('show');
        $('table.stock tbody tr, table.stock tbody a').click(function(e) {
            e.stopPropagation();
            tentid=$(this).data('productid');
            entityId=$(this).closest('.modal').data('target');

             $.post(Routing.generate(entity+'_add_tent',{'id':entityId,'tentid':tentid}),{'option':option},function(data) {
               // alert(data);
               window.location.reload();
               // $('form').submit();
            })
        });

    });

    $('.openTransportModal').click(function() {
        target=$(this).closest('table').find('.products');
        entity=$('#mainForm').data('entity');
        option=$(this).closest('table').data('option');
        $('#transportModal').modal('show');
        $('table.transport tbody tr, table.transport tbody a').click(function(e) {
            e.stopPropagation();
            transportid=$(this).data('productid');
            entityId=$(this).closest('.modal').data('target');
            //alert(Routing.generate(entity+'_add_transport',{'id':entityId,'transportid':transportid}));
             $.post(Routing.generate(entity+'_add_transport',{'id':entityId,'transportid':transportid}),{'option':option},function(data) {
               // alert(data);
               window.location.reload();
              //  $('form').submit();
            })
        });

    });

    $('#mainForm').submit(function() {
        entity=$('#mainForm').data('entity');
        $('tbody.products tr').each(function() {
            c=$(this).data('productid');
           //  console.log('rr');
            additionalDatas=$(this).find('.additionalData');
            datas=new Object();
            additionalDatas.each(function() {
                //console.log('rr'+$(this).attr("data-attribute")+"//"+$(this).val()  );
                //datas.push({$(this).attr("data-attribute"): $(this).val()});
                if($(this).attr('type')=='checkbox') {
                    //console.log('check');
                    if($(this).is(':checked')) {
                         //console.log('checked');
                        datas[$(this).attr("data-attribute")]='1';
                    }
                    else {
                        datas[$(this).attr("data-attribute")]='0';
                    }
                }
                else {
                    datas[$(this).attr("data-attribute")]=$(this).val();
                }

            });
            //console.log('c:'+c);
            //console.log(JSON.stringify(datas));
            $('#caravane_bundle_organicbundle_'+entity+'type_products_'+c+'_datas').val(JSON.stringify(datas));
        });

        return true;
    });

    $('#products .pagination a').click(function(e) {
        e.preventDefault();
        $(this).closest('.tab-pane').find('.tableContainer').load($(this).attr('href')+" .content",function(data) {
            initOffre();
        })
    });

}

function initSearch() {

    $('#searchField').keyup(function() {
        query=$(this).val();
        url=Routing.generate('search',{'query':query});
        if(query.length<=2) {
            resetSearch();
        }
        else {
            if($('#searchSuggestion').size()<1) {
                $(this).parent(). append('

');
             }
            $.get(url,function(data) {
                $('#searchSuggestion').html(data);
            })
        }
    });
}

function resetSearch() {
    $('#searchSuggestion').remove();
}
<commit_msg>reorder + reload on correct tab<commit_after>

$('#reportrange').daterangepicker(
    {
    	buttonClasses:"btn-inverse",
    	startDate:$('#startDate').val(),
    	endDate:$('#endDate').val(),
    	minDate:Date.today(),
        ranges: {
            'Today': ['today', 'today'],
            'Tomorrow': ['tomorrow', 'tomorrow'],
            'Next weekend': [Date.saturday(),Date.saturday().add({ days: +1 })],
            'Next 7 days': ['today',Date.today().add({ days: +6 })],
            'Next week': [Date.monday().add({ days: +7 }),Date.monday().add({ days: +13 })],
            'Next month': [Date.today().moveToFirstDayOfMonth().add({ months: +1 }), Date.today().moveToLastDayOfMonth().add({ months: +1 })],
        },
        locale: {
        	customRangeLabel:"Custom dates"
        }
    },
    function(start, end) {
    	$('#startDate').val(start.toString('yyyy-MM-dd hh:mm:ss'));
    	$('#endDate').val(end.toString('yyyy-MM-dd hh:mm:ss'));
        $('#reportrange span').html(start.toString('MMMM d, yyyy') + ' - ' + end.toString('MMMM d, yyyy'));
        $('#rangeDateForm').submit();
    }
);

$('.reportrange').daterangepicker(
    {
        buttonClasses:"btn-inverse",
        startDate:$(this).closest('.widget').find('input.startDate').val(),
        endDate:$(this).closest('.widget').find('input.endDate').val(),
        minDate:Date.today(),
        format : 'MM/dd/yyyy hh:mm:ss',
        locale: {
            customRangeLabel:"Custom dates"
        }
    },
    function(start, end) {
        startDateField=this.element.closest('.widget').find('input.startDate');
        endDateField=this.element.closest('.widget').find('input.endDate');

        startDateField.val(start.toString('dd/MM/yyyy hh:mm:ss'));
        endDateField.val(end.toString('dd/MM/yyyy hh:mm:ss'));
        //this.element.css('color','1px solid blue');
        //this.element.find(" ~ .reportrange").css('color','1px solid red');
        this.element.find('span.display').html("From "+start.toString('dd/MM/yyyy hh:mm:ss') + " to " + end.toString('dd/MM/yyyy hh:mm:ss'));
        //$('#rangeDateForm').submit();
    }
);

$('.combobox ul.dropdown-menu li a').click(function() {
    $(this).closest('.combobox').find('input').val($(this).text());
});

$(document).ready(function() {

    pagination();
    initClient();
    initProduct();
    initOffre();
    initSlice();
    initSearch();

    var url = document.location.toString();
    if (url.match('#')) {
        $('.nav-tabs a[href=#'+url.split('#')[1]+']').tab('show') ;
    }

    // Change hash for page-reload
    $('.nav-tabs a').on('shown', function (e) {
        window.location.hash = e.target.hash;
    })

    $('select.status').change(function() {
        $(this).closest('form').submit();
    });

    $('#conditionChoices td').click(function() {
        CKEDITOR.instances['caravane_bundle_organicbundle_invoicetype_conditions'].setData($(this).html())
        //$(this).closest('.row-fluid').find("#cke_1_contents").html($(this).html());
    });

    $('table.table-sortable tbody').sortable({
        update:function(ui,item) {

            lis=new Array();
            $(this).find('tr').each(function() {
                lis.push($(this).data('entity'));
            });

            $.post($(this).data('update'),{'list':lis},function(data) {
                if(data=='ok') {
                     window.location.reload();
                }
                //alert(data);
            });

        }
    });

});

function pagination() {

    if($('#CaravaneUiPaginationOb').length>0) {
        ob=$('#CaravaneUiPaginationOb').val();
        tA=ob.split(' ');
        currentOb=tA[0];
        currentSens=tA[1];
        currentSens=='asc'?icon='up':icon='down';
        currentField=$("thead th a[data-orderby='"+currentOb+"']");

        currentField.html(currentField.text()+" ");
        /*currentField.click(function() {
            currentSens=='asc'?currentSens='desc':currentSens='asc';
            document.location=Routing.generate($('#CaravaneUiPaginationRoute').val(),{'type':$('#CaravaneUiPaginationType').val(),'ob':currentOb+" "+currentSens,'page':$('#CaravaneUiPaginationPage').val()});
        });*/
        $("thead th a").click(function() {
            if($(this).data('orderby')==currentOb) {
                currentSens=='asc'?currentSens='desc':currentSens='asc';
            }
            document.location=Routing.generate($('#CaravaneUiPaginationRoute').val(),{'type':$('#CaravaneUiPaginationType').val(),'ob':$(this).data('orderby')+" "+currentSens,'page':$('#CaravaneUiPaginationPage').val()});
        });
    }

    $('table.table-list tbody tr td a i.icon-trash').click(function(e) {
        e.stopPropagation();
        reference=$(this).closest('a').data('rel');
        if(confirm("Are you sure you want to delete "+reference+" ?")) {
            row=$(this).closest('tr');

            deleteUrl=$(this).closest('a').attr('href');
            $.post(deleteUrl,function(data) {
                if(data=="deleted") {
                    row.remove();
                }
            }) ;
            return false;
        }

        return false;
    });

}

function initClient() {
	if($('#caravane_bundle_organicbundle_clienttype_clienttype').val()=='part') {
		$('#cieonly').hide();
	}
	$('div.btn-group button').click(function(){
		//target=$(this).attr('data-target');
		if($(this).attr('data-value')=='part') {
			$('#cieonly').hide();
		}else {
			$('#cieonly').show();
		}
	})
}

function initProduct() {
     $('a.delete_row').click(function() {
        var link=$(this);
        $.post(Routing.generate($(this).attr('data-type')+'_remove_product',{'id':$(this).attr('data-rel'),'productid':$(this).attr('data-target')}),function(data) {
            link.closest('tr').remove();
            window.location.reload();
        });
    });

    $('.add_product_link').click(function(e) {
         e.preventDefault();
         target=$(this).closest('table').find('tbody');
       /* if($(this).data('isoption')) {
            target=$('tbody#options');
        }
        else (
            target=$('tbody#products');
        )*/
        var prototype =$('table tbody#products').data('prototype');
        var index=target.find('tr').length;
        var newForm = prototype.replace(/__name__/g, index);
         target.data('index', index + 1);
         var $newFormLi = $('

').append(newForm);
         target.append($newFormLi);
         target.find('input:hidden').val($(this).data('isoption'));

         $('a.delete_new_row').click(function() {
            $(this).closest('tr').remove();
        });
    });

    $('a.delete_document').click(function() {
        var link=$(this);
        $.post(Routing.generate($(this).attr('data-type')+'_remove_document',{'id':$(this).attr('data-rel'),'documentid':$(this).attr('data-target')}),function(data) {
            link.closest('tr').remove();
           // alert(data);
        });
    });
}

var collectionHolder = $('table tbody.products');

function initSlice() {
    $('.slice').change(function() {
        $(this).closest('tr').find('.price').val('');
    });
    $('.price').change(function() {
        $(this).closest('tr').find('.slice').val('');
    });
    $('.balance').click(function() {
        $(this).closest('tr').find('.slice').val('');
        $(this).closest('tr').find('.price').val($(this).attr('rel'));
        $(this).closest('form').submit();
    });
}

function fillClient2invoice(clientid) {
    fields=new Array()
    $.post(Routing.generate('client_get_data',{'id':clientid}),function(data) {
        data=$.parseJSON(data);
        $.each(data, function(i, item) {

            $('#caravane_bundle_organicbundle_invoicetype_'+i).val(data[i]);
        });
    })
}

function fillClient(clientid,targetField) {
    if($('#clientid').length==0) {
        //$('#mainForm').submit();
        document.location=Routing.generate('client_edit',{'id':clientid});

    }
    entity=$('#mainForm').data('entity');

    fields=new Array();

    $(targetField).val(clientid);

    $.post(Routing.generate('client_get_data',{'id':clientid}),function(data) {
        data=$.parseJSON(data);

        $.each(data, function(i, item) {
            $('#caravane_bundle_organicbundle_'+entity+'type_clientid_'+i).val(data[i]);
            //$('#caravane_bundle_organicbundle_'+entity+'type_clientid_'+i).val(data[i]);
            //$('#caravane_bundle_organicbundle_clienttype_'+i).val(data[i]);
            if(i=='clienttype') {
                if(data[i]=='cie') {
                    $('#cieonly').show();
                }
                else {
                    $('#cieonly').hide();
                }
                $("#caravane_bundle_organicbundle_"+entity+"type_clienttype_widget button").removeClass('active');
                $("#caravane_bundle_organicbundle_"+entity+"type_clienttype_widget button[data-value='"+data[i]+"']").addClass('active');

                //$("#caravane_bundle_organicbundle_"+entity+"type_clientid_name
            }

        });

    })
}

function initOffre() {
    $('.add_slice_link').click(function(e) {
         e.preventDefault();
         target=$(this).closest('table').find('tbody');
       /* if($(this).data('isoption')) {
            target=$('tbody#options');
        }
        else (
            target=$('tbody#products');
        )*/
        var prototype =$('table tbody.slices').data('prototype');
        var index=target.find(':input').length;
        var newForm = prototype.replace(/__name__/g, index);
         target.data('index', index + 1);
         var $newFormLi = $('

').append(newForm);
         target.append($newFormLi);
         target.find('input:hidden').val($(this).data('isoption'));

         $('a.delete_new_row').click(function() {
            $(this).closest('tr').remove();
        });
    });

    $('.add_comment').click(function(e) {
         e.preventDefault();
         target=$(this).closest('div');
       /* if($(this).data('isoption')) {
            target=$('tbody#options');
        }
        else (
            target=$('tbody#products');
        )*/
        var prototype =$(this).data('prototype');
        var index=target.find(':input').length;
        var newForm = prototype.replace(/__name__/g, index);
         target.data('index', index + 1);
         var $newFormLi = $('

').append(newForm);
         target.append($newFormLi);

    });

    $('.openStockModal').click(function() {
        target=$(this).closest('table').find('.products');
        entity=$('#mainForm').data('entity');
        option=$(this).closest('table').data('option');
        $('#stockModal').modal('show');
        $('table.stock tbody tr, table.stock tbody a').click(function(e) {
            e.stopPropagation();
            tentid=$(this).data('productid');
            entityId=$(this).closest('.modal').data('target');

             $.post(Routing.generate(entity+'_add_tent',{'id':entityId,'tentid':tentid}),{'option':option},function(data) {
               // alert(data);
               window.location.reload();
               // $('form').submit();
            })
        });

    });

    $('.openTransportModal').click(function() {
        target=$(this).closest('table').find('.products');
        entity=$('#mainForm').data('entity');
        option=$(this).closest('table').data('option');
        $('#transportModal').modal('show');
        $('table.transport tbody tr, table.transport tbody a').click(function(e) {
            e.stopPropagation();
            transportid=$(this).data('productid');
            entityId=$(this).closest('.modal').data('target');
            //alert(Routing.generate(entity+'_add_transport',{'id':entityId,'transportid':transportid}));
             $.post(Routing.generate(entity+'_add_transport',{'id':entityId,'transportid':transportid}),{'option':option},function(data) {
               // alert(data);
               window.location.reload();
              //  $('form').submit();
            })
        });

    });

    $('#mainForm').submit(function() {
        entity=$('#mainForm').data('entity');
        $('tbody.products tr').each(function() {
            c=$(this).data('productid');
           //  console.log('rr');
            additionalDatas=$(this).find('.additionalData');
            datas=new Object();
            additionalDatas.each(function() {
                //console.log('rr'+$(this).attr("data-attribute")+"//"+$(this).val()  );
                //datas.push({$(this).attr("data-attribute"): $(this).val()});
                if($(this).attr('type')=='checkbox') {
                    //console.log('check');
                    if($(this).is(':checked')) {
                         //console.log('checked');
                        datas[$(this).attr("data-attribute")]='1';
                    }
                    else {
                        datas[$(this).attr("data-attribute")]='0';
                    }
                }
                else {
                    datas[$(this).attr("data-attribute")]=$(this).val();
                }

            });
            //console.log('c:'+c);
            //console.log(JSON.stringify(datas));
            $('#caravane_bundle_organicbundle_'+entity+'type_products_'+c+'_datas').val(JSON.stringify(datas));
        });

        return true;
    });

    $('#products .pagination a').click(function(e) {
        e.preventDefault();
        $(this).closest('.tab-pane').find('.tableContainer').load($(this).attr('href')+" .content",function(data) {
            initOffre();
        })
    });

}

function initSearch() {

    $('#searchField').keyup(function() {
        query=$(this).val();
        url=Routing.generate('search',{'query':query});
        if(query.length<=2) {
            resetSearch();
        }
        else {
            if($('#searchSuggestion').size()<1) {
                $(this).parent(). append('

');
             }
            $.get(url,function(data) {
                $('#searchSuggestion').html(data);
            })
        }
    });
}

function resetSearch() {
    $('#searchSuggestion').remove();
}
<|endoftext|>


<commit_before>window.onload = function () {
    function scatter(cfg) {
        var spec,
            seasons,
            url,
            x,
            y;

        spec = {
            "name": "scatterplot",
            "width": 1200,
            "height": 400,
            "data": [
                {
                    "name": "air/star dates",
                    "url": null
                }
            ],
            "scales": [
                {
                    "name": "y",
                    "type": "linear",
                    "range": "height",
                    "domain": {
                        "data": "air/star dates",
                        "field": "data.stardate"
                    },
                    "zero": false
                },
                {
                    "name": "x",
                    "type": "time",
                    "range": "width",
                    "round": true,
                    "nice": "month",
                    "domain": {
                        "data": "air/star dates",
                        "field": "data.airdate"
                    }
                }
            ],
            "axes": [
                {"type": "x", "scale": "x"},
                {"type": "y", "scale": "y"}
            ],
            "marks": [
                {
                    "type": "symbol",
                    "from": {"data": "air/star dates"},
                    "properties": {
                        "enter": {
                            "x": {"scale": "x", "field": "data.airdate"},
                            "y": {"scale": "y", "field": "data.stardate"},
                            "size": {"value": 50},
                            "stroke": {"value": "black"},
                            "fill": {"value": "steelblue"}
                        },
                        "hover": {
                            "size": {"value": 100},
                            "fill": {"value": "firebrick"}
                        }
                    }
                }
            ]
        };

        cfg = cfg || {};

        url = "episodes/scatter?x=" + cfg.x + "&y=" + cfg.y;
        if (cfg.seasons) {
            url += "&seasons=" + cfg.seasons;
        }

        spec.data[0].url = url;
        spec.scales[0].domain.field = "data." + cfg.y;
        spec.scales[1].domain.field = "data." + cfg.x;
        spec.marks[0].properties.enter.x.field = "data." + cfg.x;
        spec.marks[0].properties.enter.y.field = "data." + cfg.y;

        return spec;
    }

    function parse(spec) {
        vg.parse.spec(spec, function(chart) {
            var view = chart({el: "#vis"})
                .on("mouseover", function (evt, item) {
                    d3.select("#info")
                        .html(item.datum.data.title);
                })
                .on("mouseout", function (evt, item) {
                    view.update({
                        props: "enter"
                    });
                })
                .update();
        });
    }

    parse(scatter({
        x: "airdate",
        y: "stardate",
        seasons: tangelo.queryArguments().seasons
    }));
};
<commit_msg>Generalized scale types; added named chart types<commit_after>window.onload = function () {
    function scatter(cfg) {
        var spec,
            seasons,
            url,
            x,
            y;

        spec = {
            "name": "scatterplot",
            "width": 1200,
            "height": 400,
            "data": [
                {
                    "name": "air/star dates",
                    "url": null
                }
            ],
            "scales": [
                {
                    "name": "y",
                    "type": null,
                    "range": "height",
                    "domain": {
                        "data": "air/star dates",
                        "field": "data.stardate"
                    },
                    "zero": false
                },
                {
                    "name": "x",
                    "type": null,
                    "range": "width",
                    "round": true,
                    "nice": "month",
                    "domain": {
                        "data": "air/star dates",
                        "field": "data.airdate"
                    }
                }
            ],
            "axes": [
                {"type": "x", "scale": "x"},
                {"type": "y", "scale": "y"}
            ],
            "marks": [
                {
                    "type": "symbol",
                    "from": {"data": "air/star dates"},
                    "properties": {
                        "enter": {
                            "x": {"scale": "x", "field": "data.airdate"},
                            "y": {"scale": "y", "field": "data.stardate"},
                            "size": {"value": 50},
                            "stroke": {"value": "black"},
                            "fill": {"value": "steelblue"}
                        },
                        "hover": {
                            "size": {"value": 100},
                            "fill": {"value": "firebrick"}
                        }
                    }
                }
            ]
        };

        cfg = cfg || {};

        url = "episodes/scatter?x=" + cfg.x + "&y=" + cfg.y;
        if (cfg.seasons) {
            url += "&seasons=" + cfg.seasons;
        }

        spec.data[0].url = url;
        spec.scales[0].domain.field = "data." + cfg.y;
        spec.scales[0].type = cfg.yscaleType || "linear";
        spec.scales[1].domain.field = "data." + cfg.x;
        spec.scales[1].type = cfg.xscaleType || "linear";
        spec.marks[0].properties.enter.x.field = "data." + cfg.x;
        spec.marks[0].properties.enter.y.field = "data." + cfg.y;

        return spec;
    }

    function parse(spec) {
        vg.parse.spec(spec, function(chart) {
            var view = chart({el: "#vis"})
                .on("mouseover", function (evt, item) {
                    d3.select("#info")
                        .html(item.datum.data.title);
                })
                .on("mouseout", function (evt, item) {
                    view.update({
                        props: "enter"
                    });
                })
                .update();
        });
    }

    chartType = tangelo.queryArguments().chart || "airdate";
    seasons = tangelo.queryArguments().seasons;

    if (chartType === "airdate") {
        config = {
            x: "airdate",
            xscaleType: "time",
            y: "stardate",
            seasons: seasons
        };
    } else if (chartType === "episode") {
        config = {
            x: "id",
            y: "stardate",
            seasons: seasons
        };
    }

    parse(scatter(config));
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Add Margin to Heading Script for Trello
// @namespace    https://github.com/chestnutfield
// @version      0.1
// @description  Add a margin to heading tag for description.
// @author       Takashi Kurihara
// @include      https://trello.com/*
// @grant        none
// @require      https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// ==/UserScript==
var update = function() {
  $('div.current.markeddown.hide-on-edit.js-card-desc.js-show-with-desc :header').each(function(i){
    if (i == 0) {
      $(this).css("margin-bottom", "5px");
    } else {
      $(this).css("margin", "20px 0px 5px 0px");
    }
  });
};

$(document).ready(function() {
  setInterval(update, 5000);
});<commit_msg>:up: modify: set boader style<commit_after>// ==UserScript==
// @name         Add Margin to Heading Script for Trello
// @namespace    https://github.com/chestnutfield
// @version      0.1
// @description  Add a margin to heading tag for description.
// @author       Takashi Kurihara
// @include      https://trello.com/*
// @grant        none
// @require      https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// ==/UserScript==
var update = function() {
  $('div.current.markeddown.hide-on-edit.js-card-desc.js-show-with-desc :header').each(function(i){
    if ($(this)[0].tagName == "H2") {
      $(this).css("margin-bottom", "5px");
      $(this).css("border-left", "5px solid #48832C");
      $(this).css("border-bottom", "1px solid #48832C");
    } else {
      $(this).css("margin", "20px 0px 5px 0px");
      $(this).css("border-bottom", "1px solid #48832C");
    }
  });
};

$(document).ready(function() {
  setInterval(update, 5000);
});
<|endoftext|>


<commit_before>import camelCase from './camelCase';

/**
 * DOM-based Routing
 *
 * Based on {@link http://goo.gl/EUTi53|Markup-based Unobtrusive Comprehensive DOM-ready Execution} by Paul Irish
 *
 * The routing fires all common scripts, followed by the page specific scripts.
 * Add additional events for more control over timing e.g. a finalize event
 */
class Router {

  /**
   * Create a new Router
   * @param {Object} routes
   */
  constructor(routes) {
    this.routes = routes;
  }

  /**
   * Fire Router events
   * @param {string} route DOM-based route derived from body classes (`<body class="...">`)
   * @param {string} [event] Events on the route. By default, `init` and `finalize` events are called.
   * @param {string} [arg] Any custom argument to be passed to the event.
   */
  fire(route, event = 'init', arg) {
    document.dispatchEvent(new CustomEvent('routed', {
      bubbles: true,
      detail: {
        route,
        fn
      }
    }));

    const fire = route !== '' && this.routes[route] && typeof this.routes[route][event] === 'function';
    if (fire) {
      this.routes[route][event](arg);
    }
  }

  /**
   * Automatically load and fire Router events
   *
   * Events are fired in the following order:
   *  * common init
   *  * page-specific init
   *  * page-specific finalize
   *  * common finalize
   */
  loadEvents() {
    // Fire common init JS
    this.fire('common');

    // Fire page-specific init JS, and then finalize JS
    document.body.className
      .toLowerCase()
      .replace(/-/g, '_')
      .split(/\s+/)
      .map(camelCase)
      .forEach((className) => {
        this.fire(className);
        this.fire(className, 'finalize');
      });

    // Fire common finalize JS
    this.fire('common', 'finalize');
  }
}

export default Router
<commit_msg>Rename to event<commit_after>import camelCase from './camelCase';

/**
 * DOM-based Routing
 *
 * Based on {@link http://goo.gl/EUTi53|Markup-based Unobtrusive Comprehensive DOM-ready Execution} by Paul Irish
 *
 * The routing fires all common scripts, followed by the page specific scripts.
 * Add additional events for more control over timing e.g. a finalize event
 */
class Router {

  /**
   * Create a new Router
   * @param {Object} routes
   */
  constructor(routes) {
    this.routes = routes;
  }

  /**
   * Fire Router events
   * @param {string} route DOM-based route derived from body classes (`<body class="...">`)
   * @param {string} [event] Events on the route. By default, `init` and `finalize` events are called.
   * @param {string} [arg] Any custom argument to be passed to the event.
   */
  fire(route, event = 'init', arg) {
    document.dispatchEvent(new CustomEvent('routed', {
      bubbles: true,
      detail: {
        route,
        fn: event
      }
    }));

    const fire = route !== '' && this.routes[route] && typeof this.routes[route][event] === 'function';
    if (fire) {
      this.routes[route][event](arg);
    }
  }

  /**
   * Automatically load and fire Router events
   *
   * Events are fired in the following order:
   *  * common init
   *  * page-specific init
   *  * page-specific finalize
   *  * common finalize
   */
  loadEvents() {
    // Fire common init JS
    this.fire('common');

    // Fire page-specific init JS, and then finalize JS
    document.body.className
      .toLowerCase()
      .replace(/-/g, '_')
      .split(/\s+/)
      .map(camelCase)
      .forEach((className) => {
        this.fire(className);
        this.fire(className, 'finalize');
      });

    // Fire common finalize JS
    this.fire('common', 'finalize');
  }
}

export default Router
<|endoftext|>


<commit_before>var config = require('../../util').config;
var weinre = require('weinre');
weinre.run({
	boundHost: process.argv[3],
	httpPort: parseInt(process.argv[5]),
	verbose: false,
	debug: false,
	readTimeout: 5,
	deathTimeout: 15
});<commit_msg>remove weinre.js<commit_after><|endoftext|>


<commit_before>'use strict';

const DIR = './';
const DIR_COMMON = DIR + '../common/';
const path = require('path');

const root = require(DIR + 'root');
const config = require(DIR + 'config');
const CloudFunc = require(DIR_COMMON + 'cloudfunc');
const markdown = require(DIR + 'markdown');

const jaguar = require('jaguar/legacy');
const onezip = require('onezip/legacy');
const flop = require('flop');
const pullout = require('pullout/legacy');
const ponse = require('ponse');
const rendy = require('rendy');
const copymitter = require('copymitter');
const json = require('jonny');
const check = require('checkup');

const isWin32 = process.platform === 'win32';

/**
 * rest interface
 *
 * @param request
 * @param response
 * @param callback
 */
module.exports = (request, response, next) => {
    const params  = {
        request     : request,
        response    : response
    };

    check
        .type('next', next, 'function')
        .check({
            request: request,
            response: response
        });

    const apiURL = CloudFunc.apiURL;
    const name = ponse.getPathName(request);
    const regExp = RegExp('^' + apiURL);
    const is = regExp.test(name);

    if (!is)
        return next();

    params.name = name.replace(apiURL, '') || '/';

    sendData(params, (error, options, data) => {
        params.gzip = !error;

        if (!data) {
            data    = options;
            options = {};
        }

        if (options.name)
            params.name = options.name;

        if (options.gzip !== undefined)
            params.gzip = options.gzip;

        if (options.query)
            params.query = options.query;

        if (error)
            return ponse.sendError(error, params);

        ponse.send(data, params);
    });
};

/**
 * getting data on method and command
 *
 * @param params {name, method, body, requrest, response}
 */
function sendData(params, callback) {
    const p = params;
    const isMD = RegExp('^/markdown').test(p.name);

    if (isMD)
        return markdown(p.name, p.request, (error, data) => {
            callback(error, data);
        });

    switch(p.request.method) {
    case 'GET':
        onGET(params, callback);
        break;

    case 'PUT':
        pullout(p.request, 'string', (error, body) => {
            if (error)
                return callback(error);

            onPUT(p.name, body, callback);
        });
        break;
    }
}

function onGET(params, callback) {
    let cmd;
    const p = params;

    if (p.name[0] === '/')
        cmd = p.name.replace('/', '');

    if (/^pack/.test(cmd)) {
        cmd = cmd.replace(/^pack/, '');
        streamPack(root(cmd), p.response);
        return;
    }

    switch(cmd) {
    case '':
        p.data = json.stringify({
            info: 'Cloud Commander API v1'
        });

        callback(null, {name: 'api.json'}, p.data);
        break;

    default:
        callback({
            message: 'Not Found'
        });
        break;
    }
}

function getPackReg() {
    if (config('packer') === 'zip')
        return /\.zip$/;

    return /\.tar\.gz$/;
}

function streamPack(cmd, response) {
    const noop = () => {};
    const filename = cmd.replace(getPackReg(), '');
    const dir = path.dirname(filename);
    const names = [
        path.basename(filename)
    ];

    operation('pack', dir, response, names, noop);
}

function onPUT(name, body, callback) {
    let cmd;

    check
        .type('callback', callback, 'function')
        .check({
            name: name,
            body: body
        });

    if (name[0] === '/')
        cmd = name.replace('/', '');

    const files = json.parse(body);

    switch(cmd) {
    case 'mv':
        if (!files.from || !files.to)
            return callback(body);

        if (isRootAll([files.to, files.from]))
            return callback(getWin32RootMsg());

        files.from = root(files.from);
        files.to = root(files.to);

        copyFiles(files, flop.move, (error) => {
            const data = !files.names ? files : files.names.slice();
            const msg = formatMsg('move', data);

            callback(error, msg);
        });

        break;

    case 'cp':
        if (!files.from || !files.names || !files.to)
            return callback(body);

        if (isRootAll([files.to, files.from]))
            return callback(getWin32RootMsg());

        files.from  = root(files.from);
        files.to    = root(files.to);

        copy(files.from, files.to, files.names, (error) => {
            const msg = formatMsg('copy', files.names);
            callback(error, msg);
        });
        break;

    case 'pack':
        if (!files.from)
            return callback(body);

        pack(files.from, files.to, files.names, callback);
        break;

    case 'extract':
        if (!files.from)
            return callback(body);

        extract(files.from, files.to, callback);

        break;

    default:
        callback();
        break;
    }
}

function pack(from, to, names, fn) {
    from = root(from);
    to = root(to);

    if (!names) {
        names = [
            path.basename(from)
        ];

        from = path.dirname(from);
    }

    operation('pack', from, to, names, fn);
}

function extract(from, to, fn) {
    from = root(from);

    if (to)
        to  = root(to);
    else
        to = from.replace(/\.tar\.gz$/, '');

    operation('extract', from, to, fn);
}

function getPacker() {
    if (config('packer') === 'zip')
        return onezip;

    return jaguar;
}

function operation(op, from, to, names, fn) {
    if (!fn) {
        fn      = names;
        names   = [
            path.basename(from)
        ];
    }

    const packer = getPacker()[op](from, to, names);

    packer.on('error', error => {
        fn(error);
    });

    packer.on('progress', (count) => {
        process.stdout.write(rendy('\r{{ operation }} "{{ name }}": {{ count }}%', {
            operation   : op,
            name        : names[0],
            count       : count
        }));
    });

    packer.on('end', () => {
        process.stdout.write('\n');

        const name = path.basename(from);
        const msg = formatMsg(op, name);

        fn(null, msg);
    });
}

function copy(from, to, names, fn) {
    let error;
    const cp = copymitter(from, to, names);

    cp.on('error', e => {
        error = e;
        cp.abort();
    });

    cp.on('progress', (count) => {
        process.stdout.write(`\r copy ${from} ${to} ${count}%`);
    });

    cp.on('end', () => {
        process.stdout.write('\n');
        fn(error);
    });
}

function copyFiles(files, processFunc, callback) {
    let names = files.names;

    const copy = () => {
        let isLast;
        let name;
        let from = files.from;
        let to = files.to;

        if (names) {
            isLast  = !names.length;
            name    = names.shift();
            from    += name;
            to      += name;
        } else {
            isLast  = false;
            names   = [];
        }

        if (isLast)
            return callback();

        processFunc(from, to, error => {
            if (error)
                return callback(error);

            copy();
        });
    };

    check
        .type('callback', callback, 'function')
        .type('processFunc', processFunc, 'function')
        .check({
            files: files
        });

    copy();
}

function isRootWin32(path) {
    const isRoot = path === '/';
    const isConfig = config('root') === '/';

    return isWin32 && isRoot && isConfig;
}

function isRootAll(names) {
    return names.some((name) => {
        return isRootWin32(name);
    });
}

function getWin32RootMsg() {
    const message = 'Could not copy from/to root on windows!';
    const error = Error(message);

    return error;
}

function formatMsg(msgParam, dataParam, status) {
    let data;
    const isObj = typeof dataParam === 'object';

    if (isObj)
        data = json.stringify(dataParam);
    else
        data = dataParam;

    return CloudFunc.formatMsg(msgParam, data, status);
}

<commit_msg>refactor(rest) exports: shorthand properties<commit_after>'use strict';

const DIR = './';
const DIR_COMMON = DIR + '../common/';
const path = require('path');

const root = require(DIR + 'root');
const config = require(DIR + 'config');
const CloudFunc = require(DIR_COMMON + 'cloudfunc');
const markdown = require(DIR + 'markdown');

const jaguar = require('jaguar/legacy');
const onezip = require('onezip/legacy');
const flop = require('flop');
const pullout = require('pullout/legacy');
const ponse = require('ponse');
const rendy = require('rendy');
const copymitter = require('copymitter');
const json = require('jonny');
const check = require('checkup');

const isWin32 = process.platform === 'win32';

/**
 * rest interface
 *
 * @param request
 * @param response
 * @param callback
 */
module.exports = (request, response, next) => {
    check
        .type('next', next, 'function')
        .check({
            request,
            response,
        });

    const apiURL = CloudFunc.apiURL;
    const name = ponse.getPathName(request);
    const regExp = RegExp('^' + apiURL);
    const is = regExp.test(name);

    if (!is)
        return next();

    const params  = {
        request,
        response,
        name: name.replace(apiURL, '') || '/',
    };

    sendData(params, (error, options, data) => {
        params.gzip = !error;

        if (!data) {
            data = options;
            options = {};
        }

        if (options.name)
            params.name = options.name;

        if (options.gzip !== undefined)
            params.gzip = options.gzip;

        if (options.query)
            params.query = options.query;

        if (error)
            return ponse.sendError(error, params);

        ponse.send(data, params);
    });
};

/**
 * getting data on method and command
 *
 * @param params {name, method, body, requrest, response}
 */
function sendData(params, callback) {
    const p = params;
    const isMD = RegExp('^/markdown').test(p.name);

    if (isMD)
        return markdown(p.name, p.request, (error, data) => {
            callback(error, data);
        });

    switch(p.request.method) {
    case 'GET':
        onGET(params, callback);
        break;

    case 'PUT':
        pullout(p.request, 'string', (error, body) => {
            if (error)
                return callback(error);

            onPUT(p.name, body, callback);
        });
        break;
    }
}

function onGET(params, callback) {
    let cmd;
    const p = params;

    if (p.name[0] === '/')
        cmd = p.name.replace('/', '');

    if (/^pack/.test(cmd)) {
        cmd = cmd.replace(/^pack/, '');
        streamPack(root(cmd), p.response);
        return;
    }

    switch(cmd) {
    case '':
        p.data = json.stringify({
            info: 'Cloud Commander API v1'
        });

        callback(null, {name: 'api.json'}, p.data);
        break;

    default:
        callback({
            message: 'Not Found'
        });
        break;
    }
}

function getPackReg() {
    if (config('packer') === 'zip')
        return /\.zip$/;

    return /\.tar\.gz$/;
}

function streamPack(cmd, response) {
    const noop = () => {};
    const filename = cmd.replace(getPackReg(), '');
    const dir = path.dirname(filename);
    const names = [
        path.basename(filename)
    ];

    operation('pack', dir, response, names, noop);
}

function onPUT(name, body, callback) {
    let cmd;

    check
        .type('callback', callback, 'function')
        .check({
            name: name,
            body: body
        });

    if (name[0] === '/')
        cmd = name.replace('/', '');

    const files = json.parse(body);

    switch(cmd) {
    case 'mv':
        if (!files.from || !files.to)
            return callback(body);

        if (isRootAll([files.to, files.from]))
            return callback(getWin32RootMsg());

        files.from = root(files.from);
        files.to = root(files.to);

        copyFiles(files, flop.move, (error) => {
            const data = !files.names ? files : files.names.slice();
            const msg = formatMsg('move', data);

            callback(error, msg);
        });

        break;

    case 'cp':
        if (!files.from || !files.names || !files.to)
            return callback(body);

        if (isRootAll([files.to, files.from]))
            return callback(getWin32RootMsg());

        files.from  = root(files.from);
        files.to    = root(files.to);

        copy(files.from, files.to, files.names, (error) => {
            const msg = formatMsg('copy', files.names);
            callback(error, msg);
        });
        break;

    case 'pack':
        if (!files.from)
            return callback(body);

        pack(files.from, files.to, files.names, callback);
        break;

    case 'extract':
        if (!files.from)
            return callback(body);

        extract(files.from, files.to, callback);

        break;

    default:
        callback();
        break;
    }
}

function pack(from, to, names, fn) {
    from = root(from);
    to = root(to);

    if (!names) {
        names = [
            path.basename(from)
        ];

        from = path.dirname(from);
    }

    operation('pack', from, to, names, fn);
}

function extract(from, to, fn) {
    from = root(from);

    if (to)
        to  = root(to);
    else
        to = from.replace(/\.tar\.gz$/, '');

    operation('extract', from, to, fn);
}

function getPacker() {
    if (config('packer') === 'zip')
        return onezip;

    return jaguar;
}

function operation(op, from, to, names, fn) {
    if (!fn) {
        fn      = names;
        names   = [
            path.basename(from)
        ];
    }

    const packer = getPacker()[op](from, to, names);

    packer.on('error', error => {
        fn(error);
    });

    packer.on('progress', (count) => {
        process.stdout.write(rendy('\r{{ operation }} "{{ name }}": {{ count }}%', {
            operation   : op,
            name        : names[0],
            count       : count
        }));
    });

    packer.on('end', () => {
        process.stdout.write('\n');

        const name = path.basename(from);
        const msg = formatMsg(op, name);

        fn(null, msg);
    });
}

function copy(from, to, names, fn) {
    let error;
    const cp = copymitter(from, to, names);

    cp.on('error', e => {
        error = e;
        cp.abort();
    });

    cp.on('progress', (count) => {
        process.stdout.write(`\r copy ${from} ${to} ${count}%`);
    });

    cp.on('end', () => {
        process.stdout.write('\n');
        fn(error);
    });
}

function copyFiles(files, processFunc, callback) {
    let names = files.names;

    const copy = () => {
        let isLast;
        let name;
        let from = files.from;
        let to = files.to;

        if (names) {
            isLast  = !names.length;
            name    = names.shift();
            from    += name;
            to      += name;
        } else {
            isLast  = false;
            names   = [];
        }

        if (isLast)
            return callback();

        processFunc(from, to, error => {
            if (error)
                return callback(error);

            copy();
        });
    };

    check
        .type('callback', callback, 'function')
        .type('processFunc', processFunc, 'function')
        .check({
            files: files
        });

    copy();
}

function isRootWin32(path) {
    const isRoot = path === '/';
    const isConfig = config('root') === '/';

    return isWin32 && isRoot && isConfig;
}

function isRootAll(names) {
    return names.some((name) => {
        return isRootWin32(name);
    });
}

function getWin32RootMsg() {
    const message = 'Could not copy from/to root on windows!';
    const error = Error(message);

    return error;
}

function formatMsg(msgParam, dataParam, status) {
    let data;
    const isObj = typeof dataParam === 'object';

    if (isObj)
        data = json.stringify(dataParam);
    else
        data = dataParam;

    return CloudFunc.formatMsg(msgParam, data, status);
}

<|endoftext|>