<commit_before>/*
 * RevealBase Component For react-reveal
 *
 * Copyright © Roman Nosov 2016, 2017
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React from 'react';
import { string, object, number, bool, func, any, oneOfType, oneOf, instanceOf, shape, element } from 'prop-types';
import { namespace, ssr, disableSsr, globalHide, cascade, collapseend } from './lib/globals';
import Step from './lib/Step';
import debounce from './lib/debounce';

const
  inOut = shape({
    make: func,
    duration: number.isRequired,
    delay: number.isRequired,
    forever: bool,
    count: number.isRequired,
    style: object.isRequired,
    reverse: bool,
  }),
  propTypes = {
    when: any,
    spy: any,
    collapse: oneOfType([bool, shape({ height: string })]),
    wait: number,
    step: oneOfType([instanceOf(Step), string]),
    force: bool,
    disabled: bool,
    fraction: number,
    onReveal: func,
    children: element.isRequired,
    refProp: string,
    innerRef: func,
    in: inOut.isRequired,
    out: oneOfType([ inOut, oneOf([ false ]) ]).isRequired,
    //tag: string,
    //style: object,
    //className: string,
    //props: object,
  },
  defaultProps = {
    fraction: 0.2,
    when: true,
    refProp: 'ref',
  },
  contextTypes = {
    stepper: object,
  };

class RevealBase extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      style: {
        ...(props.collapse ? RevealBase.getInitialCollapseStyle(props): void 0),
        opacity: !props.when && props.out ? 0 : void 0,
      },
    };
    this.savedChild = false;
    this.isListener = false;
    //this.isShown = !!this.props.bypass;
    this.isShown = false;
    this.revealHandler = debounce(this.reveal.bind(this, false), 66);
    this.resizeHandler = debounce(this.resize.bind(this), 500);
    //this.invisible = debounce(this.invisible, 500);
    this.saveRef = this.saveRef.bind(this);
  }

  static getTop(el) {
    while (el.offsetTop === void 0)
      el = el.parentNode;
    let top = el.offsetTop;
    for (;el.offsetParent; top += el.offsetTop)
      el = el.offsetParent;
    return top;
  }

  saveRef(node) {
    this.el = node;
    if (this.childRef)
      this.childRef(node);
    if (this.props.innerRef)
      this.props.innerRef(node);
  }

  inViewport() {
    if (!this.el || window.document.hidden) return false;
    const h = this.el.offsetHeight,
          delta = window.pageYOffset - RevealBase.getTop(this.el),
          tail = Math.min(h, window.innerHeight) * ( globalHide ? this.props.fraction : 0 );
    return ( delta > tail - window.innerHeight ) && ( delta < h - tail );
  }

  hide() {
    if (this.props.out)
      this.setState({ style: { opacity: 0 } });
  }

  resize() {
    if (!this||!this.el||!this.props.when)
      return;
    if ( this.inViewport() ) {
      this.unlisten();
      this.isShown = !!this.props.when;
      this.setState({ style: { opacity: this.props.when || !this.props.out ? 1 : 0 } });
      this.onReveal(this.props);
      //if (this.props.onReveal && this.props.when)
      //  this.props.wait ? this.onRevealTimeout = window.setTimeout(this.props.onReveal, this.props.wait) : this.props.onReveal();
    }
  }

  invisible() {
    if (!this || !this.el)
      return;
    this.savedChild = false;
    if (!this.isShown) {
      this.setState( { style: { ...this.state.style, visibility: 'hidden' }/*, collapsing: false */});
      if (this.props.collapse)
        window.document.dispatchEvent(collapseend)
    }
  }

  animationEnd(func, cascade, { forever, count, delay, duration }) {
    if (forever)
      return;
    //const el = this.finalEl || this.el;
    const handler = () => {
      if (!this || !this.el)
        return;
      this.animationEndTimeout = void 0;
      //el.removeEventListener('animationend', handler);
      func.call(this);
    };
    this.animationEndTimeout = window.setTimeout(handler, delay+(duration+(cascade?(cascade === true?1000:cascade):0)*count));
    //el.addEventListener('animationend', handler);
    //this.animationEndEl = el;
    //this.animationEndHandler = handler;
  }

      //    //const delta = this.props.duration>>2,
      //    //      duration = delta,
      //    //      delay = this.props.delay + (this.props.when ? 0 : this.props.duration - delta)
  collapse(style, props, inOut) {
    if (props.collapse&&props.out) {
      const total = inOut.duration + (props.cascade ? ( props.cascade === true ? 1000 : props.cascade) : 0),
            delta = total>>2,
            duration = props.when ? delta : total - delta,
            delay = inOut.delay + (props.when ? 0 : delta),
            height = props.when ? ( props.collapse !== true && 'height' in props.collapse ? props.collapse.height : ((this.dummyEl&&this.dummyEl.offsetHeight) || false)) : 0;
            //console.log(this.dummyEl.marginTop);
            //margin = props.when ? : 0;
      if (height !== false)
        return {
            ...style,
            height,
            //margin: 0, padding: 0, border: '1px solid transparent',
            boxSizing: 'border-box',
            transition: `height ${duration}ms ease ${delay}ms`,
          //collapsing: true,
        };
    }
    return style;
  }

  animate(props) {
    if (!this || !this.el)
      return;
    this.unlisten();
    if (this.isShown === !!props.when)
      return;
    this.isShown = !!props.when;
    const leaving = !props.when && props.out,
          inOut = props[leaving ? 'out' : 'in'];
    //const inOut = props[props.when || !props.out ?'in':'out'];
    let animationName = (('style' in inOut) && inOut.style.animationName) || void 0;
    if ((props.out||props.when) && inOut.make)
        animationName = inOut.make();
    this.setState({
      style: this.collapse({
        ...inOut.style,
        animationDuration: `${inOut.duration}ms`,
        animationDelay: `${inOut.delay}ms`,
        animationIterationCount: inOut.forever ? 'infinite' : inOut.count,
        opacity: 1,
        //visibility: 'visible',
        animationName,
      }, props, inOut),
      className: inOut.className,
    });
    if (leaving) {
      this.savedChild = React.cloneElement(this.getChild());
      this.animationEnd( this.invisible, props.cascade, inOut);
    }
    else
      this.savedChild = false;
    this.onReveal(props);
  }

  onReveal(props) {
    if (props.onReveal && props.when) {
      if (this.onRevealTimeout)
        this.onRevealTimeout = window.clearTimeout(this.onRevealTimeout);
      props.wait ? this.onRevealTimeout = window.setTimeout(props.onReveal, props.wait) : props.onReveal();
    }
  }

  unlisten() {
    if (this.isListener) {
      window.removeEventListener('scroll', this.revealHandler);
      window.removeEventListener('orientationchange', this.revealHandler);
      window.document.removeEventListener('visibilitychange', this.revealHandler);
      window.document.removeEventListener('collapseend', this.revealHandler);
      window.removeEventListener('resize', this.resizeHandler);
      this.isListener = false;
    }
    if(this.onRevealTimeout)
      this.onRevealTimeout = window.clearTimeout(this.onRevealTimeout);
    if (this.animationEndTimeout)
      this.animationEndTimeout = window.clearTimeout(this.animationEndTimeout);
    //if (this.animationEndHandler)
    //   this.animationEndEl.removeEventListener('animationend', this.animationEndHandler);
  }

  componentWillUnmount() {
    this.unlisten();
    ssr && disableSsr();
  }

  listen() {
    if (!this.isListener) {
      this.isListener = true;
      window.addEventListener('scroll', this.revealHandler);
      window.addEventListener('orientationchange', this.revealHandler);
      window.document.addEventListener("visibilitychange", this.revealHandler);
      window.document.addEventListener("collapseend", this.revealHandler);
      window.addEventListener('resize', this.resizeHandler);
    }
  }

  reveal(props) {
    if (!this||!this.el) return;
    if (!props)
      props = this.props;
    if ( props.when && this.isShown && 'spy' in props ){
        this.isShown = false;
        this.setState({ style: {} });
        //window.setTimeout( () => this.animate.call(this, props), 200 );
        window.setTimeout( () => this.reveal(props), 200 );
    } else if ( this.inViewport() ) {
      if (this.start) {
        this.hide();
        this.listen();
        this.start(this.step);
        return;
      }
      this.animate(props);
    } else
      this.listen();
  }

  componentDidMount() {
    if (!this.el || this.props.disabled)
      return;
    if (this.props.force)
      return this.animate(this.props);
    if (this.props.step) {
      if (this.props.step instanceof Step)
        this.props.step.push(this);
      else if (this.context.stepper)
        this.context.stepper.get(this.props.step).push(this);
    }
    if ( ssr && (this.props.out||this.props.effect) && RevealBase.getTop(this.el) < window.pageYOffset + window.innerHeight ) {
      this.setState({ style: { opacity: 0, transition: 'opacity 1000ms' } });
      window.setTimeout(this.revealHandler, 1000);
    }
    else if(this.props.when)
      this.reveal(this.props);
  }

  cascade(children) {
    let newChildren;//, reverse = false;
    if (typeof children === 'string') {
          newChildren = children.split("").map( (ch, index) => {ch} );
          //reverse = this.props.reverse;
        }
        else
          newChildren = React.Children.toArray(children);
    const duration = this.props[this.props.when || !this.props.out ?'in':'out'].duration,
          count = newChildren.length - 1,
          total =  duration + ( this.props.cascade === true ? 1000 : this.props.cascade);
    //let i = reverse ? count : 0;
    let i = 0;
    newChildren = newChildren.map( child =>
      React.cloneElement(child,{
        style: {
          ...child.props.style,
          ...this.state.style,
          animationDuration: Math.round(cascade( /*reverse ? i-- : i++ */i++,0 , count, duration, total)) + 'ms',
        },
        //ref: i === count? (el => this.finalEl = el) : void 0,
      }));
    return newChildren;
  }

  static getInitialCollapseStyle(props) {
    return {
          visibility: props.when || !props.out ? 'visible' : 'hidden',
          height: 0,
          boxSizing: 'border-box',
    };
  }

  componentWillReceiveProps (props) {
    if (props.disabled)
      return;
    //if (props.responsive && !props.when && this.props.when && props.collapse && !this.props.collapse) {
    if (props.collapse && !this.props.collapse) {
      this.setState({ style: RevealBase.getInitialCollapseStyle(props)});
      this.isShown = false;
      return;
    }
    if ( props.when && props.collapse === true && this.dummyEl && this.dummyEl.offsetHeight && this.state.style.height !== this.dummyEl.offsetHeight )
      this.setState({ style: { ...this.state.style, height: this.dummyEl.offsetHeight } });
    if ( (props.when !== this.props.when) || (props.spy !== this.props.spy))
      this.reveal(props);
    //(props.onReveal !== this.props.onReveal) &&
    if (this.onRevealTimeout&& !props.when)
        this.onRevealTimeout = window.clearTimeout(this.onRevealTimeout);
  }

  dummy(el, child) {
    if (this.props.collapse !== true && 'height' in this.props.collapse)
      return el;
    return ({[
      el,
      <el.type
        {...el.props}
        {...{
          children: child.props.children,
          key: 2,
          //ref={ el => this.dummyEl = el }
          [this.props.refProp]: el => this.dummyEl = el,
          style: {
            ...el.props.style,
            position:'absolute',
            left:'-9999em',
            top:'-9999em',
            height: 'auto',
            //display: 'block',
            animationName: 'none',
            animationDuration: '0s',
            transition: 'none',
            opacity: 0,
          }
        }}
      />
    ]});
  }

  getChild() {
    if (this.savedChild && !this.props.disabled)
      return this.savedChild;
    else if (React.Children.count(this.props.children) === 1 /*|| this.props.tag*/)
      return React.Children.only(this.props.children);
    else {
      console.warn('react-reveal expects a single child');
      //return React.createElement(this.props.tag || 'div');
      return React.createElement('div');
    }
  }

  render() {
    let child = this.getChild();
    //if (this.props.disabled)
    //  return child;
    if (typeof child.ref === 'function')
      this.childRef = child.ref;
    let
      newChildren = false,
      { style, className, children } = child.props;
      //style = { ...style, ...this.props.style };
      //className = this.props.className ? (className||'') + ' ' + this.props.className : className;
    let
      newClass = this.props.disabled ? className : `${ this.props.out ? namespace : '' }${ this.state.className ? ' ' + this.state.className : '' }${ className ? ' ' + className : '' }`||void 0,
      newStyle = this.props.disabled ? style : { ...style, ...this.state.style };
    if (this.props.cascade && !this.props.disabled && children && this.state.style.animationName) {
      newChildren = this.cascade(children);
      newStyle.animationName = void 0;
    }
    const props = { ...this.props.props, className: newClass,  style: newStyle, [this.props.refProp]: this.saveRef };
    if (this.props.collapse && !this.props.disabled)
      props.key = 1;
    const el = React.cloneElement(child, props, newChildren||children);
    return this.props.collapse && !this.props.disabled ? this.dummy(el, child) : el;
  }

}

