<commit_before>import dom from 'vd'

export default function splash ({ path, name, org, coc, logo, active, total, channels, large, iframe, gcaptcha_sitekey }){
  let div = dom('.splash',
    !iframe && dom('.logos',
      logo && dom('.logo.org'),
      dom('.logo.slack')
    ),
    dom('p',
      'Λάβετε πρόσκληση για την ', dom('b', name),
      // mention single single-channel inline
      channels && channels.length === 1 && dom('span', ' #', channels[0]),
      ' στο Slack.'
    ),
    dom('p.status',
      active
        ? [
          dom('b.active', active), ' χρήστες online από τους ',
          dom('b.total', total), ' εγγεγραμμένους.'
        ]
        : [dom('b.total', total), ' χρήστες έχουν κάνει εγγραφή ως τώρα.']
    ),
    dom('form id=invite',
      channels && (
        channels.length > 1
          // channel selection when there are multiple
          ? dom('select.form-item name=channel',
              channels.map(channel => {
                return dom('option', { value: channel, text: channel })
              })
            )
          // otherwise a fixed channel
          : dom('input type=hidden name=channel', { value: channels[0] })
      ),
      dom('input.form-item type=email name=email placeholder=you@yourdomain.com '
        + (!iframe ? 'autofocus' : '')),
      dom('br'),
      dom(`div class="g-recaptcha" data-sitekey="${gcaptcha_sitekey}"`),
      coc && dom('.coc',
        dom('label',
          dom('input type=checkbox name=coc value=1'),
          'Συμφωνώ με τους ',
          dom('a', { href: coc, target: '_blank' }, 'όρους χρήσης'),
          '.'
        )
      ),
      dom('button.loading', 'Στειλτε μου μια προσκληση')
    ),
    dom('p.signin',
      'ή ',
      dom(`a href=https://${org}.slack.com target=_top`, 'κάντε είσοδο'),
      '.'
    ),
    !iframe && dom('footer',
      'powered by ',
      dom('a href=http://rauchg.com/slackin target=_blank', 'slackin')
    ),
    style({ logo, active, large, iframe }),
    // xxx: single build
    dom('script', `
      data = {};
      data.path = ${JSON.stringify(path)};
    `),
    dom('script src=https://cdn.socket.io/socket.io-1.4.4.js'),
    dom(`script src=${path}assets/superagent.js`),
    dom(`script src=${path}assets/client.js`)
  )
  return div
}

const pink = '#E01563'

function style ({ logo, active, large, iframe } = {}){
  var css = dom.style()
  css.add('html', { 'font-size': large ? '14px' : '10px' })

  css.add('.splash', {
    'width': iframe ? '25rem' : '30rem',
    'margin': iframe ? '0' : '20rem auto',
    'text-align': 'center',
    'font-family': '"Helvetica Neue", Helvetica, Arial'
  })

  if (iframe) {
    css.add('body, html', {
      'margin': '0',
      'padding': '0',
      'background': '#FAFAFA',
      'overflow': 'hidden' // ff
    })

    css.add('.splash', {
      'box-sizing': 'border-box',
      'padding': '1rem'
    })
  }

  if (!iframe) {
    css
    .media('(max-width: 50rem)')
    .add('.splash', {
      'margin-top': '10rem'
    })
  }

  css.add('.head', {
    'margin-bottom': '4rem'
  })

  css.add('.logos', {
    'position': 'relative',
    'margin-bottom': '4rem'
  })

  if (!iframe) {
    css.add('.logo', {
      'width': '4.8rem',
      'height': '4.8rem',
      'display': 'inline-block',
      'background-size': 'cover'
    })

    css.add('.logo.slack', {
      'background-image': 'url(assets/slack.svg)'
    })

    if (logo) {
      let pw = 1 // '+' width in rem
      let lp = 3 // logos separation in rem

      css.add('.logo.org::after', {
        'position': 'absolute',
        'display': 'block',
        'content': '"+"',
        'top': '1.5rem',
        'left': '0',
        'width': '30rem',
        'text-align': 'center',
        'color': '#D6D6D6',
        'font-size': '1.5rem', // can't use rem in font shorthand IE9-10
              // http://codersblock.com/blog/font-shorthand-bug-in-ie10/
        'font-family': 'Helvetica Neue'
      })

      css.add('.logo.org', {
        'background-image': `url(${logo})`,
        'margin-right': `${lp + pw + lp}rem`
      })
    }
  }

  css.add('.coc', {
    'font-size': '1.2rem',
    padding: '1.5rem 0 .5rem',
    color: '#666'
  })

  if (iframe) {
    css.add('.coc', {
      'font-size': '1.1rem',
      'padding-top': '1rem'
    })

    css.add('.coc input', {
      position: 'relative',
      top: '-.2rem'
    })
  }

  css.add('.coc label', {
    cursor: 'pointer'
  })

  css.add('.coc input', {
    'appearance': 'none',
    '-webkit-appearance': 'none',
    border: 'none',
    'vertical-align': 'middle',
    margin: '0 .5rem 0 0'
  })

  css.add('.coc input::after', {
    content: '""',
    display: 'inline-block',
    width: '1.5rem',
    height: '1.5rem',
    'vertical-align': 'middle',
    background: 'url(/assets/checkbox.svg)',
    cursor: 'pointer'
  })

  css.add('.coc input:checked::after', {
    'background-position': 'right'
  })

  css.add('.coc a', {
    color: '#666'
  })

  css.add('.coc a:hover', {
    'background-color': '#666',
    'text-decoration': 'none',
    color: '#fff'
  })

  css.add('p', {
    'font-size': iframe ? '1.2rem' : '1.5rem',
    'margin': iframe ? '0 0 .5rem' : '.5rem 0'
  })

  if (iframe) {
    css.add('p.status', {
      'font-size': '1.1rem'
    })
  }

  css.add('select', {
    'background': 'none'
  })

  css.add('button, .form-item', {
    'font-size': '1.2rem',
    'margin-top': iframe ? '.5rem' : '1rem',
    'vertical-align': 'middle',
    'display': 'block',
    'text-align': 'center',
    'box-sizing': 'border-box',
    'width': '100%',
    'padding': '.9rem'
  })

  css.add('button', {
    'color': '#fff',
    'font-weight': 'bold',
    'border-width': 0,
    'background': pink,
    'text-transform': 'uppercase',
    'cursor': 'pointer',
    'appearence': 'none',
    '-webkit-appearence': 'none',
    'outline': '0',
    'transition': 'background-color 150ms ease-in, color 150ms ease-in'
  })

  css.add('button.loading', {
    'pointer-events': 'none'
  })

  css.add('button:disabled', {
    'color': '#9B9B9B',
    'background-color': '#D6D6D6',
    'cursor': 'default',
    'pointer-events': 'none'
  })

  css.add('button.error', {
    'background-color': '#F4001E',
    'text-transform': 'none'
  })

  css.add('button.success:disabled', {
    'color': '#fff',
    'background-color': '#68C200'
  })

  css.add('button:not(.disabled):active', {
    'background-color': '#7A002F'
  })

  css.add('b', {
    'transition': 'transform 150ms ease-in'
  })

  css.add('b.grow', {
    'transform': 'scale(1.3)'
  })

  css.add('form', {
    'margin-top': iframe ? '1rem' : '2rem',
    'margin-bottom': '0'
  })

  css.add('input', {
    'color': '#9B9B9B',
    'border': '.1rem solid #D6D6D6'
  })

  if (iframe) {
    css.add('button, .form-item', {
      'height': '2.8rem',
      'line-height': '2.8rem',
      'padding': 0,
      'font-size': '1.1rem'
    })
  }

  css.add('input:focus', {
    'color': '#666',
    'border-color': '#999',
    'outline': '0'
  })

  if (active) {
    css.add('.active', {
      'color': pink
    })
  }

  css.add('p.signin', {
    'padding': '1rem 0 1rem',
    'font-size': '1.1rem'
  })

  css.add('p.signin a', {
    'color': pink,
    'text-decoration': 'none'
  })

  css.add('p.signin a:hover', {
    'background-color': '#E01563',
    color: '#fff'
  })

  if (!iframe) {
    css.add('footer', {
      'color': '#D6D6D6',
      'font-size': '1.1rem',
      'margin': '20rem auto 0',
      'width': '30rem',
      'text-align': 'center'
    })

    css.add('footer a', {
      'color': '#9B9B9B',
      'text-decoration': 'none',
      'border-bottom': '.1rem solid #9B9B9B'
    })

    css.add('footer a:hover', {
      'color': '#fff',
      'background-color': '#9B9B9B'
    })
  }

  return css
}
<commit_msg>Update strings in splash.js<commit_after>import dom from 'vd'