RevealBase.propTypes = propTypes;
RevealBase.defaultProps = defaultProps;
RevealBase.contextTypes = contextTypes;
export default RevealBase;
<commit_msg>adjusting collapse and cascade<commit_after>/*
 * RevealBase Component For react-reveal
 *
 * Copyright © Roman Nosov 2016, 2017
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React from 'react';
import { string, object, number, bool, func, any, oneOfType, oneOf, instanceOf, shape, element } from 'prop-types';
import { namespace, ssr, disableSsr, globalHide, cascade, collapseend } from './lib/globals';
import Step from './lib/Step';
import debounce from './lib/debounce';

const
  inOut = shape({
    make: func,
    duration: number.isRequired,
    delay: number.isRequired,
    forever: bool,
    count: number.isRequired,
    style: object.isRequired,
    reverse: bool,
  }),
  propTypes = {
    when: any,
    spy: any,
    collapse: oneOfType([bool, shape({ height: string })]),
    cascade: bool,
    wait: number,
    step: oneOfType([instanceOf(Step), string]),
    force: bool,
    disabled: bool,
    fraction: number,
    onReveal: func,
    children: element.isRequired,
    refProp: string,
    innerRef: func,
    in: inOut.isRequired,
    out: oneOfType([ inOut, oneOf([ false ]) ]).isRequired,
    //tag: string,
    //style: object,
    //className: string,
    //props: object,
  },
  defaultProps = {
    fraction: 0.2,
    when: true,
    refProp: 'ref',
  },
  contextTypes = {
    stepper: object,
  };

class RevealBase extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      style: {
        ...(props.collapse ? RevealBase.getInitialCollapseStyle(props): void 0),
        opacity: !props.when && props.out ? 0 : void 0,
      },
    };
    this.savedChild = false;
    this.isListener = false;
    //this.isShown = !!this.props.bypass;
    this.isShown = false;
    this.revealHandler = debounce(this.reveal.bind(this, false), 66);
    this.resizeHandler = debounce(this.resize.bind(this), 500);
    //this.invisible = debounce(this.invisible, 500);
    this.saveRef = this.saveRef.bind(this);
  }

  static getTop(el) {
    while (el.offsetTop === void 0)
      el = el.parentNode;
    let top = el.offsetTop;
    for (;el.offsetParent; top += el.offsetTop)
      el = el.offsetParent;
    return top;
  }

  saveRef(node) {
    this.el = node;
    if (this.childRef)
      this.childRef(node);
    if (this.props.innerRef)
      this.props.innerRef(node);
  }

  inViewport() {
    if (!this.el || window.document.hidden) return false;
    const h = this.el.offsetHeight,
          delta = window.pageYOffset - RevealBase.getTop(this.el),
          tail = Math.min(h, window.innerHeight) * ( globalHide ? this.props.fraction : 0 );
    return ( delta > tail - window.innerHeight ) && ( delta < h - tail );
  }

  hide() {
    if (this.props.out)
      this.setState({ style: { opacity: 0 } });
  }

  resize() {
    if (!this||!this.el||!this.props.when)
      return;
    if ( this.inViewport() ) {
      this.unlisten();
      this.isShown = !!this.props.when;
      this.setState({ style: { opacity: this.props.when || !this.props.out ? 1 : 0 } });
      this.onReveal(this.props);
      //if (this.props.onReveal && this.props.when)
      //  this.props.wait ? this.onRevealTimeout = window.setTimeout(this.props.onReveal, this.props.wait) : this.props.onReveal();
    }
  }

  invisible() {
    if (!this || !this.el)
      return;
    this.savedChild = false;
    if (!this.isShown) {
      this.setState( { style: { ...this.state.style, visibility: 'hidden' }/*, collapsing: false */});
      if (this.props.collapse)
        window.document.dispatchEvent(collapseend)
    }
  }

  animationEnd(func, cascade, { forever, count, delay, duration }) {
    if (forever)
      return;
    //const el = this.finalEl || this.el;
    const handler = () => {
      if (!this || !this.el)
        return;
      this.animationEndTimeout = void 0;
      //el.removeEventListener('animationend', handler);
      func.call(this);
    };
    this.animationEndTimeout = window.setTimeout(handler, delay+(duration+(cascade?(cascade === true?1000:cascade):0)*count));
    //el.addEventListener('animationend', handler);
    //this.animationEndEl = el;
    //this.animationEndHandler = handler;
  }

      //    //const delta = this.props.duration>>2,
      //    //      duration = delta,
      //    //      delay = this.props.delay + (this.props.when ? 0 : this.props.duration - delta)
  collapse(style, props, inOut) {
    if (props.collapse&&props.out) {
      const total = inOut.duration + (props.cascade ? inOut.duration : 0),
      //      delta = total>>2,
      //      duration = props.when ? delta : total - delta,
      //      delay = inOut.delay + (props.when ? 0 : delta),
            delta1 = total>>2,
            delta2 = delta1>>1,
            duration = delta1, // + (props.when ? 0 : delta2),
            delay = inOut.delay + (props.when ? 0 : total - delta1 - delta2),
            animationDuration = `${total - delta1 + (props.when ? delta2 : -delta2)}ms`,
            animationDelay = `${inOut.delay + (props.when ? delta1 - delta2 : 0)}ms`,
            height = props.when ? ( props.collapse !== true && 'height' in props.collapse ? props.collapse.height : ((this.dummyEl&&this.dummyEl.offsetHeight) || false)) : 0;
            //console.log(this.dummyEl.marginTop);
            //margin = props.when ? : 0;
      //console.log(duration, delay, animationDuration, animationDelay);
      if (height !== false)
        return {
            ...style,
            height,
            animationDuration,
            animationDelay,
            //margin: 0, padding: 0, border: '1px solid transparent',
            boxSizing: 'border-box',
            transition: `height ${duration}ms ease ${delay}ms`,
          //collapsing: true,
        };
    }
    return style;
  }

  animate(props) {
    if (!this || !this.el)
      return;
    this.unlisten();
    if (this.isShown === !!props.when)
      return;
    this.isShown = !!props.when;
    const leaving = !props.when && props.out,
          inOut = props[leaving ? 'out' : 'in'];
    //const inOut = props[props.when || !props.out ?'in':'out'];
    let animationName = (('style' in inOut) && inOut.style.animationName) || void 0;
    if ((props.out||props.when) && inOut.make)
        animationName = inOut.make();
    this.setState({
      style: this.collapse({
        ...inOut.style,
        animationDuration: `${inOut.duration}ms`,
        animationDelay: `${inOut.delay}ms`,
        animationIterationCount: inOut.forever ? 'infinite' : inOut.count,
        opacity: 1,
        //visibility: 'visible',
        animationName,
      }, props, inOut),
      className: inOut.className,
    });
    if (leaving) {
      this.savedChild = React.cloneElement(this.getChild());
      this.animationEnd( this.invisible, props.cascade, inOut);
    }
    else
      this.savedChild = false;
    this.onReveal(props);
  }

  onReveal(props) {
    if (props.onReveal && props.when) {
      if (this.onRevealTimeout)
        this.onRevealTimeout = window.clearTimeout(this.onRevealTimeout);
      props.wait ? this.onRevealTimeout = window.setTimeout(props.onReveal, props.wait) : props.onReveal();
    }
  }

  unlisten() {
    if (this.isListener) {
      window.removeEventListener('scroll', this.revealHandler);
      window.removeEventListener('orientationchange', this.revealHandler);
      window.document.removeEventListener('visibilitychange', this.revealHandler);
      window.document.removeEventListener('collapseend', this.revealHandler);
      window.removeEventListener('resize', this.resizeHandler);
      this.isListener = false;
    }
    if(this.onRevealTimeout)
      this.onRevealTimeout = window.clearTimeout(this.onRevealTimeout);
    if (this.animationEndTimeout)
      this.animationEndTimeout = window.clearTimeout(this.animationEndTimeout);
    //if (this.animationEndHandler)
    //   this.animationEndEl.removeEventListener('animationend', this.animationEndHandler);
  }

  componentWillUnmount() {
    this.unlisten();
    ssr && disableSsr();
  }

  listen() {
    if (!this.isListener) {
      this.isListener = true;
      window.addEventListener('scroll', this.revealHandler);
      window.addEventListener('orientationchange', this.revealHandler);
      window.document.addEventListener("visibilitychange", this.revealHandler);
      window.document.addEventListener("collapseend", this.revealHandler);
      window.addEventListener('resize', this.resizeHandler);
    }
  }

  reveal(props) {
    if (!this||!this.el) return;
    if (!props)
      props = this.props;
    if ( props.when && this.isShown && 'spy' in props ){
        this.isShown = false;
        this.setState({ style: {} });
        //window.setTimeout( () => this.animate.call(this, props), 200 );
        window.setTimeout( () => this.reveal(props), 200 );
    } else if ( this.inViewport() ) {
      if (this.start) {
        this.hide();
        this.listen();
        this.start(this.step);
        return;
      }
      this.animate(props);
    } else
      this.listen();
  }

  componentDidMount() {
    if (!this.el || this.props.disabled)
      return;
    if (this.props.force)
      return this.animate(this.props);
    if (this.props.step) {
      if (this.props.step instanceof Step)
        this.props.step.push(this);
      else if (this.context.stepper)
        this.context.stepper.get(this.props.step).push(this);
    }
    if ( ssr && (this.props.out||this.props.effect) && RevealBase.getTop(this.el) < window.pageYOffset + window.innerHeight ) {
      this.setState({ style: { opacity: 0, transition: 'opacity 1000ms' } });
      window.setTimeout(this.revealHandler, 1000);
    }
    else if(this.props.when)
      this.reveal(this.props);
  }

  cascade(children) {
    let newChildren;//, reverse = false;
    if (typeof children === 'string') {
          newChildren = children.split("").map( (ch, index) => {ch} );
          //reverse = this.props.reverse;
        }
        else
          newChildren = React.Children.toArray(children);
    let duration = this.props[this.props.when || !this.props.out ?'in':'out'].duration,
          count = newChildren.length - 1,
          total = duration*2;
    if (this.props.collapse) {
      total = parseInt(this.state.style.animationDuration, 10);
      duration = total/2;
    }
    //total =  duration + ( this.props.cascade === true ? 1000 : this.props.cascade);
    //let i = reverse ? count : 0;
    let i = 0;
    newChildren = newChildren.map( child =>
      React.cloneElement(child,{
        style: {
          ...child.props.style,
          ...this.state.style,
          animationDuration: Math.round(cascade( /*reverse ? i-- : i++ */i++,0 , count, duration, total)) + 'ms',
        },
        //ref: i === count? (el => this.finalEl = el) : void 0,
      }));
    return newChildren;
  }

  static getInitialCollapseStyle(props) {
    return {
          visibility: props.when || !props.out ? 'visible' : 'hidden',
          height: 0,
          boxSizing: 'border-box',
    };
  }

  componentWillReceiveProps (props) {
    if (props.disabled)
      return;
    //if (props.responsive && !props.when && this.props.when && props.collapse && !this.props.collapse) {
    if (props.collapse && !this.props.collapse) {
      this.setState({ style: RevealBase.getInitialCollapseStyle(props)});
      this.isShown = false;
      return;
    }
    if ( props.when && props.collapse === true && this.dummyEl && this.dummyEl.offsetHeight && this.state.style.height !== this.dummyEl.offsetHeight )
      this.setState({ style: { ...this.state.style, height: this.dummyEl.offsetHeight } });
    if ( (props.when !== this.props.when) || (props.spy !== this.props.spy))
      this.reveal(props);
    //(props.onReveal !== this.props.onReveal) &&
    if (this.onRevealTimeout&& !props.when)
        this.onRevealTimeout = window.clearTimeout(this.onRevealTimeout);
  }

  dummy(el, child) {
    if (this.props.collapse !== true && 'height' in this.props.collapse)
      return el;
    return ({[
      el,
      <el.type
        {...el.props}
        {...{
          children: child.props.children,
          key: 2,
          //ref={ el => this.dummyEl = el }
          [this.props.refProp]: el => this.dummyEl = el,
          style: {
            ...el.props.style,
            position:'absolute',
            left:'-9999em',
            top:'-9999em',
            height: 'auto',
            //display: 'block',
            animationName: 'none',
            animationDuration: '0s',
            transition: 'none',
            opacity: 0,
          }
        }}
      />
    ]});
  }

  getChild() {
    if (this.savedChild && !this.props.disabled)
      return this.savedChild;
    else if (React.Children.count(this.props.children) === 1 /*|| this.props.tag*/)
      return React.Children.only(this.props.children);
    else {
      console.warn('react-reveal expects a single child');
      //return React.createElement(this.props.tag || 'div');
      return React.createElement('div');
    }
  }

  render() {
    let child = this.getChild();
    //if (this.props.disabled)
    //  return child;
    if (typeof child.ref === 'function')
      this.childRef = child.ref;
    let
      newChildren = false,
      { style, className, children } = child.props;
      //style = { ...style, ...this.props.style };
      //className = this.props.className ? (className||'') + ' ' + this.props.className : className;
    let
      newClass = this.props.disabled ? className : `${ this.props.out ? namespace : '' }${ this.state.className ? ' ' + this.state.className : '' }${ className ? ' ' + className : '' }`||void 0,
      newStyle = this.props.disabled ? style : { ...style, ...this.state.style };
    if (this.props.cascade && !this.props.disabled && children && this.state.style.animationName) {
      newChildren = this.cascade(children);
      newStyle.animationName = void 0;
    }
    const props = { ...this.props.props, className: newClass,  style: newStyle, [this.props.refProp]: this.saveRef };
    if (this.props.collapse && !this.props.disabled)
      props.key = 1;
    const el = React.cloneElement(child, props, newChildren||children);
    return this.props.collapse && !this.props.disabled ? this.dummy(el, child) : el;
  }

}