export default function splash ({ path, name, org, coc, logo, active, total, channels, large, iframe, gcaptcha_sitekey }){
  let div = dom('.splash',
    !iframe && dom('.logos',
      logo && dom('.logo.org'),
      dom('.logo.slack')
    ),
    dom('p',
      'Λάβετε πρόσκληση για την ', dom('b', name),
      // mention single single-channel inline
      channels && channels.length === 1 && dom('span', ' #', channels[0]),
      ' στο Slack.'
    ),
    dom('p.status',
      active
        ? [
          dom('b.active', active), ' χρήστες online από τους ',
          dom('b.total', total), ' εγγεγραμμένους.'
        ]
        : [dom('b.total', total), ' χρήστες έχουν κάνει εγγραφή ως τώρα.']
    ),
    dom('form id=invite',
      channels && (
        channels.length > 1
          // channel selection when there are multiple
          ? dom('select.form-item name=channel',
              channels.map(channel => {
                return dom('option', { value: channel, text: channel })
              })
            )
          // otherwise a fixed channel
          : dom('input type=hidden name=channel', { value: channels[0] })
      ),
      dom('input.form-item type=email name=email placeholder=you@yourdomain.com '
        + (!iframe ? 'autofocus' : '')),
      dom('br'),
      dom(`div class="g-recaptcha" data-sitekey="${gcaptcha_sitekey}"`),
      coc && dom('.coc',
        dom('label',
          dom('input type=checkbox name=coc value=1'),
          'Συμφωνώ με τους ',
          dom('a', { href: coc, target: '_blank' }, 'όρους χρήσης'),
          '.'
        )
      ),
      dom('button.loading', 'Στειλτε μου προσκληση')
    ),
    dom('p.signin',
      'ή ',
      dom(`a href=https://${org}.slack.com target=_top`, 'είσοδος'),
      '.'
    ),
    !iframe && dom('footer',
      'powered by ',
      dom('a href=http://rauchg.com/slackin target=_blank', 'slackin')
    ),
    style({ logo, active, large, iframe }),
    // xxx: single build
    dom('script', `
      data = {};
      data.path = ${JSON.stringify(path)};
    `),
    dom('script src=https://cdn.socket.io/socket.io-1.4.4.js'),
    dom(`script src=${path}assets/superagent.js`),
    dom(`script src=${path}assets/client.js`)
  )
  return div
}

const pink = '#E01563'

function style ({ logo, active, large, iframe } = {}){
  var css = dom.style()
  css.add('html', { 'font-size': large ? '14px' : '10px' })

  css.add('.splash', {
    'width': iframe ? '25rem' : '30rem',
    'margin': iframe ? '0' : '20rem auto',
    'text-align': 'center',
    'font-family': '"Helvetica Neue", Helvetica, Arial'
  })

  if (iframe) {
    css.add('body, html', {
      'margin': '0',
      'padding': '0',
      'background': '#FAFAFA',
      'overflow': 'hidden' // ff
    })

    css.add('.splash', {
      'box-sizing': 'border-box',
      'padding': '1rem'
    })
  }

  if (!iframe) {
    css
    .media('(max-width: 50rem)')
    .add('.splash', {
      'margin-top': '10rem'
    })
  }

  css.add('.head', {
    'margin-bottom': '4rem'
  })

  css.add('.logos', {
    'position': 'relative',
    'margin-bottom': '4rem'
  })

  if (!iframe) {
    css.add('.logo', {
      'width': '4.8rem',
      'height': '4.8rem',
      'display': 'inline-block',
      'background-size': 'cover'
    })

    css.add('.logo.slack', {
      'background-image': 'url(assets/slack.svg)'
    })

    if (logo) {
      let pw = 1 // '+' width in rem
      let lp = 3 // logos separation in rem

      css.add('.logo.org::after', {
        'position': 'absolute',
        'display': 'block',
        'content': '"+"',
        'top': '1.5rem',
        'left': '0',
        'width': '30rem',
        'text-align': 'center',
        'color': '#D6D6D6',
        'font-size': '1.5rem', // can't use rem in font shorthand IE9-10
              // http://codersblock.com/blog/font-shorthand-bug-in-ie10/
        'font-family': 'Helvetica Neue'
      })

      css.add('.logo.org', {
        'background-image': `url(${logo})`,
        'margin-right': `${lp + pw + lp}rem`
      })
    }
  }

  css.add('.coc', {
    'font-size': '1.2rem',
    padding: '1.5rem 0 .5rem',
    color: '#666'
  })

  if (iframe) {
    css.add('.coc', {
      'font-size': '1.1rem',
      'padding-top': '1rem'
    })

    css.add('.coc input', {
      position: 'relative',
      top: '-.2rem'
    })
  }

  css.add('.coc label', {
    cursor: 'pointer'
  })

  css.add('.coc input', {
    'appearance': 'none',
    '-webkit-appearance': 'none',
    border: 'none',
    'vertical-align': 'middle',
    margin: '0 .5rem 0 0'
  })

  css.add('.coc input::after', {
    content: '""',
    display: 'inline-block',
    width: '1.5rem',
    height: '1.5rem',
    'vertical-align': 'middle',
    background: 'url(/assets/checkbox.svg)',
    cursor: 'pointer'
  })

  css.add('.coc input:checked::after', {
    'background-position': 'right'
  })

  css.add('.coc a', {
    color: '#666'
  })

  css.add('.coc a:hover', {
    'background-color': '#666',
    'text-decoration': 'none',
    color: '#fff'
  })

  css.add('p', {
    'font-size': iframe ? '1.2rem' : '1.5rem',
    'margin': iframe ? '0 0 .5rem' : '.5rem 0'
  })

  if (iframe) {
    css.add('p.status', {
      'font-size': '1.1rem'
    })
  }

  css.add('select', {
    'background': 'none'
  })

  css.add('button, .form-item', {
    'font-size': '1.2rem',
    'margin-top': iframe ? '.5rem' : '1rem',
    'vertical-align': 'middle',
    'display': 'block',
    'text-align': 'center',
    'box-sizing': 'border-box',
    'width': '100%',
    'padding': '.9rem'
  })

  css.add('button', {
    'color': '#fff',
    'font-weight': 'bold',
    'border-width': 0,
    'background': pink,
    'text-transform': 'uppercase',
    'cursor': 'pointer',
    'appearence': 'none',
    '-webkit-appearence': 'none',
    'outline': '0',
    'transition': 'background-color 150ms ease-in, color 150ms ease-in'
  })

  css.add('button.loading', {
    'pointer-events': 'none'
  })

  css.add('button:disabled', {
    'color': '#9B9B9B',
    'background-color': '#D6D6D6',
    'cursor': 'default',
    'pointer-events': 'none'
  })

  css.add('button.error', {
    'background-color': '#F4001E',
    'text-transform': 'none'
  })

  css.add('button.success:disabled', {
    'color': '#fff',
    'background-color': '#68C200'
  })

  css.add('button:not(.disabled):active', {
    'background-color': '#7A002F'
  })

  css.add('b', {
    'transition': 'transform 150ms ease-in'
  })

  css.add('b.grow', {
    'transform': 'scale(1.3)'
  })

  css.add('form', {
    'margin-top': iframe ? '1rem' : '2rem',
    'margin-bottom': '0'
  })

  css.add('input', {
    'color': '#9B9B9B',
    'border': '.1rem solid #D6D6D6'
  })

  if (iframe) {
    css.add('button, .form-item', {
      'height': '2.8rem',
      'line-height': '2.8rem',
      'padding': 0,
      'font-size': '1.1rem'
    })
  }

  css.add('input:focus', {
    'color': '#666',
    'border-color': '#999',
    'outline': '0'
  })

  if (active) {
    css.add('.active', {
      'color': pink
    })
  }

  css.add('p.signin', {
    'padding': '1rem 0 1rem',
    'font-size': '1.1rem'
  })

  css.add('p.signin a', {
    'color': pink,
    'text-decoration': 'none'
  })

  css.add('p.signin a:hover', {
    'background-color': '#E01563',
    color: '#fff'
  })

  if (!iframe) {
    css.add('footer', {
      'color': '#D6D6D6',
      'font-size': '1.1rem',
      'margin': '20rem auto 0',
      'width': '30rem',
      'text-align': 'center'
    })

    css.add('footer a', {
      'color': '#9B9B9B',
      'text-decoration': 'none',
      'border-bottom': '.1rem solid #9B9B9B'
    })

    css.add('footer a:hover', {
      'color': '#fff',
      'background-color': '#9B9B9B'
    })
  }

  return css
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule TouchableOpacity
 * @noflow
 */
'use strict';

// Note (avik): add @flow when Flow supports spread properties in propTypes

var Animated = require('Animated');
var Easing = require('Easing');
var NativeMethodsMixin = require('NativeMethodsMixin');
var React = require('React');
var PropTypes = require('prop-types');
var TimerMixin = require('react-timer-mixin');
var Touchable = require('Touchable');
var TouchableWithoutFeedback = require('TouchableWithoutFeedback');

var createReactClass = require('create-react-class');
var ensurePositiveDelayProps = require('ensurePositiveDelayProps');
var flattenStyle = require('flattenStyle');

type Event = Object;

var PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};

/**
 * A wrapper for making views respond properly to touches.
 * On press down, the opacity of the wrapped view is decreased, dimming it.
 *
 * Opacity is controlled by wrapping the children in an Animated.View, which is
 * added to the view hiearchy.  Be aware that this can affect layout.
 *
 * Example:
 *
 * ```
 * renderButton: function() {
 *   return (
 *     <TouchableOpacity onPress={this._onPressButton}>
 *       <Image
 *         style={styles.button}
 *         source={require('./myButton.png')}
 *       />
 *     </TouchableOpacity>
 *   );
 * },
 * ```
 */
var TouchableOpacity = createReactClass({
  displayName: 'TouchableOpacity',
  mixins: [TimerMixin, Touchable.Mixin, NativeMethodsMixin],

  propTypes: {
    ...TouchableWithoutFeedback.propTypes,
    /**
     * Determines what the opacity of the wrapped view should be when touch is
     * active. Defaults to 0.2.
     */
    activeOpacity: PropTypes.number,
    /**
     * Apple TV parallax effects
     */
    tvParallaxProperties: PropTypes.object,
  },

  getDefaultProps: function() {
    return {
      activeOpacity: 0.2,
    };
  },

  getInitialState: function() {
    return {
      ...this.touchableGetInitialState(),
      anim: new Animated.Value(this._getChildStyleOpacityWithDefault()),
    };
  },

  componentDidMount: function() {
    ensurePositiveDelayProps(this.props);
  },

  componentWillReceiveProps: function(nextProps) {
    ensurePositiveDelayProps(nextProps);
  },

  /**
   * Animate the touchable to a new opacity.
   */
  setOpacityTo: function(value: number, duration: number) {
    Animated.timing(
      this.state.anim,
      {
        toValue: value,
        duration: duration,
        easing: Easing.inOut(Easing.quad),
        useNativeDriver: true,
      }
    ).start();
  },

  /**
   * `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
   * defined on your component.
   */
  touchableHandleActivePressIn: function(e: Event) {
    if (e.dispatchConfig.registrationName === 'onResponderGrant') {
      this._opacityActive(0);
    } else {
      this._opacityActive(150);
    }
    this.props.onPressIn && this.props.onPressIn(e);
  },

  touchableHandleActivePressOut: function(e: Event) {
    this._opacityInactive(250);
    this.props.onPressOut && this.props.onPressOut(e);
  },

  touchableHandlePress: function(e: Event) {
    this.props.onPress && this.props.onPress(e);
  },

  touchableHandleLongPress: function(e: Event) {
    this.props.onLongPress && this.props.onLongPress(e);
  },

  touchableGetPressRectOffset: function() {
    return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
  },

  touchableGetHitSlop: function() {
    return this.props.hitSlop;
  },

  touchableGetHighlightDelayMS: function() {
    return this.props.delayPressIn || 0;
  },

  touchableGetLongPressDelayMS: function() {
    return this.props.delayLongPress === 0 ? 0 :
      this.props.delayLongPress || 500;
  },

  touchableGetPressOutDelayMS: function() {
    return this.props.delayPressOut;
  },

  _opacityActive: function(duration: number) {
    this.setOpacityTo(this.props.activeOpacity, duration);
  },

  _opacityInactive: function(duration: number) {
    this.setOpacityTo(
      this._getChildStyleOpacityWithDefault(),
      duration
    );
  },

  _getChildStyleOpacityWithDefault: function() {
   var childStyle = flattenStyle(this.props.style) || {};
   return childStyle.opacity == undefined ? 1 : childStyle.opacity;
 },

  render: function() {
    return (
      <Animated.View
        accessible={this.props.accessible !== false}
        accessibilityLabel={this.props.accessibilityLabel}
        accessibilityComponentType={this.props.accessibilityComponentType}
        accessibilityTraits={this.props.accessibilityTraits}
        style={[this.props.style, {opacity: this.state.anim}]}
        nativeID={this.props.nativeID}
        testID={this.props.testID}
        onLayout={this.props.onLayout}
        isTVSelectable={true}
        tvParallaxProperties={this.props.tvParallaxProperties}
        hitSlop={this.props.hitSlop}
        onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
        onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest}
        onResponderGrant={this.touchableHandleResponderGrant}
        onResponderMove={this.touchableHandleResponderMove}
        onResponderRelease={this.touchableHandleResponderRelease}
        onResponderTerminate={this.touchableHandleResponderTerminate}>
        {this.props.children}
        {Touchable.renderDebugView({color: 'cyan', hitSlop: this.props.hitSlop})}
      </Animated.View>
    );
  },
});

module.exports = TouchableOpacity;
<commit_msg>Add Example for TouchableOpacity.js<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule TouchableOpacity
 * @noflow
 */
'use strict';

// Note (avik): add @flow when Flow supports spread properties in propTypes

var Animated = require('Animated');
var Easing = require('Easing');
var NativeMethodsMixin = require('NativeMethodsMixin');
var React = require('React');
var PropTypes = require('prop-types');
var TimerMixin = require('react-timer-mixin');
var Touchable = require('Touchable');
var TouchableWithoutFeedback = require('TouchableWithoutFeedback');

var createReactClass = require('create-react-class');
var ensurePositiveDelayProps = require('ensurePositiveDelayProps');
var flattenStyle = require('flattenStyle');

type Event = Object;

var PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};

/**
 * A wrapper for making views respond properly to touches.
 * On press down, the opacity of the wrapped view is decreased, dimming it.
 *
 * Opacity is controlled by wrapping the children in an Animated.View, which is
 * added to the view hiearchy.  Be aware that this can affect layout.
 *
 * Example:
 *
 * ```
 * renderButton: function() {
 *   return (
 *     <TouchableOpacity onPress={this._onPressButton}>
 *       <Image
 *         style={styles.button}
 *         source={require('./myButton.png')}
 *       />
 *     </TouchableOpacity>
 *   );
 * },
 * ```
 * ### Example
 *
 * ```ReactNativeWebPlayer
 * import React, { Component } from 'react'
 * import {
 *   AppRegistry,
 *   StyleSheet,
 *   TouchableOpacity,
 *   Text,
 *   View,
 * } from 'react-native'
 *
 * class App extends Component {
 * constructor(props) {
 *  super(props)
 *  this.state = { count: 0 }
 * }
 *
 * onPress = () => {
 *   this.setState({
 *     count: this.state.count+1
 *   })
 * }
 *
 *  render() {
 *     return (
 *       <View style={styles.container}>
 *         <TouchableOpacity
 *          style={styles.button}
 *          onPress={this.onPress}
 *        >
 *          <Text> Touch Here </Text>
 *        </TouchableOpacity>
 *        <View style={[styles.countContainer]}>
 *          <Text style={[styles.countText]}>
 *             { this.state.count !== 0 ? this.state.count: null}
 *           </Text>
 *         </View>
 *       </View>
 *     )
 *   }
 * }
 *
 * const styles = StyleSheet.create({
 *   container: {
 *     flex: 1,
 *     justifyContent: 'center',
 *     paddingHorizontal: 10
 *   },
 *   button: {
 *     alignItems: 'center',
 *     backgroundColor: '#DDDDDD',
 *     padding: 10
 *   },
 *   countContainer: {
 *     alignItems: 'center',
 *     padding: 10
 *   },
 *   countText: {
 *     color: '#FF00FF'
 *   }
 * })
 *
 * AppRegistry.registerComponent('App', () => App)
 * ```
 *
 */
var TouchableOpacity = createReactClass({
  displayName: 'TouchableOpacity',
  mixins: [TimerMixin, Touchable.Mixin, NativeMethodsMixin],

  propTypes: {
    ...TouchableWithoutFeedback.propTypes,
    /**
     * Determines what the opacity of the wrapped view should be when touch is
     * active. Defaults to 0.2.
     */
    activeOpacity: PropTypes.number,
    /**
     * Apple TV parallax effects
     */
    tvParallaxProperties: PropTypes.object,
  },

  getDefaultProps: function() {
    return {
      activeOpacity: 0.2,
    };
  },

  getInitialState: function() {
    return {
      ...this.touchableGetInitialState(),
      anim: new Animated.Value(this._getChildStyleOpacityWithDefault()),
    };
  },

  componentDidMount: function() {
    ensurePositiveDelayProps(this.props);
  },

  componentWillReceiveProps: function(nextProps) {
    ensurePositiveDelayProps(nextProps);
  },

  /**
   * Animate the touchable to a new opacity.
   */
  setOpacityTo: function(value: number, duration: number) {
    Animated.timing(
      this.state.anim,
      {
        toValue: value,
        duration: duration,
        easing: Easing.inOut(Easing.quad),
        useNativeDriver: true,
      }
    ).start();
  },

  /**
   * `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
   * defined on your component.
   */
  touchableHandleActivePressIn: function(e: Event) {
    if (e.dispatchConfig.registrationName === 'onResponderGrant') {
      this._opacityActive(0);
    } else {
      this._opacityActive(150);
    }
    this.props.onPressIn && this.props.onPressIn(e);
  },

  touchableHandleActivePressOut: function(e: Event) {
    this._opacityInactive(250);
    this.props.onPressOut && this.props.onPressOut(e);
  },

  touchableHandlePress: function(e: Event) {
    this.props.onPress && this.props.onPress(e);
  },

  touchableHandleLongPress: function(e: Event) {
    this.props.onLongPress && this.props.onLongPress(e);
  },

  touchableGetPressRectOffset: function() {
    return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
  },

  touchableGetHitSlop: function() {
    return this.props.hitSlop;
  },

  touchableGetHighlightDelayMS: function() {
    return this.props.delayPressIn || 0;
  },

  touchableGetLongPressDelayMS: function() {
    return this.props.delayLongPress === 0 ? 0 :
      this.props.delayLongPress || 500;
  },

  touchableGetPressOutDelayMS: function() {
    return this.props.delayPressOut;
  },

  _opacityActive: function(duration: number) {
    this.setOpacityTo(this.props.activeOpacity, duration);
  },

  _opacityInactive: function(duration: number) {
    this.setOpacityTo(
      this._getChildStyleOpacityWithDefault(),
      duration
    );
  },

  _getChildStyleOpacityWithDefault: function() {
   var childStyle = flattenStyle(this.props.style) || {};
   return childStyle.opacity == undefined ? 1 : childStyle.opacity;
 },

  render: function() {
    return (
      <Animated.View
        accessible={this.props.accessible !== false}
        accessibilityLabel={this.props.accessibilityLabel}
        accessibilityComponentType={this.props.accessibilityComponentType}
        accessibilityTraits={this.props.accessibilityTraits}
        style={[this.props.style, {opacity: this.state.anim}]}
        nativeID={this.props.nativeID}
        testID={this.props.testID}
        onLayout={this.props.onLayout}
        isTVSelectable={true}
        tvParallaxProperties={this.props.tvParallaxProperties}
        hitSlop={this.props.hitSlop}
        onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
        onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest}
        onResponderGrant={this.touchableHandleResponderGrant}
        onResponderMove={this.touchableHandleResponderMove}
        onResponderRelease={this.touchableHandleResponderRelease}
        onResponderTerminate={this.touchableHandleResponderTerminate}>
        {this.props.children}
        {Touchable.renderDebugView({color: 'cyan', hitSlop: this.props.hitSlop})}
      </Animated.View>
    );
  },
});