RevealBase.propTypes = propTypes;
RevealBase.defaultProps = defaultProps;
RevealBase.contextTypes = contextTypes;
export default RevealBase;
<|endoftext|>


<commit_before>var React = require('react');
var PropTypes = require('prop-types');
var createClass = require('create-react-class');

/*
	NOTES

	1. Stop content jumping around when overflow is hidden on the body.
	2. Mobile Safari ignores { overflow: hidden } declaration on the body.
	3. Allow scroll on provided target.
*/

var ScrollLock = createClass({
	propTypes: {
		scrollTarget: PropTypes.object,
	},
	componentDidMount: function () {
		if (!canUseDom()) return;

		var scrollTarget = this.props.scrollTarget;
		var scrollbarWidth = window.innerWidth - document.body.clientWidth; // 1.
		var target = document.body;

		target.style.paddingRight = scrollbarWidth + 'px';
		target.style.overflowY = 'hidden';

		target.addEventListener('touchmove', preventTouchMove, false); // 2.

		if (scrollTarget) {
			scrollTarget.addEventListener('touchstart', preventInertiaScroll, false); // 3.
			scrollTarget.addEventListener('touchmove', allowTouchMove, false); // 3.
		}
	},
	componentWillUnmount: function () {
		if (!canUseDom()) return;

		var scrollTarget = this.props.scrollTarget;
		var target = document.body;

		target.style.paddingRight = '';
		target.style.overflowY = '';

		target.removeEventListener('touchmove', preventTouchMove, false);

		if (scrollTarget) {
			scrollTarget.removeEventListener('touchstart', preventInertiaScroll, false);
			scrollTarget.removeEventListener('touchmove', allowTouchMove, false);
		}
	},
	render: function () {
		return null;
	}
});

function preventTouchMove (e) {
	e.preventDefault();
};

function allowTouchMove (e) {
	e.stopPropagation();
};

function preventInertiaScroll () {
	var top = this.scrollTop;
	var totalScroll = this.scrollHeight;
	var currentScroll = top + this.offsetHeight;

	if (top === 0) {
		this.scrollTop = 1;
	} else if (currentScroll === totalScroll) {
		this.scrollTop = top - 1;
	}
}

function canUseDom () {
	return !!(
		typeof window !== 'undefined'
		&& window.document
		&& window.document.createElement
	);
};