module.exports = TouchableOpacity;
<|endoftext|>


<commit_before>angular.module(PKG.name + '.feature.adapters')
  .controller('CanvasController', function (myAdapterApi, MyPlumbService, $bootstrapModal, $state, $scope, $alert, myHelpers, CanvasFactory, MyPlumbFactory, $modalStack, $timeout, ModalConfirm) {
    this.nodes = [];
    this.reloadDAG = false;
    if ($scope.AdapterCreateController.data) {
      this.reloadDAG = true;
      setNodesAndConnectionsFromDraft.call(this, $scope.AdapterCreateController.data);
    }

    this.pluginTypes = [
      {
        name: 'source',
        icon: 'icon-ETLsources'
      },
      {
        name: 'transform',
        icon: 'icon-ETLtransforms'
      },
      {
        name: 'sink',
        icon: 'icon-ETLsinks'
      }
    ];

    this.canvasOperations = [
      {
        name: 'Settings',
        icon: 'fa fa-sliders'
      },
      {
        name: 'Publish',
        icon: 'fa fa-cloud-upload'
      },
      {
        name: 'Save Draft',
        icon: 'fa fa-save'
      },
      {
        name: 'Config',
        icon: 'fa fa-eye'
      },
      {
        name: 'Export',
        icon: 'fa fa-download'
      },
      {
        name: 'Import',
        icon: 'fa fa-upload'
      }
    ];

    // Utterly naive. We need to be more efficient and this code should look better.
    // Pushing for functionality for now. Will revisit this back.
    this.importFile = function(files) {
      var reader = new FileReader();
      var config = MyPlumbService.getConfigForBackend();
      reader.readAsText(files[0], "UTF-8");
      reader.onload = function (evt) {
        var result;
        try {
          result = JSON.parse(evt.target.result);
        } catch(e) {
          result = null;
          $alert({
            type: 'danger',
            content: 'The imported config json is incorrect. Please check the JSON content'
          });
          return;
        }

        if (result.template !== MyPlumbService.metadata.template.type) {
          $alert({
            type: 'danger',
            content: 'Template imported is for ' + result.template + '. Please switch to ' + result.template + ' creation to import.'
          });
          return;
        }
        // We need to perform more validations on the uploaded json.
        if (!result.config.source ||
            !result.config.sink ||
            !result.config.transforms) {
          $alert({
            type: 'danger',
            content: 'The structure of imported config is incorrect. To the base structure of the config please try creating a new adpater and viewing the config.'
          });
          return;
        }
        $scope.config = JSON.stringify(result);
        this.reloadDAG = true;
        MyPlumbService.resetToDefaults(true);
        setNodesAndConnectionsFromDraft.call(this, result);
        if ($scope.config.name) {
          MyPlumbService.metadata.name = $scope.config.name;
        }

        MyPlumbService.notifyError({});
        MyPlumbService.notifyResetListners();
      }.bind(this)
      reader.onerror = function (evt) {
        console.error('Upload config failed', evt);
      };
    };

    this.onCanvasOperationsClicked = function(group) {
      var config;
      switch(group.name) {
        case 'Export':
          var detailedConfig = MyPlumbService.getConfigForBackend();
          if (!MyPlumbService.metadata.name || MyPlumbService.metadata.name === '') {
            detailedConfig.name = 'noname';
          } else {
            detailedConfig.name =  MyPlumbService.metadata.name;
          }

          detailedConfig.ui = {
            nodes: MyPlumbService.nodes,
            connections: MyPlumbService.connections
          };
          var content = JSON.stringify(detailedConfig, null, 4);
          var blob = new Blob([content], { type: 'application/json'});
          this.exportFileName = detailedConfig.name + '-' + detailedConfig.template;
          this.url = URL.createObjectURL(blob);

          $scope.$on('$destroy', function () {
            URL.revokeObjectURL(this.url);
          });
          // Clicking on the hidden download button. #hack.
          $timeout(function() {
            document.getElementById('adapter-export-config-link').click();
          });
          break;
        case 'Import':
          // Clicking on the hidden upload button. #hack.
          $timeout(function() {
            document.getElementById('adapter-import-config-link').click();
          });
          break;
        case 'Config':
          config = angular.copy(MyPlumbService.getConfigForBackend());
          modalInstance = $bootstrapModal.open({
            templateUrl: '/assets/features/adapters/templates/create/viewconfig.html',
            size: 'lg',
            windowClass: 'adapter-modal',
            keyboard: true,
            controller: ['$scope', 'config', '$timeout', function($scope, config, $timeout) {
              $scope.config = JSON.stringify(config);
            }],
            resolve: {
              config: function() {
                return config;
              }
            }
          });
          break;
        case 'Publish':
          MyPlumbService
            .save()
            .then(
              function sucess(adapter) {
                $alert({
                  type: 'success',
                  content: adapter + ' successfully published.'
                });
                $state.go('apps.list');
              },
              function error(errorObj) {
                console.info('ERROR!: ', errorObj);
              }.bind(this)
            );
          break;
        case 'Settings':
          $bootstrapModal.open({
            templateUrl: '/assets/features/adapters/templates/create/settings.html',
            size: 'lg',
            windowClass: 'adapter-modal',
            keyboard: true,
            controller: ['$scope', 'metadata', 'EventPipe', function($scope, metadata, EventPipe) {
              $scope.metadata = metadata;
              var metadataCopy = angular.copy(metadata);
              $scope.reset = function() {
                $scope.metadata.template.schedule.cron = metadataCopy.template.schedule.cron;
                $scope.metadata.template.instance = metadataCopy.template.instance;
                EventPipe.emit('plugin.reset');
              };

              function closeFn() {
                $scope.reset();
                $scope.$close('cancel');
              }

              ModalConfirm.confirmModalAdapter(
                $scope,
                $scope.metadata,
                metadataCopy,
                closeFn
              );

            }],
            resolve: {
              'metadata': function() {
                return MyPlumbService.metadata;
              }
            }
          });
          break;
        case 'Save Draft':
          MyPlumbService
            .saveAsDraft()
            .then(
              function success() {
                $alert({
                  type: 'success',
                  content: MyPlumbService.metadata.name + ' successfully saved as draft.'
                });
                $state.go('adapters.list');
              },
              function error(message) {
                console.info('Failed saving as draft');
              }
            )
      }
    };

    this.plugins= {
      items: []
    };

    this.onPluginTypesClicked = function(group) {
      var prom;
      switch(group.name) {
        case 'source':
          prom = myAdapterApi.fetchSources({ adapterType: MyPlumbService.metadata.template.type }).$promise;
          break;
        case 'transform':
          prom = myAdapterApi.fetchTransforms({ adapterType: MyPlumbService.metadata.template.type }).$promise;
          break;
        case 'sink':
          prom = myAdapterApi.fetchSinks({ adapterType: MyPlumbService.metadata.template.type }).$promise;
          break;
      }
      prom.then(function(res) {
        this.plugins.items = [];
        res.forEach(function(plugin) {
          this.plugins.items.push(
            angular.extend(
              {
                type: group.name,
                icon: MyPlumbFactory.getIcon(plugin.name)
              },
              plugin
            )
          );
        }.bind(this));
      }.bind(this));
    };

    this.onPluginItemClicked = function(event, item) {
      if (item.type === 'source' && this.pluginTypes[0].error) {
        delete this.pluginTypes[0].error;
      } else if (item.type === 'sink' && this.pluginTypes[2].error) {
        delete this.pluginTypes[2].error;
      }

      // TODO: Better UUID?
      var id = item.name + '-' + item.type + '-' + Date.now();
      event.stopPropagation();
      var config = {
        id: id,
        name: item.name,
        icon: item.icon,
        description: item.description,
        type: item.type
      };
      MyPlumbService.addNodes(config, config.type, true);
    };

    function errorNotification(errors) {
      angular.forEach(this.pluginTypes, function (type) {
        delete type.error;
        if (errors[type.name]) {
          type.error = errors[type.name];
        }
      });
    }

    MyPlumbService.errorCallback(errorNotification.bind(this));

    function setNodesAndConnectionsFromDraft(data) {
      var ui = data.ui;
      var config = data.config;
      var nodes;
      var config1 = CanvasFactory.extractMetadataFromDraft(data.config, data);

      if (config1.name) {
        MyPlumbService.metadata.name = config1.name;
      }
      MyPlumbService.metadata.description = config1.description;
      MyPlumbService.metadata.template = config1.template;

      // Purely for feeding my-plumb to draw the diagram
      // if I already have the nodes and connections
      if (ui && ui.nodes) {
        nodes = ui.nodes;
        while(this.nodes.length) {
          this.nodes.pop();
        }
        angular.forEach(nodes, function(value) {
          this.nodes.push(value);
        }.bind(this));
      } else {
        this.nodes = CanvasFactory.getNodes(config);
      }
      this.nodes.forEach(function(node) {
        MyPlumbService.addNodes(node, node.type);
      });

      if (ui && ui.connections) {
        MyPlumbService.connections = ui.connections;
      } else {
        MyPlumbService.connections = CanvasFactory.getConnectionsBasedOnNodes(this.nodes);
      }
    }

    $scope.$on('$destroy', function() {
      $modalStack.dismissAll();
    });

  });
<commit_msg>Fixes adapter export by removing properties no related to export.<commit_after>angular.module(PKG.name + '.feature.adapters')
  .controller('CanvasController', function (myAdapterApi, MyPlumbService, $bootstrapModal, $state, $scope, $alert, myHelpers, CanvasFactory, MyPlumbFactory, $modalStack, $timeout, ModalConfirm) {
    this.nodes = [];
    this.reloadDAG = false;
    if ($scope.AdapterCreateController.data) {
      this.reloadDAG = true;
      setNodesAndConnectionsFromDraft.call(this, $scope.AdapterCreateController.data);
    }

    this.pluginTypes = [
      {
        name: 'source',
        icon: 'icon-ETLsources'
      },
      {
        name: 'transform',
        icon: 'icon-ETLtransforms'
      },
      {
        name: 'sink',
        icon: 'icon-ETLsinks'
      }
    ];

    this.canvasOperations = [
      {
        name: 'Settings',
        icon: 'fa fa-sliders'
      },
      {
        name: 'Publish',
        icon: 'fa fa-cloud-upload'
      },
      {
        name: 'Save Draft',
        icon: 'fa fa-save'
      },
      {
        name: 'Config',
        icon: 'fa fa-eye'
      },
      {
        name: 'Export',
        icon: 'fa fa-download'
      },
      {
        name: 'Import',
        icon: 'fa fa-upload'
      }
    ];

    // Utterly naive. We need to be more efficient and this code should look better.
    // Pushing for functionality for now. Will revisit this back.
    this.importFile = function(files) {
      var reader = new FileReader();
      var config = MyPlumbService.getConfigForBackend();
      reader.readAsText(files[0], "UTF-8");
      reader.onload = function (evt) {
        var result;
        try {
          result = JSON.parse(evt.target.result);
        } catch(e) {
          result = null;
          $alert({
            type: 'danger',
            content: 'The imported config json is incorrect. Please check the JSON content'
          });
          return;
        }

        if (result.template !== MyPlumbService.metadata.template.type) {
          $alert({
            type: 'danger',
            content: 'Template imported is for ' + result.template + '. Please switch to ' + result.template + ' creation to import.'
          });
          return;
        }
        // We need to perform more validations on the uploaded json.
        if (!result.config.source ||
            !result.config.sink ||
            !result.config.transforms) {
          $alert({
            type: 'danger',
            content: 'The structure of imported config is incorrect. To the base structure of the config please try creating a new adpater and viewing the config.'
          });
          return;
        }
        $scope.config = JSON.stringify(result);
        this.reloadDAG = true;
        MyPlumbService.resetToDefaults(true);
        setNodesAndConnectionsFromDraft.call(this, result);
        if ($scope.config.name) {
          MyPlumbService.metadata.name = $scope.config.name;
        }

        MyPlumbService.notifyError({});
        MyPlumbService.notifyResetListners();
      }.bind(this)
      reader.onerror = function (evt) {
        console.error('Upload config failed', evt);
      };
    };

    this.onCanvasOperationsClicked = function(group) {
      var config;
      switch(group.name) {
        case 'Export':
          var detailedConfig = MyPlumbService.getConfigForBackend();
          if (!MyPlumbService.metadata.name || MyPlumbService.metadata.name === '') {
            detailedConfig.name = 'noname';
          } else {
            detailedConfig.name =  MyPlumbService.metadata.name;
          }

          detailedConfig.ui = {
            nodes: MyPlumbService.nodes,
            connections: MyPlumbService.connections
          };

          angular.forEach(detailedConfig.ui.nodes, function(node) {
            delete node._backendProperties;
          });
          detailedConfig.ui.connections.forEach(function(conn) {
            delete conn.visited;
          });

          var content = JSON.stringify(detailedConfig, null, 4);
          var blob = new Blob([content], { type: 'application/json'});
          this.exportFileName = detailedConfig.name + '-' + detailedConfig.template;
          this.url = URL.createObjectURL(blob);

          $scope.$on('$destroy', function () {
            URL.revokeObjectURL(this.url);
          });
          // Clicking on the hidden download button. #hack.
          $timeout(function() {
            document.getElementById('adapter-export-config-link').click();
          });
          break;
        case 'Import':
          // Clicking on the hidden upload button. #hack.
          $timeout(function() {
            document.getElementById('adapter-import-config-link').click();
          });
          break;
        case 'Config':
          config = angular.copy(MyPlumbService.getConfigForBackend());
          modalInstance = $bootstrapModal.open({
            templateUrl: '/assets/features/adapters/templates/create/viewconfig.html',
            size: 'lg',
            windowClass: 'adapter-modal',
            keyboard: true,
            controller: ['$scope', 'config', '$timeout', function($scope, config, $timeout) {
              $scope.config = JSON.stringify(config);
            }],
            resolve: {
              config: function() {
                return config;
              }
            }
          });
          break;
        case 'Publish':
          MyPlumbService
            .save()
            .then(
              function sucess(adapter) {
                $alert({
                  type: 'success',
                  content: adapter + ' successfully published.'
                });
                $state.go('apps.list');
              },
              function error(errorObj) {
                console.info('ERROR!: ', errorObj);
              }.bind(this)
            );
          break;
        case 'Settings':
          $bootstrapModal.open({
            templateUrl: '/assets/features/adapters/templates/create/settings.html',
            size: 'lg',
            windowClass: 'adapter-modal',
            keyboard: true,
            controller: ['$scope', 'metadata', 'EventPipe', function($scope, metadata, EventPipe) {
              $scope.metadata = metadata;
              var metadataCopy = angular.copy(metadata);
              $scope.reset = function() {
                $scope.metadata.template.schedule.cron = metadataCopy.template.schedule.cron;
                $scope.metadata.template.instance = metadataCopy.template.instance;
                EventPipe.emit('plugin.reset');
              };

              function closeFn() {
                $scope.reset();
                $scope.$close('cancel');
              }

              ModalConfirm.confirmModalAdapter(
                $scope,
                $scope.metadata,
                metadataCopy,
                closeFn
              );

            }],
            resolve: {
              'metadata': function() {
                return MyPlumbService.metadata;
              }
            }
          });
          break;
        case 'Save Draft':
          MyPlumbService
            .saveAsDraft()
            .then(
              function success() {
                $alert({
                  type: 'success',
                  content: MyPlumbService.metadata.name + ' successfully saved as draft.'
                });
                $state.go('adapters.list');
              },
              function error(message) {
                console.info('Failed saving as draft');
              }
            )
      }
    };

    this.plugins= {
      items: []
    };

    this.onPluginTypesClicked = function(group) {
      var prom;
      switch(group.name) {
        case 'source':
          prom = myAdapterApi.fetchSources({ adapterType: MyPlumbService.metadata.template.type }).$promise;
          break;
        case 'transform':
          prom = myAdapterApi.fetchTransforms({ adapterType: MyPlumbService.metadata.template.type }).$promise;
          break;
        case 'sink':
          prom = myAdapterApi.fetchSinks({ adapterType: MyPlumbService.metadata.template.type }).$promise;
          break;
      }
      prom.then(function(res) {
        this.plugins.items = [];
        res.forEach(function(plugin) {
          this.plugins.items.push(
            angular.extend(
              {
                type: group.name,
                icon: MyPlumbFactory.getIcon(plugin.name)
              },
              plugin
            )
          );
        }.bind(this));
      }.bind(this));
    };

    this.onPluginItemClicked = function(event, item) {
      if (item.type === 'source' && this.pluginTypes[0].error) {
        delete this.pluginTypes[0].error;
      } else if (item.type === 'sink' && this.pluginTypes[2].error) {
        delete this.pluginTypes[2].error;
      }

      // TODO: Better UUID?
      var id = item.name + '-' + item.type + '-' + Date.now();
      event.stopPropagation();
      var config = {
        id: id,
        name: item.name,
        icon: item.icon,
        description: item.description,
        type: item.type
      };
      MyPlumbService.addNodes(config, config.type, true);
    };

    function errorNotification(errors) {
      angular.forEach(this.pluginTypes, function (type) {
        delete type.error;
        if (errors[type.name]) {
          type.error = errors[type.name];
        }
      });
    }

    MyPlumbService.errorCallback(errorNotification.bind(this));

    function setNodesAndConnectionsFromDraft(data) {
      var ui = data.ui;
      var config = data.config;
      var nodes;
      var config1 = CanvasFactory.extractMetadataFromDraft(data.config, data);

      if (config1.name) {
        MyPlumbService.metadata.name = config1.name;
      }
      MyPlumbService.metadata.description = config1.description;
      MyPlumbService.metadata.template = config1.template;

      // Purely for feeding my-plumb to draw the diagram
      // if I already have the nodes and connections
      if (ui && ui.nodes) {
        nodes = ui.nodes;
        while(this.nodes.length) {
          this.nodes.pop();
        }
        angular.forEach(nodes, function(value) {
          this.nodes.push(value);
        }.bind(this));
      } else {
        this.nodes = CanvasFactory.getNodes(config);
      }
      this.nodes.forEach(function(node) {
        MyPlumbService.addNodes(node, node.type);
      });

      if (ui && ui.connections) {
        MyPlumbService.connections = ui.connections;
      } else {
        MyPlumbService.connections = CanvasFactory.getConnectionsBasedOnNodes(this.nodes);
      }
    }

    $scope.$on('$destroy', function() {
      $modalStack.dismissAll();
    });

  });
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const defaultVars = require('./scripts/default-vars');
const darkVars = require('./scripts/dark-vars');
const compactVars = require('./scripts/compact-vars');

function generateThemeFileContent(theme) {
  return `const { ${theme}ThemeSingle } = require('./theme');\nconst defaultTheme = require('./default-theme');\n
module.exports = {
  ...defaultTheme,
  ...${theme}ThemeSingle
}`;
}