module.exports = ScrollLock;
<commit_msg>Fix preventDefault being ignored due to event listeners being passive (#2)<commit_after>var React = require('react');
var PropTypes = require('prop-types');
var createClass = require('create-react-class');

/*
	NOTES

	1. Stop content jumping around when overflow is hidden on the body.
	2. Mobile Safari ignores { overflow: hidden } declaration on the body.
	3. Allow scroll on provided target.
*/

var listenerOptions = { capture: false, passive: false };
var ScrollLock = createClass({
	propTypes: {
		scrollTarget: PropTypes.object,
		preventContentJumping: PropTypes.bool
	},
	defaultProps: {
		preventContentJumping: true
	},
	componentDidMount: function () {
		if (!canUseDom()) return;

		var scrollTarget = this.props.scrollTarget;
		var target = document.body;

		if (this.props.preventContentJumping) {
			var scrollbarWidth = window.innerWidth - document.body.clientWidth; // 1.

			target.style.paddingRight = scrollbarWidth + 'px';
		}
		target.style.overflowY = 'hidden';

		target.addEventListener('touchmove', preventTouchMove, listenerOptions); // 2.

		if (scrollTarget) {
			scrollTarget.addEventListener('touchstart', preventInertiaScroll, listenerOptions); // 3.
			scrollTarget.addEventListener('touchmove', allowTouchMove, listenerOptions); // 3.
		}
	},
	componentWillUnmount: function () {
		if (!canUseDom()) return;

		var scrollTarget = this.props.scrollTarget;
		var target = document.body;

		if (this.props.preventContentJumping) {
			target.style.paddingRight = '';
		}
		target.style.overflowY = '';

		target.removeEventListener('touchmove', preventTouchMove, listenerOptions);

		if (scrollTarget) {
			scrollTarget.removeEventListener('touchstart', preventInertiaScroll, listenerOptions);
			scrollTarget.removeEventListener('touchmove', allowTouchMove, listenerOptions);
		}
	},
	render: function () {
		return null;
	}
});

function preventTouchMove (e) {
	e.preventDefault();
};

function allowTouchMove (e) {
	e.stopPropagation();
};

function preventInertiaScroll () {
	var top = this.scrollTop;
	var totalScroll = this.scrollHeight;
	var currentScroll = top + this.offsetHeight;

	if (top === 0) {
		this.scrollTop = 1;
	} else if (currentScroll === totalScroll) {
		this.scrollTop = top - 1;
	}
}

function canUseDom () {
	return !!(
		typeof window !== 'undefined'
		&& window.document
		&& window.document.createElement
	);
};

module.exports = ScrollLock;
<|endoftext|>


<commit_before>var crypto = require("crypto")
  , events = require('events')
  , _ = require('underscore')._
  , express = require('express')
  , config = require('./config.json');

var tupasPath = "/tupas"
  , cancelPath = tupasPath + "/cancel"
  , okPath = tupasPath + "/ok"
  , rejectPath = tupasPath + "/reject";

var SHA256 = "03"
  , TUPAS_MESSAGE_TYPE = "701"
  , LANG_CODES = ['FI', 'SV', 'EN'];

var tupasFormTemplate = _.template(
                         '<form id="<%= id %>-form" method="POST" action="<%= bankAuthUrl %>" class="tupas-button">'+
                         '<div id="<%= id %>-login" style="cursor: pointer">' +
                         '
<img src="<%= imgPath %>" alt="<%= name %>">
' +
                         '
<%= name %>
' +
                         '
' +
                         '<input name="A01Y_ACTION_ID" type="hidden" value="<%= messageType %>">' +
                         '<input name="A01Y_VERS" type="hidden" value="<%= version %>">' +
                         '<input name="A01Y_RCVID" type="hidden" value="<%= vendorId %>">' +
                         '<input name="A01Y_LANGCODE" type="hidden" value="<%= languageCode %>">' +
                         '<input name="A01Y_STAMP" type="hidden" value="<%= identifier %>">' +
                         '<input name="A01Y_IDTYPE" type="hidden" value="<%= idType %>">' +
                         '<input name="A01Y_RETLINK" type="hidden" value="<%= returnLink %>">' +
                         '<input name="A01Y_CANLINK" type="hidden" value="<%= cancelLink %>">' +
                         '<input name="A01Y_REJLINK" type="hidden" value="<%= rejectLink %>">' +
                         '<input name="A01Y_KEYVERS" type="hidden" value="<%= keyVersion %>">' +
                         '<input name="A01Y_ALG" type="hidden" value="<%= algorithmType %>">' +
                         '<input name="A01Y_MAC" type="hidden" value="<%= mac %>">' +
                         '' +
                         '</form>');

exports.create = function (globalOpts, bankOpts) {
  requireArgument(globalOpts.appHandler, "globalOpts.appHandler");
  requireArgument(globalOpts.hostUrl, "globalOpts.hostUrl");

  var tupas = Object.create(events.EventEmitter.prototype);
  var banks = updatedBankConfigsWith(bankOpts);
  var vendorOpts = _.extend({}, globalOpts,
    { returnUrls : returnUrls(globalOpts.hostUrl) });

  bindReturnUrlsToHandler(tupas, vendorOpts.appHandler);
  vendorOpts.appHandler.use(express.static(__dirname + '/public'));

  tupas.banks = _.pluck(banks, 'id');
  tupas.requestMac = generateMacForRequest;
  tupas.responseMac = function (params) {
    return generateMacForResponse(params, banks)
  };

  tupas.buildRequestParams = function (bankId, languageCode, requestId) {
    return buildParamsForRequest(findConfig(bankId, banks),
      languageCode, vendorOpts.returnUrls, requestId);
  };

  tupas.tupasButton = function (bankId, languageCode, requestId) {
    var formParams = tupas.buildRequestParams(bankId, languageCode, requestId);
    return tupasFormTemplate(formParams);
  };

  return tupas;
};

function requireArgument(argValue, argName) {
  if (typeof argValue === "undefined" || argValue === null) {
    throw "Missing required argument " + argName + ".";
  }
}

function returnUrls (hostUrl) {
  return {
    ok: hostUrl + okPath,
    cancel: hostUrl + cancelPath,
    reject: hostUrl + rejectPath
  };
}

function updatedBankConfigsWith (bankOpts) {
  var updatedDefaults = mergeWithDefaults(bankOpts);
  var defaultBankIds = _.pluck(updatedDefaults, 'id');
  var newBanks = _.reject(bankOpts, function (bank) {
    return _.contains(defaultBankIds, bank.id)
  });

  return updatedDefaults.concat(newBanks);
}

function mergeWithDefaults (bankOpts) {
  return _.map(config.banks, function (bank) {
    var vendorOpts = _.find(bankOpts, function (bankConf) {
      return bankConf.id == bank.id;
    });

    if (vendorOpts) {
      return _.extend({}, bank, vendorOpts)
    } else {
      return bank
    }
  });
}

function bindReturnUrlsToHandler (tupas, handler) {
  handler.post(okPath, ok(tupas)); // Danske Bank uses POST.
  handler.get(okPath, ok(tupas));  // Others use GET.
  handler.get(cancelPath, cancel(tupas));
  handler.get(rejectPath, reject(tupas));
}

function buildParamsForRequest (bank, languageCode, returnUrls, requestId) {
  if (invalidLangCode(languageCode))
    throw "Unsupported language code: " + languageCode + ".";
  if (requestId.length > 20)
    throw "Request id too long: " + requestId + ".";

  var params = {
    name : bank.name,
    id : bank.id,
    bankAuthUrl: bank.authUrl,
    messageType: TUPAS_MESSAGE_TYPE,
    version: bank.version,
    vendorId: bank.vendorId,
    identifier: requestId,
    languageCode: languageCode,
    idType: bank.idType,
    returnLink: returnUrls.ok,
    cancelLink: returnUrls.cancel,
    rejectLink: returnUrls.reject,
    keyVersion: bank.keyVersion,
    algorithmType: SHA256,
    checksumKey: bank.checksumKey,
    imgPath : bank.imgPath
  };

  params.mac = generateMacForRequest (params);

  return params;
}

function invalidLangCode(langCode) {
  return !_.contains(LANG_CODES, langCode);
}

function findConfig (bankId, bankConfig) {
  return _.find(bankConfig, function (bank) {
    return bank.id == bankId;
  });
}

function generateMacForRequest (requestParams) {
  var macParams = [
    requestParams.messageType,
    requestParams.version,
    requestParams.vendorId,
    requestParams.languageCode,
    requestParams.identifier,
    requestParams.idType,
    requestParams.returnLink,
    requestParams.cancelLink,
    requestParams.rejectLink,
    requestParams.keyVersion,
    requestParams.algorithmType,
    requestParams.checksumKey
  ];

  return generateMac(macParams);
}

function generateMacForResponse (queryParams, bankConfig) {
  var bankNumber = queryParams.B02K_TIMESTMP.substr(0, 3);
  var bank = _.find(bankConfig, function (bank) {
    return bank.number == bankNumber;
  });

  var macParams = _.map(_.compact([
    queryParams.B02K_VERS,
    queryParams.B02K_TIMESTMP,
    queryParams.B02K_IDNBR,
    queryParams.B02K_STAMP,
    queryParams.B02K_CUSTNAME,
    queryParams.B02K_KEYVERS,
    queryParams.B02K_ALG,
    queryParams.B02K_CUSTID,
    queryParams.B02K_CUSTTYPE,
    queryParams.B02K_USERID,
    queryParams.B02K_USERNAME,
    bank.checksumKey
  ]), function (val) {
    return unescape(val).replace('+', ' ');
  });

  return generateMac(macParams);
}

function generateMac(params) {
  var joinedParams = params.join("&") + "&";
  return crypto.createHash('sha256').update(joinedParams).digest('hex').toUpperCase();
}

function ok (tupas) {
  return function (req, res) {
    if (req.query.B02K_MAC && req.query.B02K_MAC.toUpperCase() === tupas.responseMac(req.query)) {
      tupas.emit('success', req, res);
    } else {
      tupas.emit('mac-check-failed', req, res);
    }
  }
}

function cancel (tupas) {
  return function (req, res) {
    tupas.emit('cancel', req, res);
  }
}

function reject (tupas) {
  return function (req, res) {
    tupas.emit('reject', req, res);
  }
}
<commit_msg>Fix replace in return value decoding.<commit_after>var crypto = require("crypto")
  , events = require('events')
  , _ = require('underscore')._
  , express = require('express')
  , config = require('./config.json');

var tupasPath = "/tupas"
  , cancelPath = tupasPath + "/cancel"
  , okPath = tupasPath + "/ok"
  , rejectPath = tupasPath + "/reject";

var SHA256 = "03"
  , TUPAS_MESSAGE_TYPE = "701"
  , LANG_CODES = ['FI', 'SV', 'EN'];

var tupasFormTemplate = _.template(
                         '<form id="<%= id %>-form" method="POST" action="<%= bankAuthUrl %>" class="tupas-button">'+
                         '<div id="<%= id %>-login" style="cursor: pointer">' +
                         '
<img src="<%= imgPath %>" alt="<%= name %>">
' +
                         '
<%= name %>
' +
                         '
' +
                         '<input name="A01Y_ACTION_ID" type="hidden" value="<%= messageType %>">' +
                         '<input name="A01Y_VERS" type="hidden" value="<%= version %>">' +
                         '<input name="A01Y_RCVID" type="hidden" value="<%= vendorId %>">' +
                         '<input name="A01Y_LANGCODE" type="hidden" value="<%= languageCode %>">' +
                         '<input name="A01Y_STAMP" type="hidden" value="<%= identifier %>">' +
                         '<input name="A01Y_IDTYPE" type="hidden" value="<%= idType %>">' +
                         '<input name="A01Y_RETLINK" type="hidden" value="<%= returnLink %>">' +
                         '<input name="A01Y_CANLINK" type="hidden" value="<%= cancelLink %>">' +
                         '<input name="A01Y_REJLINK" type="hidden" value="<%= rejectLink %>">' +
                         '<input name="A01Y_KEYVERS" type="hidden" value="<%= keyVersion %>">' +
                         '<input name="A01Y_ALG" type="hidden" value="<%= algorithmType %>">' +
                         '<input name="A01Y_MAC" type="hidden" value="<%= mac %>">' +
                         '' +
                         '</form>');

exports.create = function (globalOpts, bankOpts) {
  requireArgument(globalOpts.appHandler, "globalOpts.appHandler");
  requireArgument(globalOpts.hostUrl, "globalOpts.hostUrl");

  var tupas = Object.create(events.EventEmitter.prototype);
  var banks = updatedBankConfigsWith(bankOpts);
  var vendorOpts = _.extend({}, globalOpts,
    { returnUrls : returnUrls(globalOpts.hostUrl) });

  bindReturnUrlsToHandler(tupas, vendorOpts.appHandler);
  vendorOpts.appHandler.use(express.static(__dirname + '/public'));

  tupas.banks = _.pluck(banks, 'id');
  tupas.requestMac = generateMacForRequest;
  tupas.responseMac = function (params) {
    return generateMacForResponse(params, banks)
  };

  tupas.buildRequestParams = function (bankId, languageCode, requestId) {
    return buildParamsForRequest(findConfig(bankId, banks),
      languageCode, vendorOpts.returnUrls, requestId);
  };

  tupas.tupasButton = function (bankId, languageCode, requestId) {
    var formParams = tupas.buildRequestParams(bankId, languageCode, requestId);
    return tupasFormTemplate(formParams);
  };

  return tupas;
};

function requireArgument(argValue, argName) {
  if (typeof argValue === "undefined" || argValue === null) {
    throw "Missing required argument " + argName + ".";
  }
}

function returnUrls (hostUrl) {
  return {
    ok: hostUrl + okPath,
    cancel: hostUrl + cancelPath,
    reject: hostUrl + rejectPath
  };
}

function updatedBankConfigsWith (bankOpts) {
  var updatedDefaults = mergeWithDefaults(bankOpts);
  var defaultBankIds = _.pluck(updatedDefaults, 'id');
  var newBanks = _.reject(bankOpts, function (bank) {
    return _.contains(defaultBankIds, bank.id)
  });

  return updatedDefaults.concat(newBanks);
}

function mergeWithDefaults (bankOpts) {
  return _.map(config.banks, function (bank) {
    var vendorOpts = _.find(bankOpts, function (bankConf) {
      return bankConf.id == bank.id;
    });

    if (vendorOpts) {
      return _.extend({}, bank, vendorOpts)
    } else {
      return bank
    }
  });
}

function bindReturnUrlsToHandler (tupas, handler) {
  handler.post(okPath, ok(tupas)); // Danske Bank uses POST.
  handler.get(okPath, ok(tupas));  // Others use GET.
  handler.get(cancelPath, cancel(tupas));
  handler.get(rejectPath, reject(tupas));
}

function buildParamsForRequest (bank, languageCode, returnUrls, requestId) {
  if (invalidLangCode(languageCode))
    throw "Unsupported language code: " + languageCode + ".";
  if (requestId.length > 20)
    throw "Request id too long: " + requestId + ".";

  var params = {
    name : bank.name,
    id : bank.id,
    bankAuthUrl: bank.authUrl,
    messageType: TUPAS_MESSAGE_TYPE,
    version: bank.version,
    vendorId: bank.vendorId,
    identifier: requestId,
    languageCode: languageCode,
    idType: bank.idType,
    returnLink: returnUrls.ok,
    cancelLink: returnUrls.cancel,
    rejectLink: returnUrls.reject,
    keyVersion: bank.keyVersion,
    algorithmType: SHA256,
    checksumKey: bank.checksumKey,
    imgPath : bank.imgPath
  };

  params.mac = generateMacForRequest (params);

  return params;
}

function invalidLangCode(langCode) {
  return !_.contains(LANG_CODES, langCode);
}

function findConfig (bankId, bankConfig) {
  return _.find(bankConfig, function (bank) {
    return bank.id == bankId;
  });
}

function generateMacForRequest (requestParams) {
  var macParams = [
    requestParams.messageType,
    requestParams.version,
    requestParams.vendorId,
    requestParams.languageCode,
    requestParams.identifier,
    requestParams.idType,
    requestParams.returnLink,
    requestParams.cancelLink,
    requestParams.rejectLink,
    requestParams.keyVersion,
    requestParams.algorithmType,
    requestParams.checksumKey
  ];

  return generateMac(macParams);
}

function generateMacForResponse (queryParams, bankConfig) {
  var bankNumber = queryParams.B02K_TIMESTMP.substr(0, 3);
  var bank = _.find(bankConfig, function (bank) {
    return bank.number == bankNumber;
  });

  var macParams = _.map(_.compact([
    queryParams.B02K_VERS,
    queryParams.B02K_TIMESTMP,
    queryParams.B02K_IDNBR,
    queryParams.B02K_STAMP,
    queryParams.B02K_CUSTNAME,
    queryParams.B02K_KEYVERS,
    queryParams.B02K_ALG,
    queryParams.B02K_CUSTID,
    queryParams.B02K_CUSTTYPE,
    queryParams.B02K_USERID,
    queryParams.B02K_USERNAME,
    bank.checksumKey
  ]), function (val) {
    return unescape(val).replace(/\+/g, ' ');
  });

  return generateMac(macParams);
}

function generateMac(params) {
  var joinedParams = params.join("&") + "&";
  return crypto.createHash('sha256').update(joinedParams).digest('hex').toUpperCase();
}

function ok (tupas) {
  return function (req, res) {
    if (req.query.B02K_MAC && req.query.B02K_MAC.toUpperCase() === tupas.responseMac(req.query)) {
      tupas.emit('success', req, res);
    } else {
      tupas.emit('mac-check-failed', req, res);
    }
  }
}

function cancel (tupas) {
  return function (req, res) {
    tupas.emit('cancel', req, res);
  }
}

function reject (tupas) {
  return function (req, res) {
    tupas.emit('reject', req, res);
  }
}
<|endoftext|>


<commit_before>var Bluebird = require('bluebird');
var Chalk = require('chalk');
var Cli = require('structured-cli');
var ConfigFile = require('../../lib/config');
var Sandbox = require('sandboxjs');
var SuperagentProxy = require('superagent-proxy');
var _ = require('lodash');

module.exports = {
    onBeforeConfigure: require('./profileOptions').onBeforeConfigure,
    onBeforeHandler: onBeforeHandler,
};

function onBeforeHandler(context) {
    var args = context.args;

    return sandboxFromArguments(args)
        .then(onProfile);

    function onProfile(profile) {
        args.profile = profile;
    }
}

function sandboxFromArguments(args, options) {
    return new Bluebird(function (resolve, reject) {
        if (!options) options = {};

        if (args.token) {
            if (args.profile && !options.allowProfile) return resolve(new Cli.error.invalid('--profile should not be specified with custom tokens'));

            var sandboxOptions = {
                onBeforeRequest,
                url: args.url || 'https://webtask.it.auth0.com',
            };

            if (args.container) sandboxOptions.container = args.container;

            try {
                return resolve(Sandbox.fromToken(args.token, sandboxOptions));
            } catch (e) {
                return reject(e);
            }
        }

        if (args.url) return reject(Cli.error.invalid('--token must be specified with --url'));

        var config = new ConfigFile();
        var profile$ = config.load()
            .then(loadProfile)
            .then(onProfileLoaded);

        return resolve(profile$);

        function loadProfile(profiles) {
            if (_.isEmpty(profiles)) {
                throw Cli.error.hint('No webtask profiles found. To get started:\n'
                    + Chalk.bold('$ wt init'));
            }

            return config.getProfile(args.profile);
        }

        function onBeforeRequest(request) {
            const proxy = process.env.http_proxy || process.env.HTTP_PROXY;
            const result = proxy
                ?   SuperagentProxy(request, proxy)
                :   request;

            return result;
        }

        function onProfileLoaded(profile) {
            if (args.container) profile.container = args.container;

            return profile;
        }
    });
}
<commit_msg>Fix for when --url, --token and --container are all passed<commit_after>var Bluebird = require('bluebird');
var Chalk = require('chalk');
var Cli = require('structured-cli');
var ConfigFile = require('../../lib/config');
var Sandbox = require('sandboxjs');
var SuperagentProxy = require('superagent-proxy');
var _ = require('lodash');

module.exports = {
    onBeforeConfigure: require('./profileOptions').onBeforeConfigure,
    onBeforeHandler: onBeforeHandler,
};

function onBeforeHandler(context) {
    var args = context.args;

    return sandboxFromArguments(args)
        .then(onProfile);

    function onProfile(profile) {
        args.profile = profile;
    }
}

function sandboxFromArguments(args, options) {
    return new Bluebird(function (resolve, reject) {
        if (!options) options = {};

        if (args.token) {
            if (args.profile && !options.allowProfile) return resolve(new Cli.error.invalid('--profile should not be specified with custom tokens'));

            var sandboxOptions = {
                onBeforeRequest,
                url: args.url || 'https://webtask.it.auth0.com',
            };

            if (args.container && args.token) {
                try {
                    return resolve(Sandbox.init({
                        onBeforeRequest,
                        container: args.container,
                        token: args.token,
                        url: args.url,
                    }));
                } catch (e) {
                    return reject(e);
                }
            }

            if (args.container) sandboxOptions.container = args.container;

            try {
                return resolve(Sandbox.fromToken(args.token, sandboxOptions));
            } catch (e) {
                return reject(e);
            }
        }

        if (args.url) return reject(Cli.error.invalid('--token must be specified with --url'));

        var config = new ConfigFile();
        var profile$ = config.load()
            .then(loadProfile)
            .then(onProfileLoaded);

        return resolve(profile$);

        function loadProfile(profiles) {
            if (_.isEmpty(profiles)) {
                throw Cli.error.hint('No webtask profiles found. To get started:\n'
                    + Chalk.bold('$ wt init'));
            }

            return config.getProfile(args.profile);
        }

        function onBeforeRequest(request) {
            const proxy = process.env.http_proxy || process.env.HTTP_PROXY;
            const result = proxy
                ?   SuperagentProxy(request, proxy)
                :   request;

            return result;
        }

        function onProfileLoaded(profile) {
            if (args.container) profile.container = args.container;

            return profile;
        }
    });
}
<|endoftext|>


<commit_before>var util = require('util')
  , twitter = require('twitter')
  , Stream = require('stream')
  , repl = require('repl')
  , keys = require('./keys')
  , local = repl.start()

local.context.repl = local
local.defineCommand('tweet', function(tweet){
  twit
    .verifyCredentials(function(data) {
      console.log(util.inspect(data))
    })
    .updateStatus('Test tweet from node-twitter/' + twitter.VERSION,
      function(data) {
        console.log(util.inspect(data))
    })
})

var twish = new twitter(keys)
//twish.get('/statuses/show/183682338646011904.json', function(data){
  //console.log(data)
//})
//twish.stream('statuses/sample', function(stream){
twish.stream('user', {track:'gkatsev', delimited:20}, function(stream){
  stream.on('data', function(data){
    setTimeout(function(){
      process.stdout.write(JSON.stringify(data, null, '  '))
    }, 1000)
  })
})

module.exports = twish
<commit_msg>actually tweet tweet rather than test message<commit_after>var util = require('util')
  , twitter = require('twitter')
  , Stream = require('stream')
  , repl = require('repl')
  , keys = require('./keys')
  , local = repl.start()
  , first = true

local.context.repl = local
local.defineCommand('tweet', function(tweet){
  twit
    .verifyCredentials(function(data) {
      console.log(util.inspect(data))
    })
    .updateStatus(tweet,
      function(data) {
        console.log(util.inspect(data))
    })
})

var twish = new twitter(keys)
//twish.get('/statuses/show/183682338646011904.json', function(data){
  //console.log(data)
//})
//twish.stream('statuses/sample', function(stream){
twish.stream('user', {track:'gkatsev', delimited:20}, function(stream){
  stream.on('data', function(data){
    if(first){
      first = false
      return
    }
    setTimeout(function(){
      process.stdout.write(JSON.stringify(data, null, '  '))
    }, 500)
  })
})

module.exports = twish
<|endoftext|>


<commit_before>/*global IScroll*/
(function($) {
  /**
   * Wrapper widget around iScroll adding special bump events which
   * are triggered when scrolling to the very top or very bottom
   * (called boundary posititon below).
   * @private
   */
  $.widget('pageflow.scroller', {
    dragThreshold: 50,
    maxXDelta: 50,
    doubleBumpThreshold: 500,

    _create: function() {
      this.iscroll = new IScroll(this.element[0], _.extend({
        mouseWheel: true,
        bounce: false,
        keyBindings: true,
        probeType: 2,
        preventDefault: false
      }, _.pick(this.options, 'freeScroll', 'scrollX', 'noMouseWheelScrollX')));

      this.iscroll.disable();

      if (pageflow.entryData.getThemingOption('page_change_by_scrolling')) {
        this._initMousewheelBump('up');
        this._initMousewheelBump('down');
        this._initDragGestureBump();
      }

      this._initKeyboardBump('up');
      this._initKeyboardBump('down');
      this._initNearBottomEvents();
      this._initNearTopEvents();
      this._initMoveEvents();

      this._onScrollEndCallbacks = new $.Callbacks();
    },

    enable: function() {
      this.iscroll.enable();
      this.iscroll.refresh();
    },

    resetPosition: function(options) {
      options = options || {};

      this.iscroll.refresh();

      if (options.position === 'bottom') {
        this.iscroll.scrollTo(0, this.iscroll.maxScrollY, 0);
      }
      else {
        this.iscroll.scrollTo(0, 0, 0);
      }

      this._triggerBoundaryEvents();
    },

    scrollBy: function(deltaX, deltaY, time, easing) {
      this.scrollTo(
        this.iscroll.x + deltaX,
        this.iscroll.y + deltaY,
        time,
        easing
      );
    },

    scrollTo: function(x, y, time, easing) {
      this.iscroll.scrollTo(
        Math.max(Math.min(x, 0), this.iscroll.maxScrollX),
        Math.max(Math.min(y, 0), this.iscroll.maxScrollY),
        time,
        easing
      );
      this._onScrollEndCallbacks.fire();
    },

    refresh: function() {
      this.iscroll.refresh();
    },

    afterAnimationHook: function() {
      this._triggerBoundaryEvents();
    },

    disable: function() {
      this.iscroll.disable();
    },

    positionX: function() {
      return this.iscroll.x;
    },

    positionY: function() {
      return this.iscroll.y;
    },

    maxX: function() {
      return this.iscroll.maxScrollX;
    },

    maxY: function() {
      return this.iscroll.maxScrollY;
    },

    onScroll: function(callback) {
      this.iscroll.on('scroll', callback);
    },

    onScrollEnd: function(callback) {
      this.iscroll.on('scrollEnd', callback);
      this._onScrollEndCallbacks.add(callback);
    },

    _initMoveEvents: function() {
      this.iscroll.on('mousewheelup', _.bind(this._triggerMoveEvent, this));
      this.iscroll.on('mousewheeldown', _.bind(this._triggerMoveEvent, this));
      this.iscroll.on('afterkeyboard', _.bind(this._triggerMoveEvent, this));
    },

    _triggerMoveEvent: function() {
      this._trigger('move');
    },

    _initNearBottomEvents: function() {
      this.iscroll.on('scroll', _.bind(this._triggerNearBottomEvents, this));
      this.iscroll.on('scrollEnd', _.bind(this._triggerNearBottomEvents, this));
      this.iscroll.on('afterkeyboard', _.bind(this._triggerNearBottomEvents, this));
    },

    _initNearTopEvents: function() {
      this.iscroll.on('scroll', _.bind(this._triggerNearTopEvents, this));
      this.iscroll.on('scrollEnd', _.bind(this._triggerNearTopEvents, this));
      this.iscroll.on('afterkeyboard', _.bind(this._triggerNearTopEvents, this));
    },

    _triggerBoundaryEvents: function() {
      this._triggerNearTopEvents();
      this._triggerNearBottomEvents();
    },

    _triggerNearBottomEvents: function() {
      if (this._atBoundary('down', {delta: 50})) {
        this._trigger('nearbottom');
      }
      else {
        this._trigger('notnearbottom');
      }
    },

    _triggerNearTopEvents: function() {
      if (this._atBoundary('up', {delta: 50})) {
        this._trigger('neartop');
      }
      else {
        this._trigger('notneartop');
      }
    },

    // Whenever the a mousewheel event is triggered, we test whether
    // the scroller is at the very top or at the very bottom. If so,
    // we trigger a hintdown or hintup event the first time the mouse
    // wheel turns and a bumpup or bumpdown event when the mouse wheel
    // is turned to times in a short period of time.
    _initMousewheelBump: function(direction) {
      var firstBump = false;

      this.iscroll.on('mousewheel' + direction, _.bind(function() {
        if (!this._atBoundary(direction)) {
          return;
        }

        if (firstBump) {
          this._trigger('bump' + direction);
          firstBump = false;

          clearTimeout(this.waitForSecondBump);
        }
        else {
          this._trigger('hint' + direction);
          firstBump = true;

          this.waitForSecondBump = setTimeout(function() {
            firstBump = false;
          }, this.doubleBumpThreshold);
        }
      }, this));
    },

    // Trigger bumpup or bumpdown event when the a up/down key is
    // pressed while the scroller in boundary position.
    _initKeyboardBump: function(direction) {
      this.iscroll.on('keyboard' + direction, _.bind(function(event) {
        if (this._atBoundary(direction)) {
          // Make sure other iScrolls which might be enabled by the
          // bump event do not process the keyboard event again.
          event.stopImmediatePropagation();
          this._trigger('bump' + direction);
        }
      }, this));

      this.iscroll.on('keyboardhint' + direction, _.bind(function() {
        if (this._atBoundary(direction)) {
          this._trigger('hint' + direction);
        }
      }, this));
    },

    // Trigger bumpup or bumpdown when the user drags the page from a
    // boundary position.
    _initDragGestureBump: function() {
      var allowUp = false,
          allowDown = false,
          startX, startY;

      this.element.on('touchstart MSPointerDown pointerdown', _.bind(function(event) {
        var point = event.originalEvent.touches ? event.originalEvent.touches[0] : event.originalEvent;
        startX = point.pageX;
        startY = point.pageY;

        if (!isNonTouchPointer(event)) {
          allowDown = this._atBoundary('down');
          allowUp = this._atBoundary('up');
        }
      }, this));

      this.element.on('touchmove MSPointerMove pointermove', _.bind(function(event) {
        var point = event.originalEvent.touches ? event.originalEvent.touches[0] : event.originalEvent;
        var deltaX = point.pageX - startX;
        var deltaY = point.pageY - startY;

        if (Math.abs(deltaX) > this.maxXDelta) {
          allowDown = allowUp = false;
        }

        if (allowUp && deltaY > this.dragThreshold) {
          this._trigger('bumpup');
          allowDown = allowUp = false;
        }
        else if (allowDown && deltaY < -this.dragThreshold) {
          this._trigger('bumpdown');
          allowDown = allowUp = false;
        }
      }, this));

      this.element.on('touchend MSPointerUp pointerup', _.bind(function(event) {
        if (allowUp) {
          this._trigger('hintup');
        }
        if (allowDown) {
          this._trigger('hintdown');
        }
      }, this));

      function isNonTouchPointer(event) {
        return event.originalEvent.pointerType &&
          event.originalEvent.pointerType !== event.originalEvent.MSPOINTER_TYPE_TOUCH &&
          event.originalEvent.pointerType !== 'touch';
      }
    },

    // Checks whether the scroller is at the very top or very bottom.
    _atBoundary: function(direction, options) {
      options = options || {};
      var delta = options.delta || 0;

      if (direction === 'up') {
        return (this.iscroll.y >= -delta);
      }
      else {
        return (this.iscroll.y <= this.iscroll.maxScrollY + delta);
      }
    }
  });
}(jQuery));<commit_msg>Dispatch sroller events for horizontal bump and hint gestures<commit_after>/*global IScroll*/
(function($) {
  /**
   * Wrapper widget around iScroll adding special bump events which
   * are triggered when scrolling to the very top or very bottom
   * (called boundary posititon below).
   * @private
   */
  $.widget('pageflow.scroller', {
    dragThreshold: 50,
    maxXDelta: 50,
    maxYDelta: 50,
    doubleBumpThreshold: 500,

    _create: function() {
      this.iscroll = new IScroll(this.element[0], _.extend({
        mouseWheel: true,
        bounce: false,
        keyBindings: true,
        probeType: 2,
        preventDefault: false
      }, _.pick(this.options, 'freeScroll', 'scrollX', 'noMouseWheelScrollX')));

      this.iscroll.disable();

      if (pageflow.entryData.getThemingOption('page_change_by_scrolling')) {
        this._initMousewheelBump('up');
        this._initMousewheelBump('down');
        this._initDragGestureBump();
      }

      this._initKeyboardBump('up');
      this._initKeyboardBump('down');
      this._initNearBottomEvents();
      this._initNearTopEvents();
      this._initMoveEvents();

      this._onScrollEndCallbacks = new $.Callbacks();
    },

    enable: function() {
      this.iscroll.enable();
      this.iscroll.refresh();
    },

    resetPosition: function(options) {
      options = options || {};

      this.iscroll.refresh();

      if (options.position === 'bottom') {
        this.iscroll.scrollTo(0, this.iscroll.maxScrollY, 0);
      }
      else {
        this.iscroll.scrollTo(0, 0, 0);
      }

      this._triggerBoundaryEvents();
    },

    scrollBy: function(deltaX, deltaY, time, easing) {
      this.scrollTo(
        this.iscroll.x + deltaX,
        this.iscroll.y + deltaY,
        time,
        easing
      );
    },

    scrollTo: function(x, y, time, easing) {
      this.iscroll.scrollTo(
        Math.max(Math.min(x, 0), this.iscroll.maxScrollX),
        Math.max(Math.min(y, 0), this.iscroll.maxScrollY),
        time,
        easing
      );
      this._onScrollEndCallbacks.fire();
    },

    refresh: function() {
      this.iscroll.refresh();
    },

    afterAnimationHook: function() {
      this._triggerBoundaryEvents();
    },

    disable: function() {
      this.iscroll.disable();
    },

    positionX: function() {
      return this.iscroll.x;
    },

    positionY: function() {
      return this.iscroll.y;
    },

    maxX: function() {
      return this.iscroll.maxScrollX;
    },

    maxY: function() {
      return this.iscroll.maxScrollY;
    },

    onScroll: function(callback) {
      this.iscroll.on('scroll', callback);
    },

    onScrollEnd: function(callback) {
      this.iscroll.on('scrollEnd', callback);
      this._onScrollEndCallbacks.add(callback);
    },

    _initMoveEvents: function() {
      this.iscroll.on('mousewheelup', _.bind(this._triggerMoveEvent, this));
      this.iscroll.on('mousewheeldown', _.bind(this._triggerMoveEvent, this));
      this.iscroll.on('afterkeyboard', _.bind(this._triggerMoveEvent, this));
    },

    _triggerMoveEvent: function() {
      this._trigger('move');
    },

    _initNearBottomEvents: function() {
      this.iscroll.on('scroll', _.bind(this._triggerNearBottomEvents, this));
      this.iscroll.on('scrollEnd', _.bind(this._triggerNearBottomEvents, this));
      this.iscroll.on('afterkeyboard', _.bind(this._triggerNearBottomEvents, this));
    },

    _initNearTopEvents: function() {
      this.iscroll.on('scroll', _.bind(this._triggerNearTopEvents, this));
      this.iscroll.on('scrollEnd', _.bind(this._triggerNearTopEvents, this));
      this.iscroll.on('afterkeyboard', _.bind(this._triggerNearTopEvents, this));
    },

    _triggerBoundaryEvents: function() {
      this._triggerNearTopEvents();
      this._triggerNearBottomEvents();
    },

    _triggerNearBottomEvents: function() {
      if (this._atBoundary('down', {delta: 50})) {
        this._trigger('nearbottom');
      }
      else {
        this._trigger('notnearbottom');
      }
    },

    _triggerNearTopEvents: function() {
      if (this._atBoundary('up', {delta: 50})) {
        this._trigger('neartop');
      }
      else {
        this._trigger('notneartop');
      }
    },

    // Whenever the a mousewheel event is triggered, we test whether
    // the scroller is at the very top or at the very bottom. If so,
    // we trigger a hintdown or hintup event the first time the mouse
    // wheel turns and a bumpup or bumpdown event when the mouse wheel
    // is turned to times in a short period of time.
    _initMousewheelBump: function(direction) {
      var firstBump = false;

      this.iscroll.on('mousewheel' + direction, _.bind(function() {
        if (!this._atBoundary(direction)) {
          return;
        }

        if (firstBump) {
          this._trigger('bump' + direction);
          firstBump = false;

          clearTimeout(this.waitForSecondBump);
        }
        else {
          this._trigger('hint' + direction);
          firstBump = true;

          this.waitForSecondBump = setTimeout(function() {
            firstBump = false;
          }, this.doubleBumpThreshold);
        }
      }, this));
    },

    // Trigger bumpup or bumpdown event when the a up/down key is
    // pressed while the scroller in boundary position.
    _initKeyboardBump: function(direction) {
      this.iscroll.on('keyboard' + direction, _.bind(function(event) {
        if (this._atBoundary(direction)) {
          // Make sure other iScrolls which might be enabled by the
          // bump event do not process the keyboard event again.
          event.stopImmediatePropagation();
          this._trigger('bump' + direction);
        }
      }, this));

      this.iscroll.on('keyboardhint' + direction, _.bind(function() {
        if (this._atBoundary(direction)) {
          this._trigger('hint' + direction);
        }
      }, this));
    },

    // Trigger bumpup or bumpdown when the user drags the page from a
    // boundary position. Trigger bumpleft or bumpright if user drags
    // horizontally.
    _initDragGestureBump: function() {
      var allowUp = false,
          allowDown = false,
          allowLeft = false,
          allowRight = false,
          startX, startY;

      this.element.on('touchstart MSPointerDown pointerdown', _.bind(function(event) {
        var point = event.originalEvent.touches ?
                    event.originalEvent.touches[0] : event.originalEvent;

        startX = point.pageX;
        startY = point.pageY;

        if (!this._isNonTouchPointer(event)) {
          allowDown = this._atBoundary('down');
          allowUp = this._atBoundary('up');
          allowLeft = true;
          allowRight = true;
        }
      }, this));

      this.element.on('touchmove MSPointerMove pointermove', _.bind(function(event) {
        var point = event.originalEvent.touches ?
                    event.originalEvent.touches[0] : event.originalEvent;

        var deltaX = point.pageX - startX;
        var deltaY = point.pageY - startY;

        if (Math.abs(deltaX) > this.maxXDelta) {
          allowDown = allowUp = false;
        }

        if (Math.abs(deltaY) > this.maxYDelta) {
          allowLeft = allowRight = false;
        }

        if (allowUp && deltaY > this.dragThreshold) {
          this._trigger('bumpup');
          allowDown = allowUp = allowLeft = allowRight = false;
        }
        else if (allowDown && deltaY < -this.dragThreshold) {
          this._trigger('bumpdown');
          allowDown = allowUp = allowLeft = allowRight = false;
        }
        else if (allowLeft && deltaX > this.dragThreshold) {
          this._trigger('bumpleft');
          allowDown = allowUp = allowLeft = allowRight = false;
        }
        else if (allowRight && deltaX < -this.dragThreshold) {
          this._trigger('bumpright');
          allowDown = allowUp = allowLeft = allowRight =false;
        }
      }, this));

      this.element.on('touchend MSPointerUp pointerup', _.bind(function(event) {
        var point = event.originalEvent.touches ?
                    event.originalEvent.changedTouches[0] : event.originalEvent;

        var deltaX = point.pageX - startX;
        var deltaY = point.pageY - startY;

        if (allowUp && deltaY > 0) {
          this._trigger('hintup');
        }
        else if (allowDown && deltaY < 0) {
          this._trigger('hintdown');
        }

        if (allowLeft && deltaX > 0) {
          this._trigger('hintleft');
        }
        else if (allowRight && deltaX < 0) {
          this._trigger('hintright');
        }
      }, this));
    },

    _isNonTouchPointer: function(event) {
      return event.originalEvent.pointerType &&
             event.originalEvent.pointerType !== event.originalEvent.MSPOINTER_TYPE_TOUCH &&
             event.originalEvent.pointerType !== 'touch';
    },

    // Checks whether the scroller is at the very top or very bottom.
    _atBoundary: function(direction, options) {
      options = options || {};
      var delta = options.delta || 0;

      if (direction === 'up') {
        return (this.iscroll.y >= -delta);
      }
      else {
        return (this.iscroll.y <= this.iscroll.maxScrollY + delta);
      }
    }
  });
}(jQuery));
<|endoftext|>


<commit_before>declare var Intl: any;

declare type Path = string;
declare type Locale = string;
declare type LocaleMessage = string | LocaleMessageObject | LocaleMessageArray;
declare type LocaleMessageObject = { [key: Path]: LocaleMessage };
declare type LocaleMessageArray = Array<LocaleMessage>;
declare type LocaleMessages = { [key: Locale]: LocaleMessageObject };

// This options is the same as Intl.DateTimeFormat constructor options:
// http://www.ecma-international.org/ecma-402/2.0/#sec-intl-datetimeformat-constructor
declare type DateTimeFormatOptions = {
  year?: 'numeric' | '2-digit',
  month?: 'numeric' | '2-digit' | 'narrow' | 'short' | 'long',
  day?: 'numeric' | '2-digit',
  hour?: 'numeric' | '2-digit',
  minute?: 'numeric' | '2-digit',
  second?: 'numeric' | '2-digit',
  weekday?: 'narrow' | 'short' | 'long',
  hour12?: boolean,
  era?: 'narrow' | 'short' | 'long',
  timeZone?: string, // IANA time zone
  timeZoneName?: 'short' | 'long',
  localeMatcher?: 'lookup' | 'best fit',
  formatMatcher?: 'basic' | 'best fit'
};
declare type DateTimeFormat = { [key: string]: DateTimeFormatOptions };
declare type DateTimeFormats = { [key: Locale]: DateTimeFormat };

// This options is the same as Intl.NumberFormat constructor options:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
declare type NumberFormatOptions = {
  style?: 'decimal' | 'currency' | 'percent',
  currency?: string, // ISO 4217 currency codes
  currencyDisplay?: 'symbol' | 'code' | 'name',
  useGrouping?: boolean,
  minimumIntegerDigits?: number,
  minimumFractionDigits?: number,
  maximumFractionDigits?: number,
  minimumSignificantDigits?: number,
  maximumSignificantDigits?: number,
  localeMatcher?: 'lookup' | 'best fit',
  formatMatcher?: 'basic' | 'best fit'
};
declare type NumberFormat = { [key: string]: NumberFormatOptions };
declare type NumberFormats = { [key: Locale]: NumberFormat };

declare type TranslateResult = string | Array<any>;
declare type DateTimeFormatResult = string;
declare type NumberFormatResult = string;
declare type MissingHandler = (locale: Locale, key: Path, vm?: any) => void;

declare type I18nOptions = {
  locale?: Locale,
  fallbackLocale?: Locale,
  messages?: LocaleMessages,
  dateTimeFormats?: DateTimeFormats,
  numberFormats?: NumberFormats,
  formatter?: Formatter,
  missing?: MissingHandler,
  root?: I18n, // for internal
  fallbackRoot?: boolean,
  sync?: boolean,
  silentTranslationWarn?: boolean
};

declare type IntlAvailability = {
  dateTimeFormat: boolean,
  numberFormat: boolean
};

declare interface I18n {
  static install: () => void, // for Vue plugin interface
  static version: string,
  static availabilities: IntlAvailability,
  get vm (): any, // for internal
  get locale (): Locale,
  set locale (locale: Locale): void,
  get fallbackLocale (): Locale,
  set fallbackLocale (locale: Locale): void,
  get messages (): LocaleMessages,
  get dateTimeFormats (): DateTimeFormats,
  get missing (): ?MissingHandler,
  set missing (handler: MissingHandler): void,
  get formatter (): Formatter,
  set formatter (formatter: Formatter): void,
  get silentTranslationWarn (): boolean,
  set silentTranslationWarn (silent: boolean): void,
  getLocaleMessage (locale: Locale): LocaleMessageObject,
  setLocaleMessage (locale: Locale, message: LocaleMessageObject): void,
  mergeLocaleMessage (locale: Locale, message: LocaleMessageObject): void,
  t (key: Path, ...values: any): TranslateResult,
  i (key: Path, ...values: any): TranslateResult,
  tc (key: Path, choice?: number, ...values: any): TranslateResult,
  te (key: Path, locale?: Locale): boolean,
  getDateTimeFormat (locale: Locale): DateTimeFormat,
  setDateTimeFormat (locale: Locale, format: DateTimeFormat): void,
  mergeDateTimeFormat (locale: Locale, format: DateTimeFormat): void,
  d (value: number | Date, ...args: any): DateTimeFormatResult,
  getNumberFormat (locale: Locale): NumberFormat,
  setNumberFormat (locale: Locale, format: NumberFormat): void,
  mergeNumberFormat (locale: Locale, format: NumberFormat): void,
  n (value: number, ...args: any): NumberFormatResult
};

declare type FormatterOptions = { [key: string]: any };

declare interface Formatter {
  interpolate (message: string, values: any): Array<any>
};
<commit_msg>:shirt: update(flowtype): remove unneccesary type<commit_after>declare var Intl: any;

declare type Path = string;
declare type Locale = string;
declare type LocaleMessage = string | LocaleMessageObject | LocaleMessageArray;
declare type LocaleMessageObject = { [key: Path]: LocaleMessage };
declare type LocaleMessageArray = Array<LocaleMessage>;
declare type LocaleMessages = { [key: Locale]: LocaleMessageObject };

// This options is the same as Intl.DateTimeFormat constructor options:
// http://www.ecma-international.org/ecma-402/2.0/#sec-intl-datetimeformat-constructor
declare type DateTimeFormatOptions = {
  year?: 'numeric' | '2-digit',
  month?: 'numeric' | '2-digit' | 'narrow' | 'short' | 'long',
  day?: 'numeric' | '2-digit',
  hour?: 'numeric' | '2-digit',
  minute?: 'numeric' | '2-digit',
  second?: 'numeric' | '2-digit',
  weekday?: 'narrow' | 'short' | 'long',
  hour12?: boolean,
  era?: 'narrow' | 'short' | 'long',
  timeZone?: string, // IANA time zone
  timeZoneName?: 'short' | 'long',
  localeMatcher?: 'lookup' | 'best fit',
  formatMatcher?: 'basic' | 'best fit'
};
declare type DateTimeFormat = { [key: string]: DateTimeFormatOptions };
declare type DateTimeFormats = { [key: Locale]: DateTimeFormat };

// This options is the same as Intl.NumberFormat constructor options:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
declare type NumberFormatOptions = {
  style?: 'decimal' | 'currency' | 'percent',
  currency?: string, // ISO 4217 currency codes
  currencyDisplay?: 'symbol' | 'code' | 'name',
  useGrouping?: boolean,
  minimumIntegerDigits?: number,
  minimumFractionDigits?: number,
  maximumFractionDigits?: number,
  minimumSignificantDigits?: number,
  maximumSignificantDigits?: number,
  localeMatcher?: 'lookup' | 'best fit',
  formatMatcher?: 'basic' | 'best fit'
};
declare type NumberFormat = { [key: string]: NumberFormatOptions };
declare type NumberFormats = { [key: Locale]: NumberFormat };

declare type TranslateResult = string | Array<any>;
declare type DateTimeFormatResult = string;
declare type NumberFormatResult = string;
declare type MissingHandler = (locale: Locale, key: Path, vm?: any) => void;

declare type I18nOptions = {
  locale?: Locale,
  fallbackLocale?: Locale,
  messages?: LocaleMessages,
  dateTimeFormats?: DateTimeFormats,
  numberFormats?: NumberFormats,
  formatter?: Formatter,
  missing?: MissingHandler,
  root?: I18n, // for internal
  fallbackRoot?: boolean,
  sync?: boolean,
  silentTranslationWarn?: boolean
};

declare type IntlAvailability = {
  dateTimeFormat: boolean,
  numberFormat: boolean
};

declare interface I18n {
  static install: () => void, // for Vue plugin interface
  static version: string,
  static availabilities: IntlAvailability,
  get vm (): any, // for internal
  get locale (): Locale,
  set locale (locale: Locale): void,
  get fallbackLocale (): Locale,
  set fallbackLocale (locale: Locale): void,
  get messages (): LocaleMessages,
  get dateTimeFormats (): DateTimeFormats,
  get missing (): ?MissingHandler,
  set missing (handler: MissingHandler): void,
  get formatter (): Formatter,
  set formatter (formatter: Formatter): void,
  get silentTranslationWarn (): boolean,
  set silentTranslationWarn (silent: boolean): void,
  getLocaleMessage (locale: Locale): LocaleMessageObject,
  setLocaleMessage (locale: Locale, message: LocaleMessageObject): void,
  mergeLocaleMessage (locale: Locale, message: LocaleMessageObject): void,
  t (key: Path, ...values: any): TranslateResult,
  i (key: Path, ...values: any): TranslateResult,
  tc (key: Path, choice?: number, ...values: any): TranslateResult,
  te (key: Path, locale?: Locale): boolean,
  getDateTimeFormat (locale: Locale): DateTimeFormat,
  setDateTimeFormat (locale: Locale, format: DateTimeFormat): void,
  mergeDateTimeFormat (locale: Locale, format: DateTimeFormat): void,
  d (value: number | Date, ...args: any): DateTimeFormatResult,
  getNumberFormat (locale: Locale): NumberFormat,
  setNumberFormat (locale: Locale, format: NumberFormat): void,
  mergeNumberFormat (locale: Locale, format: NumberFormat): void,
  n (value: number, ...args: any): NumberFormatResult
};

declare interface Formatter {
  interpolate (message: string, values: any): Array<any>
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';

import Meadow from './Meadow';

export default React.createClass({
  displayName: 'Meadow.TypeChoice',

  getDefaultProps() {
    return {
      types: [],
      onReplaceInfoAtKeyPath: null,
      tabIndex: 0,
    };
  },

  shouldComponentUpdate(nextProps, nextState) {
    const currentProps = this.props;

    return (
      nextProps.types !== currentProps.types ||
      nextProps.value != currentProps.value ||
      nextProps.typeSpecs !== currentProps.typeSpecs ||
      nextProps.fieldSpecs !== currentProps.fieldSpecs ||
      nextProps.fieldComponent !== currentProps.fieldComponent ||
      nextProps.onReplaceInfoAtKeyPath !== currentProps.onReplaceInfoAtKeyPath
    );
  },

  getSelectedType() {
    const { value } = this.props;
    return value ? value.type : null;
  },

  onChangeType(newSelectedType) {
    if (!!value && (value.type === newSelectedType)) {
      return;
    }

    const info = {
      type: newSelectedType
    };

    this.props.onReplaceInfoAtKeyPath(info, []);
  },

  render() {
    const {
      types,
      value,
      typeSpecs,
      fieldSpecs,
      level,
      fieldComponent: Field,
      groupComponent,
      multipleComponent,
      onReplaceInfoAtKeyPath,
      ...rest,
    } = this.props;

    const selectedType = this.getSelectedType();
    let selectedTypeSpec = null;

    types.some(typeID => {
      if (typeID === selectedType) {
        selectedTypeSpec = typeSpecs[typeID];;
      }

      return false;
    });

    const typeChoices = types.map(typeID => ({
      id: typeID,
      title: typeSpecs[typeID].title,
    }));

    const typeChoiceField = (
      <Field key='typeChoice'
        type='choice'
        value={ selectedType }
        choices={ typeChoices }
        { ...rest }
        onChangeValue={ this.onChangeType }
      />
    );

    return (
      <Meadow key='fields'
        fields={ !!selectedTypeSpec ? selectedTypeSpec.fields : [] }
        values={ value }
        typeSpecs={ typeSpecs }
        fieldSpecs={ fieldSpecs }
        level={ level + 1 }
        typeChoiceField={ typeChoiceField }
        fieldComponent={ Field }
        groupComponent={ groupComponent }
        multipleComponent={ multipleComponent }
        onReplaceInfoAtKeyPath={ onReplaceInfoAtKeyPath }
      />
    );
  },
});
<commit_msg>Fix TypeChoice’s onChangeType<commit_after>import React, { PropTypes } from 'react';

import Meadow from './Meadow';

export default React.createClass({
  displayName: 'Meadow.TypeChoice',

  getDefaultProps() {
    return {
      types: [],
      onReplaceInfoAtKeyPath: null,
      tabIndex: 0,
    };
  },

  shouldComponentUpdate(nextProps, nextState) {
    const currentProps = this.props;

    return (
      nextProps.types !== currentProps.types ||
      nextProps.value != currentProps.value ||
      nextProps.typeSpecs !== currentProps.typeSpecs ||
      nextProps.fieldSpecs !== currentProps.fieldSpecs ||
      nextProps.fieldComponent !== currentProps.fieldComponent ||
      nextProps.onReplaceInfoAtKeyPath !== currentProps.onReplaceInfoAtKeyPath
    );
  },

  getSelectedType() {
    const { value } = this.props;
    return value ? value.type : null;
  },

  onChangeType(newSelectedType) {
    const { value } = this.props;

    if (!!value && (value.type === newSelectedType)) {
      return;
    }

    const info = {
      type: newSelectedType,
    };

    this.props.onReplaceInfoAtKeyPath(info, []);
  },

  render() {
    const {
      types,
      value,
      typeSpecs,
      fieldSpecs,
      level,
      fieldComponent: Field,
      groupComponent,
      multipleComponent,
      onReplaceInfoAtKeyPath,
      ...rest,
    } = this.props;

    const selectedType = this.getSelectedType();
    let selectedTypeSpec = null;

    types.some(typeID => {
      if (typeID === selectedType) {
        selectedTypeSpec = typeSpecs[typeID];;
      }

      return false;
    });

    const typeChoices = types.map(typeID => ({
      id: typeID,
      title: typeSpecs[typeID].title,
    }));

    const typeChoiceField = (
      <Field key='typeChoice'
        type='choice'
        value={ selectedType }
        choices={ typeChoices }
        { ...rest }
        onChangeValue={ this.onChangeType }
      />
    );

    return (
      <Meadow key='fields'
        fields={ !!selectedTypeSpec ? selectedTypeSpec.fields : [] }
        values={ value }
        typeSpecs={ typeSpecs }
        fieldSpecs={ fieldSpecs }
        level={ level + 1 }
        typeChoiceField={ typeChoiceField }
        fieldComponent={ Field }
        groupComponent={ groupComponent }
        multipleComponent={ multipleComponent }
        onReplaceInfoAtKeyPath={ onReplaceInfoAtKeyPath }
      />
    );
  },
});
<|endoftext|>


<commit_before>import CellRangeFilter from './CellRangeFilter'

export default class UnitConfig {
  /**
   * @param {string} symbol
   * @param {CellRange} range
   */
  constructor (symbol, range) {
    /** @type {string} */
    this.symbol = symbol

    /** @type {CellRange} */
    this.range = new CellRangeFilter(range, cell => cell.unit === null)
  }
}
<commit_msg>Refactoring: UnitConfig adds range filter only when necessary<commit_after>import NoUnitCellRangeFilter from './NoUnitCellRangeFilter'

export default class UnitConfig {
  /**
   * @param {string} symbol
   * @param {CellRange} range
   */
  constructor (symbol, range) {
    /** @type {string} */
    this.symbol = symbol

    /** @type {CellRange} */
    this.range = (range instanceof NoUnitCellRangeFilter) ? range : new NoUnitCellRangeFilter(range)
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import querystring from 'querystring';
import ReactSwipe from '../src/reactSwipe';

const query = querystring.parse(window.location.search.slice(1));

// generate slide panes
const numberOfSlides = parseInt(query.slidesNum, 10) || 20;
const paneNodes = Array.apply(null, Array(numberOfSlides)).map((_, i) => {
  return (

{i}

  );
});

// change Swipe.js options by query params
const startSlide = parseInt(query.startSlide, 10) || 0;
const swipeOptions = {
  startSlide: startSlide < paneNodes.length && startSlide >= 0 ? startSlide : 0,
  auto: parseInt(query.auto, 10) || 0,
  speed: parseInt(query.speed, 10) || 300,
  disableScroll: query.disableScroll === 'true',
  continuous: query.continuous === 'true',
  callback() {
    console.log('slide changed');
  },
  transitionEnd() {
    console.log('ended transition');
  }
};

class Page extends Component {
  next() {
    this.refs.reactSwipe.next();
  }

  prev() {
    this.refs.reactSwipe.prev();
  }

  render() {
    return (

ReactSwipe.js

Open this page from a mobile device (real or emulated).

You can pass Swipe.js options as query params.

        <ReactSwipe ref="reactSwipe" className="mySwipe" swipeOptions={swipeOptions}>
            {paneNodes}
        </ReactSwipe>

          <button type="button" onClick={::this.prev}>Prev</button>
          <button type="button" onClick={::this.next}>Next</button>

    );
  }
}

ReactDOM.render(
  <Page />,
  document.getElementById('app')
);
<commit_msg>Replace string ref with callback ref<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import querystring from 'querystring';
import ReactSwipe from '../src/reactSwipe';

const query = querystring.parse(window.location.search.slice(1));

// generate slide panes
const numberOfSlides = parseInt(query.slidesNum, 10) || 20;
const paneNodes = Array.apply(null, Array(numberOfSlides)).map((_, i) => {
  return (

{i}

  );
});

// change Swipe.js options by query params
const startSlide = parseInt(query.startSlide, 10) || 0;
const swipeOptions = {
  startSlide: startSlide < paneNodes.length && startSlide >= 0 ? startSlide : 0,
  auto: parseInt(query.auto, 10) || 0,
  speed: parseInt(query.speed, 10) || 300,
  disableScroll: query.disableScroll === 'true',
  continuous: query.continuous === 'true',
  callback() {
    console.log('slide changed');
  },
  transitionEnd() {
    console.log('ended transition');
  }
};

class Page extends Component {
  next() {
    this.reactSwipe.next();
  }

  prev() {
    this.reactSwipe.prev();
  }

  render() {
    return (

ReactSwipe.js

Open this page from a mobile device (real or emulated).

You can pass Swipe.js options as query params.

        <ReactSwipe ref={reactSwipe => this.reactSwipe = reactSwipe} className="mySwipe" swipeOptions={swipeOptions}>
            {paneNodes}
        </ReactSwipe>

          <button type="button" onClick={::this.prev}>Prev</button>
          <button type="button" onClick={::this.next}>Next</button>

    );
  }
}

ReactDOM.render(
  <Page />,
  document.getElementById('app')
);
<|endoftext|>


<commit_before>
var Fs = require("fs");
var Path = require("path");
var Stream = require("stream");
var Resolve = require("resolve");
var Browserify = require("browserify");
var Icon = require("../util/icon.js");
var Collect = require("../util/collect.js");
var Assume = require("../util/assume.js");
var Bind = require("../util/bind.js");

module.exports = function (options) {
  var transpiles = Collect(options.transpile, /\.js$/);
  var mains = Collect(options.main, /\.js$/);
  var browserify = (function (readable) {
    readable.push(Bind(Fs.readFileSync(__dirname+"/template.js", "utf8"), {
      "@MAINS": JSON.stringify(mains),
      "@TRANSPILES": JSON.stringify(transpiles)
    }));
    readable.push(null);
    return Browserify(readable, {basedir:__dirname});
  } (new Stream.Readable()));
  options.transpile && (function (basedir) {
    for (var key in transpiles)
      transpiles[key].replace(/[^a-zA-Z_$]require\s*\(\s*((\"[^"]*\")|(\'[^']*\'))\s*\)/g, function (_, dependency) {
        // Tried to remove the dependency with Resolve without success:
        // Source: https://github.com/nodejs/node/blob/v5.10.0/lib/module.js
        //         https://github.com/nodejs/node/blob/v5.10.0/lib/internal/module.js
        // require("module")._resolveFilename(module, {paths:[basedir]})
        browserify.require(
          Resolve.sync(JSON.parse(dependency), {basedir:basedir}),
          {expose:JSON.parse(dependency)});
      });
  } (/\.js$/.test(options.transpile) ? Path.dirname(options.transpile) : options.transpile));
  browserify.bundle(Assume(function (bundle) {
    var output = Fs.readFileSync(__dirname+"/template.html", "utf8")
      .replace("@ICON", Icon)
      .replace("@TITLE", "Demo")
      .replace("@BUNDLE", function () { return bundle.toString("utf8") });
    options.out ? Fs.writeFileSync(options.out, output, "utf8") : process.stdout.write(output);
  }));
};
<commit_msg>use eval instead of JSON.parse to handle single quoted strings<commit_after>
var Fs = require("fs");
var Path = require("path");
var Stream = require("stream");
var Resolve = require("resolve");
var Browserify = require("browserify");
var Icon = require("../util/icon.js");
var Collect = require("../util/collect.js");
var Assume = require("../util/assume.js");
var Bind = require("../util/bind.js");

module.exports = function (options) {
  var transpiles = Collect(options.transpile, /\.js$/);
  var mains = Collect(options.main, /\.js$/);
  var browserify = (function (readable) {
    readable.push(Bind(Fs.readFileSync(__dirname+"/template.js", "utf8"), {
      "@MAINS": JSON.stringify(mains),
      "@TRANSPILES": JSON.stringify(transpiles)
    }));
    readable.push(null);
    return Browserify(readable, {basedir:__dirname});
  } (new Stream.Readable()));
  options.transpile && (function (basedir) {
    for (var key in transpiles)
      transpiles[key].replace(/[^a-zA-Z_$]require\s*\(\s*((\"[^"]*\")|(\'[^']*\'))\s*\)/g, function (_, dependency) {
        // Tried to remove the dependency with Resolve without success:
        // Source: https://github.com/nodejs/node/blob/v5.10.0/lib/module.js
        //         https://github.com/nodejs/node/blob/v5.10.0/lib/internal/module.js
        // require("module")._resolveFilename(module, {paths:[basedir]})
        browserify.require(
          Resolve.sync(global.eval(dependency), {basedir:basedir}), // use eval instead of JSON.parse to handle single quoted strings
          {expose:JSON.parse(dependency)});
      });
  } (/\.js$/.test(options.transpile) ? Path.dirname(options.transpile) : options.transpile));
  browserify.bundle(Assume(function (bundle) {
    var output = Fs.readFileSync(__dirname+"/template.html", "utf8")
      .replace("@ICON", Icon)
      .replace("@TITLE", "Demo")
      .replace("@BUNDLE", function () { return bundle.toString("utf8") });
    options.out ? Fs.writeFileSync(options.out, output, "utf8") : process.stdout.write(output);
  }));
};
<|endoftext|>


<commit_before>var path = require('path')
var changelogParser = require('changelog-parser')
var exec = require('shelljs').exec

function getDefaults (workPath, callback) {
  var pkg = require(path.resolve(workPath, 'package.json'))

  if (!pkg.hasOwnProperty('repository')) {
    return callback(new Error('You must define a repository for your module => https://docs.npmjs.com/files/package.json#repository'))
  }

  var commit = getTargetCommitish()
  var repoPath = pkg.repository.url.split('github.com')[1].slice(1).split('/')
  var owner = repoPath[0]
  var repo = repoPath[1].split('.git')[0]
  var logPath = path.resolve(workPath, 'CHANGELOG.md')

  changelogParser(logPath, function (err, result) {
    if (err) return callback(err)
    var log = result.versions.find(function (release) { return release.version !== null })

    if (log.version !== pkg.version) {
      var errStr = 'CHANGELOG.md out of sync with package.json '
      errStr += '(' + (log.version || log.title) + ' !== ' + pkg.version + ')'
      return callback(new Error(errStr))
    }

    var version = pkg.version ? 'v' + pkg.version : null

    callback(null, {
      assets: false,
      owner: owner,
      repo: repo,
      dryRun: false,
      workpath: process.cwd(),
      body: log.body,
      prerelease: false,
      draft: false,
      target_commitish: commit,
      tag_name: version,
      name: version
    })
  })
}

function getTargetCommitish () {
  var commit = exec('git rev-parse HEAD', { silent: true }).output.split('\n')[0]
  if (commit.indexOf('fatal') === -1) return commit
  return 'master'
}

module.exports = getDefaults
module.exports.getTargetCommitish = getTargetCommitish
<commit_msg>Use .filter to support ES5 engines<commit_after>var path = require('path')
var changelogParser = require('changelog-parser')
var exec = require('shelljs').exec

function getDefaults (workPath, callback) {
  var pkg = require(path.resolve(workPath, 'package.json'))

  if (!pkg.hasOwnProperty('repository')) {
    return callback(new Error('You must define a repository for your module => https://docs.npmjs.com/files/package.json#repository'))
  }

  var commit = getTargetCommitish()
  var repoPath = pkg.repository.url.split('github.com')[1].slice(1).split('/')
  var owner = repoPath[0]
  var repo = repoPath[1].split('.git')[0]
  var logPath = path.resolve(workPath, 'CHANGELOG.md')

  changelogParser(logPath, function (err, result) {
    if (err) return callback(err)
    var log = result.versions.filter(function (release) { return release.version !== null })[0]

    if (log.version !== pkg.version) {
      var errStr = 'CHANGELOG.md out of sync with package.json '
      errStr += '(' + (log.version || log.title) + ' !== ' + pkg.version + ')'
      return callback(new Error(errStr))
    }

    var version = pkg.version ? 'v' + pkg.version : null

    callback(null, {
      assets: false,
      owner: owner,
      repo: repo,
      dryRun: false,
      workpath: process.cwd(),
      body: log.body,
      prerelease: false,
      draft: false,
      target_commitish: commit,
      tag_name: version,
      name: version
    })
  })
}

function getTargetCommitish () {
  var commit = exec('git rev-parse HEAD', { silent: true }).output.split('\n')[0]
  if (commit.indexOf('fatal') === -1) return commit
  return 'master'
}

module.exports = getDefaults
module.exports.getTargetCommitish = getTargetCommitish
<|endoftext|>