// We need compile additional content for antd user
function finalizeCompile() {
  if (fs.existsSync(path.join(__dirname, './lib'))) {
    // Build a entry less file to dist/antd.less
    const componentsPath = path.join(process.cwd(), 'components');
    let componentsLessContent = '';
    // Build components in one file: lib/style/components.less
    fs.readdir(componentsPath, (err, files) => {
      files.forEach(file => {
        if (fs.existsSync(path.join(componentsPath, file, 'style', 'index.less'))) {
          componentsLessContent += `@import "../${path.join(file, 'style', 'index.less')}";\n`;
        }
      });
      fs.writeFileSync(
        path.join(process.cwd(), 'lib', 'style', 'components.less'),
        componentsLessContent,
      );
    });
  }
}

function buildThemeFile(theme, vars) {
  // Build less entry file: dist/antd.${theme}.less
  if (theme !== 'default') {
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', `antd.${theme}.less`),
      `@import "../lib/style/${theme}.less";\n@import "../lib/style/components.less";`,
    );
    // eslint-disable-next-line no-console
    console.log(`Built a entry less file to dist/antd.${theme}.less`);
  } else {
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', `default-theme.js`),
      `module.exports = ${JSON.stringify(vars, null, 2)};\n`,
    );
    return;
  }

  // Build ${theme}.js: dist/${theme}-theme.js, for less-loader

  fs.writeFileSync(
    path.join(process.cwd(), 'dist', `theme.js`),
    `const ${theme}ThemeSingle = ${JSON.stringify(vars, null, 2)};\n`,
    {
      flag: 'a',
    },
  );

  fs.writeFileSync(
    path.join(process.cwd(), 'dist', `${theme}-theme.js`),
    generateThemeFileContent(theme),
  );

  // eslint-disable-next-line no-console
  console.log(`Built a ${theme} theme js file to dist/${theme}-theme.js`);
}

function finalizeDist() {
  if (fs.existsSync(path.join(__dirname, './dist'))) {
    // Build less entry file: dist/antd.less
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', 'antd.less'),
      '@import "../lib/style/index.less";\n@import "../lib/style/components.less";',
    );
    // eslint-disable-next-line no-console
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', 'theme.js'),
      `const defaultTheme = require('./default-theme.js');\n`,
    );
    // eslint-disable-next-line no-console
    console.log('Built a entry less file to dist/antd.less');
    buildThemeFile('default', defaultVars);
    buildThemeFile('dark', darkVars);
    buildThemeFile('compact', compactVars);
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', `theme.js`),
      `
function getThemeVariables(options = {}) {
  let themeVar = {
    'hack': \`true;@import "\${require.resolve('antd/lib/style/color/colorPalette.less')}";\`,
    ...defaultTheme
  };
  if(options.dark) {
    themeVar = {
      ...themeVar,
      ...darkThemeSingle
    }
  }
  if(options.compact){
    themeVar = {
      ...themeVar,
      ...compactThemeSingle
    }
  }
  return themeVar;
}

module.exports = {
  darkThemeSingle,
  compactThemeSingle,
  getThemeVariables
}`,
      {
        flag: 'a',
      },
    );
  }
}

module.exports = {
  compile: {
    finalize: finalizeCompile,
  },
  dist: {
    finalize: finalizeDist,
  },
  generateThemeFileContent,
};
<commit_msg>fix: path error when packaging the component style export file in the windeos environment (#31277)<commit_after>const fs = require('fs');
const path = require('path');
const defaultVars = require('./scripts/default-vars');
const darkVars = require('./scripts/dark-vars');
const compactVars = require('./scripts/compact-vars');

function generateThemeFileContent(theme) {
  return `const { ${theme}ThemeSingle } = require('./theme');\nconst defaultTheme = require('./default-theme');\n
module.exports = {
  ...defaultTheme,
  ...${theme}ThemeSingle
}`;
}

// We need compile additional content for antd user
function finalizeCompile() {
  if (fs.existsSync(path.join(__dirname, './lib'))) {
    // Build a entry less file to dist/antd.less
    const componentsPath = path.join(process.cwd(), 'components');
    let componentsLessContent = '';
    // Build components in one file: lib/style/components.less
    fs.readdir(componentsPath, (err, files) => {
      files.forEach(file => {
        if (fs.existsSync(path.join(componentsPath, file, 'style', 'index.less'))) {
          componentsLessContent += `@import "../${path.posix.join(file, 'style', 'index.less')}";\n`;
        }
      });
      fs.writeFileSync(
        path.join(process.cwd(), 'lib', 'style', 'components.less'),
        componentsLessContent,
      );
    });
  }
}

function buildThemeFile(theme, vars) {
  // Build less entry file: dist/antd.${theme}.less
  if (theme !== 'default') {
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', `antd.${theme}.less`),
      `@import "../lib/style/${theme}.less";\n@import "../lib/style/components.less";`,
    );
    // eslint-disable-next-line no-console
    console.log(`Built a entry less file to dist/antd.${theme}.less`);
  } else {
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', `default-theme.js`),
      `module.exports = ${JSON.stringify(vars, null, 2)};\n`,
    );
    return;
  }

  // Build ${theme}.js: dist/${theme}-theme.js, for less-loader

  fs.writeFileSync(
    path.join(process.cwd(), 'dist', `theme.js`),
    `const ${theme}ThemeSingle = ${JSON.stringify(vars, null, 2)};\n`,
    {
      flag: 'a',
    },
  );

  fs.writeFileSync(
    path.join(process.cwd(), 'dist', `${theme}-theme.js`),
    generateThemeFileContent(theme),
  );

  // eslint-disable-next-line no-console
  console.log(`Built a ${theme} theme js file to dist/${theme}-theme.js`);
}

function finalizeDist() {
  if (fs.existsSync(path.join(__dirname, './dist'))) {
    // Build less entry file: dist/antd.less
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', 'antd.less'),
      '@import "../lib/style/index.less";\n@import "../lib/style/components.less";',
    );
    // eslint-disable-next-line no-console
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', 'theme.js'),
      `const defaultTheme = require('./default-theme.js');\n`,
    );
    // eslint-disable-next-line no-console
    console.log('Built a entry less file to dist/antd.less');
    buildThemeFile('default', defaultVars);
    buildThemeFile('dark', darkVars);
    buildThemeFile('compact', compactVars);
    fs.writeFileSync(
      path.join(process.cwd(), 'dist', `theme.js`),
      `
function getThemeVariables(options = {}) {
  let themeVar = {
    'hack': \`true;@import "\${require.resolve('antd/lib/style/color/colorPalette.less')}";\`,
    ...defaultTheme
  };
  if(options.dark) {
    themeVar = {
      ...themeVar,
      ...darkThemeSingle
    }
  }
  if(options.compact){
    themeVar = {
      ...themeVar,
      ...compactThemeSingle
    }
  }
  return themeVar;
}

module.exports = {
  darkThemeSingle,
  compactThemeSingle,
  getThemeVariables
}`,
      {
        flag: 'a',
      },
    );
  }
}

module.exports = {
  compile: {
    finalize: finalizeCompile,
  },
  dist: {
    finalize: finalizeDist,
  },
  generateThemeFileContent,
};
<|endoftext|>


<commit_before>import flatten from 'flat';

export function reformatColumns(items) {
	const flatList = items.map((item) => flatten(item, { maxDepth: 2 }));

	const reformattedList = rotateOnTeam(flatList);
	const concatObj = concatOnProperties(reformattedList);
	const concatList = convertToList(concatObj);

	return concatList;
}

function rotateOnTeam(list) {
	// convert columns
  const rotatedList = list.map((item) => ({
    ...item,
    // Put the hours in the right column
    [item['budgetHours.column']]: item['budgetHours.value'],
   }));

  return rotatedList;
}

function concatOnProperties(list) {
	let concatObj = {};

	// combine on feature
	list.map((item) => {
    // Feature isn't already in the object
		if (typeof concatObj[item.feature] === 'undefined') {
			concatObj[item.feature] = item;
		} else {
      // Add to existing feature
			for (const property in item) {
				if(Array.isArray(item[property])) {
          concatObj[item.feature][property] = [
            ...concatObj[item.feature][property],
            ...item[property],
          ];
				} else if(typeof item[property] === 'number') {
          // Sum the numbers
					concatObj[item.feature][property] = concatObj[item.feature][property] + item[property] || item[property];
				}
			}
		}
		return item;
	});

	return concatObj;
}

// convert concatObj from properties to array elements
export function convertToList(object) {
	let list = [];

	for (const element in object) {
		if(object.hasOwnProperty(element)) {
			list = [...list, object[element]];
		}
	}

	return list;
}
<commit_msg>Fix typcasting error<commit_after>import flatten from 'flat';

export function reformatColumns(items) {
	const flatList = items.map((item) => flatten(item, { maxDepth: 2 }));

	const reformattedList = rotateOnTeam(flatList);
	const concatObj = concatOnProperties(reformattedList);
	const concatList = convertToList(concatObj);

	return concatList;
}

function rotateOnTeam(list) {
	// convert columns
  const rotatedList = list.map((item) => ({
    ...item,
    // Put the hours in the right column
    [item['budgetHours.column']]: parseInt(item['budgetHours.value']),
   }));

  return rotatedList;
}

function concatOnProperties(list) {
	let concatObj = {};

	// combine on feature
	list.map((item) => {
    // Feature isn't already in the object
		if (typeof concatObj[item.feature] === 'undefined') {
			concatObj[item.feature] = item;
		} else {
      // Add to existing feature
			for (const property in item) {
				if(Array.isArray(item[property])) {
          concatObj[item.feature][property] = [
            ...concatObj[item.feature][property],
            ...item[property],
          ];
				} else if(typeof item[property] === 'number') {
          // Sum the numbers
					concatObj[item.feature][property] = concatObj[item.feature][property] + item[property] || item[property];
				}
			}
		}
		return item;
	});
	return concatObj;
}

// convert concatObj from properties to array elements
export function convertToList(object) {
	let list = [];

	for (const element in object) {
		if(object.hasOwnProperty(element)) {
			list = [...list, object[element]];
		}
	}

	return list;
}
<|endoftext|>


<commit_before>var updateChangedPackages = require("./updateChangedPackages");
var checkUpdatedPackages  = require("../../utils/checkUpdatedPackages");
var npmPublishSemiAtomic  = require("./npmPublishSemiAtomic");
var readline              = require("readline-sync");
var gitUtils              = require("../../utils/gitUtils");
var fsUtils               = require("../../utils/fsUtils");
var logger                = require("../../utils/logger");
var semver                = require("semver");

function userGetVersion(currentVersion, pkgName) {
  var message = "New version ";
  if (pkgName) message += "for \"" + pkgName + "\" ";
  message += "(Leave blank for patch version): ";

  var input = readline.question(message);

  var ver = semver.valid(input);

  if (!ver) {
    ver = semver.inc(currentVersion, input || "patch");
  }

  if (ver) {
    return ver;
  } else {
    logger.log("info", "Version provided is not valid semver.");
    return userGetVersion(currentVersion, pkgName);
  }
}

function updateVersionFile(versionLoc, version) {
  fsUtils.writeFileSync(versionLoc, version, "utf8");
  gitUtils.addFile(versionLoc);
}

function gitCommitAndTagVersion(version) {
  var tag = "v" + version;
  gitUtils.commit(tag);
  gitUtils.addTag(tag);
  return tag;
}

function gitCommitAndTagVersions(packages, versions) {
  var message = "Publish\n";
  var tags = packages.map(function(pkg) {
    var tag = pkg.name + "@" + versions[pkg.name];
    message += "\n - " + tag;
    return tag;
  });

  gitUtils.commit(message);
  tags.forEach(gitUtils.addTag);
  return tags;
}

function gitRemoveTaggedVersions(tags) {
  logger.log("warning", "Attempting to roll back tag creation.");
  tags.forEach(gitUtils.removeTag);
}

function gitPushWithTags(tags) {
  execSync("git push");
  execSync("git push origin " + tags.join(" "));
}

function logChangedPackages(packages, versions) {
  logger.log("info", "Packages to be updated");
  logger.log("info", packages.map(function (pkg) {
    return "- " + pkg.name + "@" + versions[pkg.name];
  }).join("\n"));
}

module.exports = function publishChangedPackages(
  currentVersion,
  versionLoc,
  packagesLoc,
  independent,
  callback
) {
  var changedPackages;
  var masterVersion;
  var versions = {};
  var tags;

  try {
    // Find all changed packages to publish
    changedPackages = checkUpdatedPackages(packagesLoc);

    if (!independent) {
      // Prompt the user for the version
      masterVersion = userGetVersion(currentVersion);
      updateVersionFile(versionLoc, masterVersion);
      logger.log("info", masterVersion);
    }

    changedPackages.forEach(function(pkg) {
      if (independent) {
        versions[pkg.name] = userGetVersion(pkg.version, pkg.name);
      } else {
        versions[pkg.name] = masterVersion;
      }
    });

    // Log them to the console
    logChangedPackages(changedPackages, versions);

    // Go through all the changed packages and update their package.json deps.
    updateChangedPackages(changedPackages, packagesLoc, versions);

    // Add a tag for the new version
    if (independent) {
      tags = gitCommitAndTagVersions(changedPackages, versions);
    } else {
      tags = [gitCommitAndTagVersion(masterVersion)];
    }

    npmPublishSemiAtomic(changedPackages, packagesLoc, versions, function (err) {
      if (err) return onError(err);
      gitUtils.pushWithTags(tags);
      onSuccess();
    });
  } catch (err) {
    onError(err);
  }

  function onSuccess() {
    callback(null, changedPackages, versions);
  }

  function onError(err) {
    // If we got far along to create a tag, remove it.
    if (tags) gitRemoveTaggedVersions(tags);
    callback(err);
  }
}
<commit_msg>Fix lint<commit_after>var updateChangedPackages = require("./updateChangedPackages");
var checkUpdatedPackages  = require("../../utils/checkUpdatedPackages");
var npmPublishSemiAtomic  = require("./npmPublishSemiAtomic");
var readline              = require("readline-sync");
var gitUtils              = require("../../utils/gitUtils");
var fsUtils               = require("../../utils/fsUtils");
var logger                = require("../../utils/logger");
var semver                = require("semver");

function userGetVersion(currentVersion, pkgName) {
  var message = "New version ";
  if (pkgName) message += "for \"" + pkgName + "\" ";
  message += "(Leave blank for patch version): ";

  var input = readline.question(message);

  var ver = semver.valid(input);

  if (!ver) {
    ver = semver.inc(currentVersion, input || "patch");
  }

  if (ver) {
    return ver;
  } else {
    logger.log("info", "Version provided is not valid semver.");
    return userGetVersion(currentVersion, pkgName);
  }
}

function updateVersionFile(versionLoc, version) {
  fsUtils.writeFileSync(versionLoc, version, "utf8");
  gitUtils.addFile(versionLoc);
}

function gitCommitAndTagVersion(version) {
  var tag = "v" + version;
  gitUtils.commit(tag);
  gitUtils.addTag(tag);
  return tag;
}

function gitCommitAndTagVersions(packages, versions) {
  var message = "Publish\n";
  var tags = packages.map(function(pkg) {
    var tag = pkg.name + "@" + versions[pkg.name];
    message += "\n - " + tag;
    return tag;
  });

  gitUtils.commit(message);
  tags.forEach(gitUtils.addTag);
  return tags;
}

function gitRemoveTaggedVersions(tags) {
  logger.log("warning", "Attempting to roll back tag creation.");
  tags.forEach(gitUtils.removeTag);
}

function logChangedPackages(packages, versions) {
  logger.log("info", "Packages to be updated");
  logger.log("info", packages.map(function (pkg) {
    return "- " + pkg.name + "@" + versions[pkg.name];
  }).join("\n"));
}

module.exports = function publishChangedPackages(
  currentVersion,
  versionLoc,
  packagesLoc,
  independent,
  callback
) {
  var changedPackages;
  var masterVersion;
  var versions = {};
  var tags;

  try {
    // Find all changed packages to publish
    changedPackages = checkUpdatedPackages(packagesLoc);

    if (!independent) {
      // Prompt the user for the version
      masterVersion = userGetVersion(currentVersion);
      updateVersionFile(versionLoc, masterVersion);
      logger.log("info", masterVersion);
    }

    changedPackages.forEach(function(pkg) {
      if (independent) {
        versions[pkg.name] = userGetVersion(pkg.version, pkg.name);
      } else {
        versions[pkg.name] = masterVersion;
      }
    });

    // Log them to the console
    logChangedPackages(changedPackages, versions);

    // Go through all the changed packages and update their package.json deps.
    updateChangedPackages(changedPackages, packagesLoc, versions);

    // Add a tag for the new version
    if (independent) {
      tags = gitCommitAndTagVersions(changedPackages, versions);
    } else {
      tags = [gitCommitAndTagVersion(masterVersion)];
    }

    npmPublishSemiAtomic(changedPackages, packagesLoc, versions, function (err) {
      if (err) return onError(err);
      gitUtils.pushWithTags(tags);
      onSuccess();
    });
  } catch (err) {
    onError(err);
  }

  function onSuccess() {
    callback(null, changedPackages, versions);
  }

  function onError(err) {
    // If we got far along to create a tag, remove it.
    if (tags) gitRemoveTaggedVersions(tags);
    callback(err);
  }
}
<|endoftext|>


<commit_before>/*
 *
 * (c) Copyright Ascensio System Limited 2010-2016
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

/**
 *  DocumentHolder.js
 *  Document Editor
 *
 *  Created by Alexander Yuzhin on 11/8/16
 *  Copyright (c) 2016 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'jquery',
    'underscore',
    'backbone'
], function ($, _, Backbone) {
    'use strict';

    DE.Views.DocumentHolder = Backbone.View.extend((function() {
        // private
        var _anchorId = 'context-menu-target';

        function androidSizeMenu(popover, target) {
            popover.css({left: '', top: ''});
            var modalWidth =  popover.width();
            var modalHeight =  popover.height();
            var modalAngleSize = 10;
            var targetWidth = target.outerWidth();
            var targetHeight = target.outerHeight();
            var targetOffset = target.offset();
            var targetParentPage = target.parents('.page');
            if (targetParentPage.length > 0) {
                targetOffset.top = targetOffset.top - targetParentPage[0].scrollTop;
            }

            var windowHeight = $(window).height();
            var windowWidth = $(window).width();

            var modalTop = 0;
            var modalLeft = 0;

            // Top Position
            var modalPosition = 'top';// material ? 'bottom' : 'top';
            {
                if ((modalHeight + modalAngleSize) < targetOffset.top) {
                    // On top
                    modalTop = targetOffset.top - modalHeight - modalAngleSize;
                }
                else if ((modalHeight + modalAngleSize) < windowHeight - targetOffset.top - targetHeight) {
                    // On bottom
                    modalPosition = 'bottom';
                    modalTop = targetOffset.top + targetHeight + modalAngleSize;
                }
                else {
                    // On middle
                    modalPosition = 'middle';
                    modalTop = targetHeight / 2 + targetOffset.top - modalHeight / 2;

                    if (modalTop <= 0) {
                        modalTop = 5;
                    }
                    else if (modalTop + modalHeight >= windowHeight) {
                        modalTop = windowHeight - modalHeight - 5;
                    }
                }

                // Horizontal Position
                if (modalPosition === 'top' || modalPosition === 'bottom') {
                    modalLeft = targetWidth / 2 + targetOffset.left - modalWidth / 2;
                    if (modalLeft < 5) modalLeft = 5;
                    if (modalLeft + modalWidth > windowWidth) modalLeft = windowWidth - modalWidth - 5;
                }
                else if (modalPosition === 'middle') {
                    modalLeft = targetOffset.left - modalWidth - modalAngleSize;

                    if (modalLeft < 5 || (modalLeft + modalWidth > windowWidth)) {
                        if (modalLeft < 5) modalLeft = targetOffset.left + targetWidth + modalAngleSize;
                        if (modalLeft + modalWidth > windowWidth) modalLeft = windowWidth - modalWidth - 5;
                    }
                }
            }

            // Apply Styles
            popover.css({top: modalTop + 'px', left: modalLeft + 'px'});
        }

        return {
            el: '#editor_sdk',

            template: _.template('

'),
            // Delegated events for creating new items, and clearing completed ones.
            events: {
            },

            // Set innerHTML and get the references to the DOM elements
            initialize: function() {
                //
            },

            // Render layout
            render: function() {
                var el = $(this.el);
                el.append(this.template({}));

                return this;
            },

            showMenu: function (items, posX, posY) {
                if (items.length < 1) {
                    return;
                }

                var menuItemTemplate = _.template([
                    '<% _.each(menuItems, function(item) { %>',
                    '<li data-event="<%= item.event %>"><%= item.caption %>
',
                    '<% }); %>'
                ].join(''));

                $('#' + _anchorId)
                    .css('left', posX)
                    .css('top', posY);

                uiApp.closeModal('.document-menu.modal-in');

                var popoverHTML =
                    '
'+
                        '
'+
                            '
'+
                                '
'+
                                    menuItemTemplate({menuItems: items}) +
                                '
'+
                            '
'+
                        '
'+
                    '
';

                var popover = uiApp.popover(popoverHTML, $('#' + _anchorId));

                if (Common.SharedSettings.get('android')) {
                    androidSizeMenu($(popover),  $('#' + _anchorId));
                }

                $('.modal-overlay').removeClass('modal-overlay-visible');

                $('.document-menu li').single('click', _.buffered(function(e) {
                    var $target = $(e.currentTarget),
                        eventName = $target.data('event');

                    this.fireEvent('contextmenu:click', [this, eventName]);
                }, 100, this));
            },

            hideMenu: function () {
                $('#' + _anchorId)
                    .css('left', -1000)
                    .css('top', -1000);

                uiApp.closeModal('.document-menu.modal-in');
            }
        }
    })());
});<commit_msg>[DE mobile] Fixed display context menu.<commit_after>/*
 *
 * (c) Copyright Ascensio System Limited 2010-2016
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

/**
 *  DocumentHolder.js
 *  Document Editor
 *
 *  Created by Alexander Yuzhin on 11/8/16
 *  Copyright (c) 2016 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'jquery',
    'underscore',
    'backbone'
], function ($, _, Backbone) {
    'use strict';

    DE.Views.DocumentHolder = Backbone.View.extend((function() {
        // private
        var _anchorId = 'context-menu-target';

        function androidSizeMenu(popover, target) {
            popover.css({left: '', top: ''});
            var modalWidth =  popover.width();
            var modalHeight =  popover.height();
            var modalAngleSize = 10;
            var targetWidth = target.outerWidth();
            var targetHeight = target.outerHeight();
            var targetOffset = target.offset();
            var targetParentPage = target.parents('.page');
            if (targetParentPage.length > 0) {
                targetOffset.top = targetOffset.top - targetParentPage[0].scrollTop;
            }

            var windowHeight = $(window).height();
            var windowWidth = $(window).width();

            var modalTop = 0;
            var modalLeft = 0;

            // Top Position
            var modalPosition = 'top';// material ? 'bottom' : 'top';
            {
                if ((modalHeight + modalAngleSize) < targetOffset.top) {
                    // On top
                    modalTop = targetOffset.top - modalHeight - modalAngleSize;
                }
                else if ((modalHeight + modalAngleSize) < windowHeight - targetOffset.top - targetHeight) {
                    // On bottom
                    modalPosition = 'bottom';
                    modalTop = targetOffset.top + targetHeight + modalAngleSize;
                }
                else {
                    // On middle
                    modalPosition = 'middle';
                    modalTop = targetHeight / 2 + targetOffset.top - modalHeight / 2;

                    if (modalTop <= 0) {
                        modalTop = 5;
                    }
                    else if (modalTop + modalHeight >= windowHeight) {
                        modalTop = windowHeight - modalHeight - 5;
                    }
                }

                // Horizontal Position
                if (modalPosition === 'top' || modalPosition === 'bottom') {
                    modalLeft = targetWidth / 2 + targetOffset.left - modalWidth / 2;
                    if (modalLeft < 5) modalLeft = 5;
                    if (modalLeft + modalWidth > windowWidth) modalLeft = windowWidth - modalWidth - 5;
                }
                else if (modalPosition === 'middle') {
                    modalLeft = targetOffset.left - modalWidth - modalAngleSize;

                    if (modalLeft < 5 || (modalLeft + modalWidth > windowWidth)) {
                        if (modalLeft < 5) modalLeft = targetOffset.left + targetWidth + modalAngleSize;
                        if (modalLeft + modalWidth > windowWidth) modalLeft = windowWidth - modalWidth - 5;
                    }
                }
            }

            // Apply Styles
            popover.css({top: modalTop + 'px', left: modalLeft + 'px'});
        }

        return {
            el: '#editor_sdk',

            template: _.template('

'),
            // Delegated events for creating new items, and clearing completed ones.
            events: {
            },

            // Set innerHTML and get the references to the DOM elements
            initialize: function() {
                //
            },

            // Render layout
            render: function() {
                var el = $(this.el);
                el.append(this.template({}));

                return this;
            },

            showMenu: function (items, posX, posY) {
                if (items.length < 1) {
                    return;
                }

                var menuItemTemplate = _.template([
                    '<% _.each(menuItems, function(item) { %>',
                    '<li data-event="<%= item.event %>"><%= item.caption %>
',
                    '<% }); %>'
                ].join(''));

                $('#' + _anchorId)
                    .css('left', posX)
                    .css('top', Math.max(0, posY));

                uiApp.closeModal('.document-menu.modal-in');

                var popoverHTML =
                    '
'+
                        '
'+
                            '
'+
                                '
'+
                                    menuItemTemplate({menuItems: items}) +
                                '
'+
                            '
'+
                        '
'+
                    '
';

                var popover = uiApp.popover(popoverHTML, $('#' + _anchorId));

                if (Common.SharedSettings.get('android')) {
                    androidSizeMenu($(popover),  $('#' + _anchorId));
                }

                $('.modal-overlay').removeClass('modal-overlay-visible');

                $('.document-menu li').single('click', _.buffered(function(e) {
                    var $target = $(e.currentTarget),
                        eventName = $target.data('event');

                    this.fireEvent('contextmenu:click', [this, eventName]);
                }, 100, this));
            },

            hideMenu: function () {
                $('#' + _anchorId)
                    .css('left', -1000)
                    .css('top', -1000);

                uiApp.closeModal('.document-menu.modal-in');
            }
        }
    })());
});<|endoftext|>


<commit_before>import constants from '../constants';
import ApiFetch from '../../../utils/fetch/ApiFetch';

/**
 * Add comment on event
 *
 * **Dispatch**: `COMMENT_EVENT`
 *
 * @alias module:Comments.doCommentEvent
 * @category actions
 *
 * @example
 * BetaSeries.getAction('comments', 'doCommentEvent')({
 *   eventId: 438,
 *   text: 'Trop bien cette épisode !',
 * });
 *
 * @param {Object}  [obj]           Accept the following:
 * @param {Number}  [obj.eventId]   Event ID
 * @param {String}  [obj.text]      Text of comment
 *
 * @returns {Promise}
 */
const doCommentEvent = ({ eventId, text }) =>
  dispatch =>
    ApiFetch.post('comments/comment', {
      id: eventId,
      type: 'event',
      text
    }).then(response =>
      dispatch({
        type: constants.COMMENT_EVENT,
        payload: {
          eventId,
          text,
          comment: response.comment
        }
      }));

export default doCommentEvent;
<commit_msg>add other props to doCommentEvent action<commit_after>import constants from '../constants';
import ApiFetch from '../../../utils/fetch/ApiFetch';

/**
 * Add comment on event
 *
 * **Dispatch**: `COMMENT_EVENT`
 *
 * @alias module:Comments.doCommentEvent
 * @category actions
 *
 * @example
 * BetaSeries.getAction('comments', 'doCommentEvent')({
 *   eventId: 438,
 *   text: 'Trop bien cette épisode !',
 * });
 *
 * @param {Object}  [obj]           Accept the following:
 * @param {Number}  [obj.eventId]   Event ID
 * @param {String}  [obj.text]      Text of comment
 *
 * @returns {Promise}
 */
const doCommentEvent = ({ eventId, text, ...props }) =>
  dispatch =>
    ApiFetch.post('comments/comment', {
      ...props,
      id: eventId,
      type: 'event',
      text
    }).then(response =>
      dispatch({
        type: constants.COMMENT_EVENT,
        payload: {
          ...props,
          eventId,
          text,
          comment: response.comment
        }
      }));

export default doCommentEvent;
<|endoftext|>