<commit_before>var nodemcu = nodemcu || {};
(function () {
  'use strict';
  var languageCodeToNameMap = {en: 'English', de: 'Deutsch'};
  var languageNames = values(languageCodeToNameMap);
  var defaultLanguageCode = 'en';

  $(document).ready(function () {
    addToc();
    hideNavigationForAllButSelectedLanguage();
    addLanguageSelectorToRtdFlyOutMenu();
  });

  /**
   * Adds a TOC-style table to each page in the 'Modules' section.
   */
  function addToc() {
    var func, intro, tocHtmlTable;
    if (isModulePage()) {
      tocHtmlTable = '
';
      $('h2').each(function (index) {
        // 'slice' cuts off the single permalink character at the end of the text (e.g. '¶')
        func = $(this).text().slice(0, -1);
        // get the first sentence of the paragraph directly below h2
        intro = $(this).next().text();
        intro = intro.substring(0, intro.indexOf('.') + 1);
        tocHtmlTable += createTocTableRow(func, intro);
      });
      tocHtmlTable += '
';
      $(tocHtmlTable).insertBefore($('h2').first())
    }
    function isModulePage() {
      // if the breadcrumb contains 'Modules »' it must be an API page
      return $("ul.wy-breadcrumbs li:contains('Modules »')").size() > 0;
    }
    function createTocTableRow(func, intro) {
      // fragile attempt to auto-create the in-page anchor
      var href = func.replace(/\./g, '').replace('()', '').replace(' --', '-');
      var link = '' + func + '';
      return '
' + link + '	' + intro + '
';
    }
  }

  function hideNavigationForAllButSelectedLanguage() {
    var selectedLanguageCode = determineSelectedLanguageCode();
    var selectedLanguageName = languageCodeToNameMap[selectedLanguageCode];
    // Finds all subnav elements and hides them if they're /language/ subnavs. Hence, all 'Modules' subnav elements
    // won't be hidden.
    //

    //
Modules

    //

    //     node
    //

    $('.subnav li span').not(':contains(' + selectedLanguageName + ')').each(function (index) {
      var spanElement = $(this);
      if ($.inArray(spanElement.text(), languageNames) > -1) {
        spanElement.parent().parent().hide();
      }
    });
  }

  /**
   * Adds a language selector to the RTD fly-out menu found bottom left. Example:
   *
   *

   *
Languages

   *
<a href="http://nodemcu.readthedocs.org/en/<branch>/de/">de

   *
   *
<a href="http://nodemcu.readthedocs.org/en/<branch>/en/">en

   *
   *

   *
   * UGLY! That fly-out menu is added by RTD with an AJAX call after page load. Hence, we need to
   * react to the subsequent DOM manipulation using a DOM4 MutationObserver. The provided structure
   * is as follows:
   *
   *

   *
   *

   */
  function addLanguageSelectorToRtdFlyOutMenu() {
    var flyOutWrapper = $('.rst-other-versions');
    // only relevant on RTD
    if (flyOutWrapper.size() > 0) {
      var observer = new MutationObserver(function (mutations) {
        // since mutation on the target node was triggered we can safely assume the injected RTD div has now been added
        var injectedDiv = $('.rst-other-versions .injected');
        var selectedLanguageCode = determineSelectedLanguageCode();
        var dl = document.createElement('dl');
        var dt = document.createElement('dt');
        dl.appendChild(dt);
        dt.appendChild(document.createTextNode('Languages'));
        for (var languageCode in languageCodeToNameMap) {
          dl.appendChild(createLanguageLinkFor(languageCode, selectedLanguageCode === languageCode));
        }
        injectedDiv.prepend(dl);
        // no need for that observer anymore
        observer.disconnect();
      });

      // observed target node is the fly-out wrapper, the only event we care about is when children are modified
      observer.observe(flyOutWrapper[0], {childList: true});
    }
  }

  function createLanguageLinkFor(languageCode, isCurrentlySelected) {
    var strong;
    // split[0] is an '' because the path starts with the separator
    var pathSegments = window.location.pathname.split('/');
    var dd = document.createElement("dd");
    var href = document.createElement("a");
    href.setAttribute('href', '/' + pathSegments[1] + '/' + pathSegments[2] + '/' + languageCode);
    href.appendChild(document.createTextNode(languageCode));
    dd.appendChild(href);
    if (isCurrentlySelected) {
      strong = document.createElement("strong");
      strong.appendChild(dd);
      return strong;
    } else {
      return dd;
    }
  }

  /**
   * Analyzes the URL of the current page to find out what the selected language is. It's usually
   * part of the location path. The code needs to distinguish between running MkDocs standalone
   * and docs served from RTD. If no valid language could be determined the default language is
   * returned.
   *
   * @returns 2-char language code
   */
  function determineSelectedLanguageCode() {
    var selectedLanguageCode, path = window.location.pathname;
    if (window.location.origin.indexOf('readthedocs') > -1) {
      // path is like /en/<branch>/<lang>/build/ -> extract 'lang'
      // split[0] is an '' because the path starts with the separator
      selectedLanguageCode = path.split('/')[3];
    } else {
      // path is like /<lang>/build/ -> extract 'lang'
      selectedLanguageCode = path.substr(1, 2);
    }
    if (!selectedLanguageCode || selectedLanguageCode.length > 2) {
      selectedLanguageCode = defaultLanguageCode;
    }
    return selectedLanguageCode;
  }

  function values(associativeArray) {
    var values = [];
    for (var key in associativeArray) {
      if (associativeArray.hasOwnProperty(key)) {
        values.push(associativeArray[key]);
      }
    }
    return values;
  }
}());<commit_msg>Add fix in TOC JavaScript for in-page anchors<commit_after>var nodemcu = nodemcu || {};
(function () {
  'use strict';
  var languageCodeToNameMap = {en: 'English', de: 'Deutsch'};
  var languageNames = values(languageCodeToNameMap);
  var defaultLanguageCode = 'en';

  $(document).ready(function () {
    addToc();
    hideNavigationForAllButSelectedLanguage();
    addLanguageSelectorToRtdFlyOutMenu();
  });

  /**
   * Adds a TOC-style table to each page in the 'Modules' section.
   */
  function addToc() {
    var func, intro, tocHtmlTable;
    if (isModulePage()) {
      tocHtmlTable = '
';
      $('h2').each(function (index) {
        // 'slice' cuts off the single permalink character at the end of the text (e.g. '¶')
        func = $(this).text().slice(0, -1);
        // get the first sentence of the paragraph directly below h2
        intro = $(this).next().text();
        intro = intro.substring(0, intro.indexOf('.') + 1);
        tocHtmlTable += createTocTableRow(func, intro);
      });
      tocHtmlTable += '
';
      $(tocHtmlTable).insertBefore($('h2').first())
    }
    function isModulePage() {
      // if the breadcrumb contains 'Modules »' it must be an API page
      return $("ul.wy-breadcrumbs li:contains('Modules »')").size() > 0;
    }
    function createTocTableRow(func, intro) {
      // fragile attempt to auto-create the in-page anchor
      var href = func.replace(/\.|:/g, '').replace('()', '').replace(' --', '-').replace(/ /g, '-');
      var link = '' + func + '';
      return '
' + link + '	' + intro + '
';
    }
  }

  function hideNavigationForAllButSelectedLanguage() {
    var selectedLanguageCode = determineSelectedLanguageCode();
    var selectedLanguageName = languageCodeToNameMap[selectedLanguageCode];
    // Finds all subnav elements and hides them if they're /language/ subnavs. Hence, all 'Modules' subnav elements
    // won't be hidden.
    //

    //
Modules

    //

    //     node
    //

    $('.subnav li span').not(':contains(' + selectedLanguageName + ')').each(function (index) {
      var spanElement = $(this);
      if ($.inArray(spanElement.text(), languageNames) > -1) {
        spanElement.parent().parent().hide();
      }
    });
  }

  /**
   * Adds a language selector to the RTD fly-out menu found bottom left. Example:
   *
   *

   *
Languages

   *
<a href="http://nodemcu.readthedocs.org/en/<branch>/de/">de

   *
   *
<a href="http://nodemcu.readthedocs.org/en/<branch>/en/">en

   *
   *

   *
   * UGLY! That fly-out menu is added by RTD with an AJAX call after page load. Hence, we need to
   * react to the subsequent DOM manipulation using a DOM4 MutationObserver. The provided structure
   * is as follows:
   *
   *

   *
   *

   */
  function addLanguageSelectorToRtdFlyOutMenu() {
    var flyOutWrapper = $('.rst-other-versions');
    // only relevant on RTD
    if (flyOutWrapper.size() > 0) {
      var observer = new MutationObserver(function (mutations) {
        // since mutation on the target node was triggered we can safely assume the injected RTD div has now been added
        var injectedDiv = $('.rst-other-versions .injected');
        var selectedLanguageCode = determineSelectedLanguageCode();
        var dl = document.createElement('dl');
        var dt = document.createElement('dt');
        dl.appendChild(dt);
        dt.appendChild(document.createTextNode('Languages'));
        for (var languageCode in languageCodeToNameMap) {
          dl.appendChild(createLanguageLinkFor(languageCode, selectedLanguageCode === languageCode));
        }
        injectedDiv.prepend(dl);
        // no need for that observer anymore
        observer.disconnect();
      });

      // observed target node is the fly-out wrapper, the only event we care about is when children are modified
      observer.observe(flyOutWrapper[0], {childList: true});
    }
  }

  function createLanguageLinkFor(languageCode, isCurrentlySelected) {
    var strong;
    // split[0] is an '' because the path starts with the separator
    var pathSegments = window.location.pathname.split('/');
    var dd = document.createElement("dd");
    var href = document.createElement("a");
    href.setAttribute('href', '/' + pathSegments[1] + '/' + pathSegments[2] + '/' + languageCode);
    href.appendChild(document.createTextNode(languageCode));
    dd.appendChild(href);
    if (isCurrentlySelected) {
      strong = document.createElement("strong");
      strong.appendChild(dd);
      return strong;
    } else {
      return dd;
    }
  }

  /**
   * Analyzes the URL of the current page to find out what the selected language is. It's usually
   * part of the location path. The code needs to distinguish between running MkDocs standalone
   * and docs served from RTD. If no valid language could be determined the default language is
   * returned.
   *
   * @returns 2-char language code
   */
  function determineSelectedLanguageCode() {
    var selectedLanguageCode, path = window.location.pathname;
    if (window.location.origin.indexOf('readthedocs') > -1) {
      // path is like /en/<branch>/<lang>/build/ -> extract 'lang'
      // split[0] is an '' because the path starts with the separator
      selectedLanguageCode = path.split('/')[3];
    } else {
      // path is like /<lang>/build/ -> extract 'lang'
      selectedLanguageCode = path.substr(1, 2);
    }
    if (!selectedLanguageCode || selectedLanguageCode.length > 2) {
      selectedLanguageCode = defaultLanguageCode;
    }
    return selectedLanguageCode;
  }

  function values(associativeArray) {
    var values = [];
    for (var key in associativeArray) {
      if (associativeArray.hasOwnProperty(key)) {
        values.push(associativeArray[key]);
      }
    }
    return values;
  }
}());<|endoftext|>


<commit_before><commit_msg>new compiled js file with updated data<commit_after><|endoftext|>


<commit_before>export default class Example1 {

  static createView(context) {

     context.querySelector("div").border = "2px solid green"

    return
This is my View

  }

}<commit_msg>AUTO-COMMIT demos/swd21/pipes-and-filters/example1.js<commit_after>export default class Example1 {

  static createView(context) {

     context.querySelector("div").border = "5px solid green"

    return
This is my View

  }

}<|endoftext|>


<commit_before>"use strict";

/**

 * Module dependencies

 */

/*
*
* Checks if provided parameters for new Project are valid or returns an appropiate response.
* @name
* @description
* @members - optional
*
*/
module.exports.validCreate = function(req, res, next) {
  // validate input parameters
  if (!req.body.name) {
    return res.status(400).json({ errors: { name: 'Por favor ingresa el nombre de tu proyecto.'}});
  }

  if (!req.body.description) {
    return res.status(400).json({ errors: { description: 'Por favor ingresa alguna descripción de tu proyecto.'}});
  }
  next();
}

/*
*
* Checks if provided parameters to update a Project are valid or returns an appropiate response.
* @name
* @description
*
*/

module.exports.validUpdate = function(req, res, next) {
  // validate input parameters
  if (req.body.name) {
    if(req.body.name === ''){
      return res.status(400).json({ errors: { name: 'El nombre provisto no es válido.'}});
    }
  }

  if (req.body.description) {
    if(req.body.description === ''){
      return res.status(400).json({ errors: { description: 'La descripción provista no es válida.'}});
    }
  }
  next();
}

/*
*
* Checks if provided parameters get a Project are valid or returns an appropiate response.
* @id
*
*/
module.exports.validGet = function(req, res, next) {
  // validate input parameters
  if (!req.params.id)  {
        return res.status(400).json({ errors: { all: 'Por favor ingrese los parámetros requeridos.'}});
  }
  next();
}

/*
*
* Checks if provided parameters to send invitations to Project are valid or returns an appropiate response.
* @id
* @addresses
*
*/
module.exports.validNewMembers = function(req, res, next){
  // validate input parameters
  if (!req.params.id || !req.body.addresses)  {
        return res.status(400).json({ errors: { all: 'Por favor ingrese los parámetros requeridos.'}});
  }
  next();
}

/*
*
* Checks if provided parameters to accept project invitations are valid or returns an appropiate response.
*
*
*
*/
module.exports.validAcceptInvitation = function(req, res, next){
  // validate input parameters
  if (!req.body.token)  {
    return res.status(400).json({ errors: { all: 'Por favor ingrese los parámetros requeridos.'}});
  }
  next();
}
<commit_msg>Se agrega validacion de mails de invitados al crear nuevo proyecto<commit_after>"use strict";

/**

 * Module dependencies

 */

/*
*
* Checks if provided parameters for new Project are valid or returns an appropiate response.
* @name
* @description
* @members - optional
*
*/
var validator = require("email-validator");

//Max project name and description text lengths
//should be consts but it's use is not allowed under strict mode... yet.
var NameLenght = 40;
var DescLength = 2000;

module.exports.validCreate = function(req, res, next) {
  var errors = {};
  var hasErrors = false;

  // validate input parameters
  if (!req.body.name && !req.body.description) {
    return res.status(400).json({ errors: { all: 'Por favor completa el nombre y la descripción de tu proyecto.'}});
  }

  if (!req.body.name) {
    errors.name = 'Por favor ingresa el nombre de tu proyecto.';
    hasErrors = true;
  } else if (req.body.name.length > NameLenght) {
    errors.name = 'El nombre de tu proyecto no debe superar los '+NameLenght+' caracteres.';
    hasErrors = true;
  }

  if (!req.body.description) {
    errors.description = 'Por favor ingresa una descripción de tu proyecto.';
    hasErrors = true;
  } else if (req.body.description.length > DescLength) {
    errors.description = 'La descripción de tu proyecto no debe superar los '+DescLength+' caracteres.';
    hasErrors = true;
  }

  if (req.body.members.length > 0) {
    for (var m in req.body.members) {
      if (!validator.validate((req.body.members[m].address))) {
        errors[req.body.members[m].name] = 'Correo inválido';
        hasErrors = true;
      }
    }
  }

  if (hasErrors) {
    return res.status(400).json({ errors: errors });
  }

  next();
}

/*
*
* Checks if provided parameters to update a Project are valid or returns an appropiate response.
* @name
* @description
*
*/

module.exports.validUpdate = function(req, res, next) {
  // validate input parameters
  if (req.body.name) {
    if(req.body.name === ''){
      return res.status(400).json({ errors: { name: 'El nombre provisto no es válido.'}});
    }
  }

  if (req.body.description) {
    if(req.body.description === ''){
      return res.status(400).json({ errors: { description: 'La descripción provista no es válida.'}});
    }
  }
  next();
}

/*
*
* Checks if provided parameters get a Project are valid or returns an appropiate response.
* @id
*
*/
module.exports.validGet = function(req, res, next) {
  // validate input parameters
  if (!req.params.id)  {
        return res.status(400).json({ errors: { all: 'Por favor ingrese los parámetros requeridos.'}});
  }
  next();
}

/*
*
* Checks if provided parameters to send invitations to Project are valid or returns an appropiate response.
* @id
* @addresses
*
*/
module.exports.validNewMembers = function(req, res, next){
  // validate input parameters
  if (!req.params.id || !req.body.addresses)  {
        return res.status(400).json({ errors: { all: 'Por favor ingrese los parámetros requeridos.'}});
  }
  next();
}

/*
*
* Checks if provided parameters to accept project invitations are valid or returns an appropiate response.
*
*
*
*/
module.exports.validAcceptInvitation = function(req, res, next){
  // validate input parameters
  if (!req.body.token)  {
    return res.status(400).json({ errors: { all: 'Por favor ingrese los parámetros requeridos.'}});
  }
  next();
}
<|endoftext|>


<commit_before>// @flow
import React, {Component} from 'react'
import {TextField} from 'material-ui'
import {globalStyles, globalColors, globalColorsDZ2} from '../styles/style-guide'
import {styles as TextStyles} from './text'
import materialTheme from '../styles/material-theme.desktop'

import InputOld from './input.old.desktop'

import type {Props} from './input'

export default class Input extends Component {
  props: Props;
  state: {value: ?string, focused: boolean};
  _textField: any;

  constructor (props: Props) {
    super(props)

    this.state = {
      value: props.value,
      focused: false
    }
  }
  getChildContext (): Object {
    return {
      muiTheme: materialTheme
    }
  }

  getValue (): ?string {
    return this.state.value
  }

  clearValue () {
    this.setState({value: null})
  }

  onChange (event: {target: {value: ?string}}) {
    this.setState({value: event.target.value})
  }

  blur () {
    this._textField && this._textField.blur()
  }

  render () {
    if (!this.props.dz2) {
      return <InputOld {...this.props}/>
    }

    const style = this.props.small ? styles.containerSmall : styles.container
    const textStyle = this.props.small ? styles.inputSmall : styles.input

    // HACK: We can't reset the text area style, so we need to counteract it by moving the wrapper up
    const multiLineStyleFix = {
      height: 'auto', position: 'relative',
      // Other HACK: having a floating label affects position, but only in multiline
      bottom: (this.props.floatingLabelText ? 30 : 5),
      marginTop: 6
    }
    const inputStyle = this.props.multiLine ? multiLineStyleFix : {height: 'auto'}
    return (

        <TextField
          ref={textField => this._textField = textField}
          fullWidth
          inputStyle={inputStyle}
          underlineStyle={{bottom: 'auto'}}
          errorStyle={{...styles.errorStyle, ...this.props.errorStyle}}
          style={{...textStyle, ...globalStyles.flexBoxColumn}}
          autoFocus={this.props.autoFocus}
          errorText={this.props.errorText}
          floatingLabelText={this.props.small ? undefined : this.props.floatingLabelText}
          floatingLabelStyle={{...styles.floatingLabelStyle, ...(this.state.focused ? {color: globalColorsDZ2.blue2} : {})}}
          onFocus={() => this.setState({focused: true})}
          onBlur={() => this.setState({focused: false})}
          hintText={this.props.hintText}
          hintStyle={{...styles.hintStyle, ...(this.props.multiLine ? {textAlign: 'center'} : {top: 3, bottom: 'auto'})}}
          multiLine={this.props.multiLine}
          onChange={event => {
            this.onChange(event)
            this.props.onChange && this.props.onChange(event)
          }}
          onEnterKeyDown={this.props.onEnterKeyDown}
          underlineFocusStyle={styles.underlineFocusStyle}
          rows={this.props.rows}
          rowsMax={this.props.rowsMax}
          type={this.props.type}
          value={this.state.value}
          />

    )
  }
}

Input.childContextTypes = {
  muiTheme: React.PropTypes.object
}

export const styles = {
  container: {
    marginBottom: 8
  },
  containerSmall: {
    margin: 0,
    marginTop: 2
  },
  input: {
    ...TextStyles.textBody
  },
  inputSmall: {
    ...TextStyles.textBody,
    ...TextStyles.textSmallMixin,
    height: 40,
    lineHeight: '11px'
  },
  underlineFocusStyle: {
    borderColor: globalColorsDZ2.blue2,
    transition: ''
  },
  errorStyle: {
    ...globalStyles.DZ2.fontRegular,
    color: globalColors.highRiskWarning,
    alignSelf: 'center',
    fontSize: 13,
    lineHeight: '17px',
    position: 'initial',
    marginTop: 4
  },
  hintStyle: {
    ...globalStyles.DZ2.fontRegular
  },
  floatingLabelStyle: {
    ...globalStyles.DZ2.fontRegular,
    alignSelf: 'center',
    position: 'inherit',
    top: 34
  }
}

<commit_msg>Focus input on click<commit_after>// @flow
import React, {Component} from 'react'
import {TextField} from 'material-ui'
import {globalStyles, globalColors, globalColorsDZ2} from '../styles/style-guide'
import {styles as TextStyles} from './text'
import materialTheme from '../styles/material-theme.desktop'

import InputOld from './input.old.desktop'

import type {Props} from './input'

export default class Input extends Component {
  props: Props;
  state: {value: ?string, focused: boolean};
  _textField: any;

  constructor (props: Props) {
    super(props)

    this.state = {
      value: props.value,
      focused: false
    }
  }
  getChildContext (): Object {
    return {
      muiTheme: materialTheme
    }
  }

  getValue (): ?string {
    return this.state.value
  }

  clearValue () {
    this.setState({value: null})
  }

  onChange (event: {target: {value: ?string}}) {
    this.setState({value: event.target.value})
  }

  blur () {
    this._textField && this._textField.blur()
  }

  render () {
    if (!this.props.dz2) {
      return <InputOld {...this.props}/>
    }

    const style = this.props.small ? styles.containerSmall : styles.container
    const textStyle = this.props.small ? styles.inputSmall : styles.input

    // HACK: We can't reset the text area style, so we need to counteract it by moving the wrapper up
    const multiLineStyleFix = {
      height: 'auto', position: 'relative',
      // Other HACK: having a floating label affects position, but only in multiline
      bottom: (this.props.floatingLabelText ? 30 : 5),
      marginTop: 6
    }
    const inputStyle = this.props.multiLine ? multiLineStyleFix : {height: 'auto'}
    return (

 {this._textField && this._textField.focus()}}>
        <TextField
          ref={textField => this._textField = textField}
          fullWidth
          inputStyle={inputStyle}
          underlineStyle={{bottom: 'auto'}}
          errorStyle={{...styles.errorStyle, ...this.props.errorStyle}}
          style={{...textStyle, ...globalStyles.flexBoxColumn}}
          autoFocus={this.props.autoFocus}
          errorText={this.props.errorText}
          floatingLabelText={this.props.small ? undefined : this.props.floatingLabelText}
          floatingLabelStyle={{...styles.floatingLabelStyle, ...(this.state.focused ? {color: globalColorsDZ2.blue2} : {})}}
          onFocus={() => this.setState({focused: true})}
          onBlur={() => this.setState({focused: false})}
          hintText={this.props.hintText}
          hintStyle={{...styles.hintStyle, ...(this.props.multiLine ? {textAlign: 'center'} : {top: 3, bottom: 'auto'})}}
          multiLine={this.props.multiLine}
          onChange={event => {
            this.onChange(event)
            this.props.onChange && this.props.onChange(event)
          }}
          onEnterKeyDown={this.props.onEnterKeyDown}
          underlineFocusStyle={styles.underlineFocusStyle}
          rows={this.props.rows}
          rowsMax={this.props.rowsMax}
          type={this.props.type}
          value={this.state.value}
          />

    )
  }
}

Input.childContextTypes = {
  muiTheme: React.PropTypes.object
}

export const styles = {
  container: {
    marginBottom: 8
  },
  containerSmall: {
    margin: 0,
    marginTop: 2
  },
  input: {
    ...TextStyles.textBody
  },
  inputSmall: {
    ...TextStyles.textBody,
    ...TextStyles.textSmallMixin,
    height: 40,
    lineHeight: '11px'
  },
  underlineFocusStyle: {
    borderColor: globalColorsDZ2.blue2,
    transition: ''
  },
  errorStyle: {
    ...globalStyles.DZ2.fontRegular,
    color: globalColors.highRiskWarning,
    alignSelf: 'center',
    fontSize: 13,
    lineHeight: '17px',
    position: 'initial',
    marginTop: 4
  },
  hintStyle: {
    ...globalStyles.DZ2.fontRegular
  },
  floatingLabelStyle: {
    ...globalStyles.DZ2.fontRegular,
    alignSelf: 'center',
    position: 'inherit',
    top: 34
  }
}

<|endoftext|>


<commit_before>// @flow
import React, {Component} from 'react'
import {TextField} from 'material-ui'
import {globalStyles, globalColors, globalColorsDZ2} from '../styles/style-guide'
import {styles as TextStyles} from './text'
import materialTheme from '../styles/material-theme.desktop'

import InputOld from './input.old.desktop'

import type {Props} from './input'

export default class Input extends Component {
  props: Props;
  state: {value: ?string, focused: boolean};
  _textField: any;

  constructor (props: Props) {
    super(props)

    this.state = {
      value: props.value,
      focused: false
    }
  }
  getChildContext (): Object {
    return {
      muiTheme: materialTheme
    }
  }

  getValue (): ?string {
    if (!this.props.dz2) {
      return this.refs.inputOld && this.refs.inputOld.getValue()
    }
    return this.state.value
  }

  clearValue () {
    if (!this.props.dz2) {
      this.refs.inputOld && this.refs.inputOld.clearValue()
      return
    }
    this.setState({value: null})
  }

  onChange (event: {target: {value: ?string}}) {
    this.setState({value: event.target.value})
  }

  blur () {
    if (!this.props.dz2) {
      return this.refs.inputOld && this.refs.inputOld.blur()
    }

    this._textField && this._textField.blur()
  }

  render () {
    if (!this.props.dz2) {
      return <InputOld ref="inputOld" {...this.props}/>
    }

    const style = this.props.small ? styles.containerSmall : styles.container
    const textStyle = this.props.small ? styles.inputSmall : styles.input

    // HACK: We can't reset the text area style, so we need to counteract it by moving the wrapper up
    const multiLineStyleFix = {
      height: 'auto', position: 'relative',
      // Other HACK: having a floating label affects position, but only in multiline
      bottom: (this.props.floatingLabelText ? 30 : 5),
      marginTop: 6
    }
    const inputStyle = this.props.multiLine ? multiLineStyleFix : {height: 'auto'}
    return (

 { this._textField && this._textField.focus() }}>
        <TextField
          ref={textField => (this._textField = textField)}
          fullWidth
          inputStyle={{...inputStyle, textAlign: 'center'}}
          underlineStyle={{bottom: 'auto'}}
          errorStyle={{...styles.errorStyle, ...this.props.errorStyle}}
          style={{...textStyle, ...globalStyles.flexBoxColumn}}
          autoFocus={this.props.autoFocus}
          errorText={this.props.errorText}
          floatingLabelText={this.props.small ? undefined : this.props.floatingLabelText}
          floatingLabelStyle={{...styles.floatingLabelStyle, ...(this.state.focused ? {color: globalColorsDZ2.blue} : {})}}
          onFocus={() => this.setState({focused: true})}
          onBlur={() => this.setState({focused: false})}
          hintText={this.props.hintText}
          hintStyle={{...styles.hintStyle, ...(this.props.multiLine ? {textAlign: 'center'} : {top: 3, bottom: 'auto'})}}
          multiLine={this.props.multiLine}
          onChange={event => {
            this.onChange(event)
            this.props.onChange && this.props.onChange(event)
          }}
          onEnterKeyDown={this.props.onEnterKeyDown}
          underlineFocusStyle={styles.underlineFocusStyle}
          rows={this.props.rows}
          rowsMax={this.props.rowsMax}
          type={this.props.type}
          value={this.state.value}
          />

    )
  }
}

Input.childContextTypes = {
  muiTheme: React.PropTypes.object
}

export const styles = {
  container: {
    marginBottom: 8
  },
  containerSmall: {
    margin: 0,
    marginTop: 2
  },
  input: {
    ...TextStyles.textBodyBigSemibold,
    height: 80
  },
  inputSmall: {
    ...TextStyles.textBody,
    ...TextStyles.textSmallMixin,
    height: 40,
    lineHeight: '11px'
  },
  underlineFocusStyle: {
    borderColor: globalColorsDZ2.blue,
    transition: ''
  },
  errorStyle: {
    ...globalStyles.DZ2.fontRegular,
    color: globalColors.highRiskWarning,
    alignSelf: 'center',
    fontSize: 13,
    lineHeight: '17px',
    position: 'initial',
    marginTop: 4
  },
  hintStyle: {
    ...globalStyles.DZ2.fontRegular
  },
  floatingLabelStyle: {
    ...globalStyles.DZ2.fontRegular,
    alignSelf: 'center',
    position: 'inherit',
    top: 34
  }
}
<commit_msg>1px bottom border for TextFields<commit_after>// @flow
import React, {Component} from 'react'
import {TextField} from 'material-ui'
import {globalStyles, globalColors, globalColorsDZ2} from '../styles/style-guide'
import {styles as TextStyles} from './text'
import materialTheme from '../styles/material-theme.desktop'

import InputOld from './input.old.desktop'

import type {Props} from './input'

export default class Input extends Component {
  props: Props;
  state: {value: ?string, focused: boolean};
  _textField: any;

  constructor (props: Props) {
    super(props)

    this.state = {
      value: props.value,
      focused: false
    }
  }
  getChildContext (): Object {
    return {
      muiTheme: materialTheme
    }
  }

  getValue (): ?string {
    if (!this.props.dz2) {
      return this.refs.inputOld && this.refs.inputOld.getValue()
    }
    return this.state.value
  }

  clearValue () {
    if (!this.props.dz2) {
      this.refs.inputOld && this.refs.inputOld.clearValue()
      return
    }
    this.setState({value: null})
  }

  onChange (event: {target: {value: ?string}}) {
    this.setState({value: event.target.value})
  }

  blur () {
    if (!this.props.dz2) {
      return this.refs.inputOld && this.refs.inputOld.blur()
    }

    this._textField && this._textField.blur()
  }

  render () {
    if (!this.props.dz2) {
      return <InputOld ref="inputOld" {...this.props}/>
    }

    const style = this.props.small ? styles.containerSmall : styles.container
    const textStyle = this.props.small ? styles.inputSmall : styles.input

    // HACK: We can't reset the text area style, so we need to counteract it by moving the wrapper up
    const multiLineStyleFix = {
      height: 'auto', position: 'relative',
      // Other HACK: having a floating label affects position, but only in multiline
      bottom: (this.props.floatingLabelText ? 30 : 5),
      marginTop: 6
    }
    const inputStyle = this.props.multiLine ? multiLineStyleFix : {height: 'auto'}
    return (

 { this._textField && this._textField.focus() }}>
        <TextField
          ref={textField => (this._textField = textField)}
          fullWidth
          inputStyle={{...inputStyle, textAlign: 'center'}}
          underlineStyle={{bottom: 'auto'}}
          errorStyle={{...styles.errorStyle, ...this.props.errorStyle}}
          style={{...textStyle, ...globalStyles.flexBoxColumn}}
          autoFocus={this.props.autoFocus}
          errorText={this.props.errorText}
          floatingLabelText={this.props.small ? undefined : this.props.floatingLabelText}
          floatingLabelStyle={{...styles.floatingLabelStyle, ...(this.state.focused ? {color: globalColorsDZ2.blue} : {})}}
          onFocus={() => this.setState({focused: true})}
          onBlur={() => this.setState({focused: false})}
          hintText={this.props.hintText}
          hintStyle={{...styles.hintStyle, ...(this.props.multiLine ? {textAlign: 'center'} : {top: 3, bottom: 'auto'})}}
          multiLine={this.props.multiLine}
          onChange={event => {
            this.onChange(event)
            this.props.onChange && this.props.onChange(event)
          }}
          onEnterKeyDown={this.props.onEnterKeyDown}
          underlineFocusStyle={styles.underlineFocusStyle}
          rows={this.props.rows}
          rowsMax={this.props.rowsMax}
          type={this.props.type}
          value={this.state.value}
          />

    )
  }
}

Input.childContextTypes = {
  muiTheme: React.PropTypes.object
}

export const styles = {
  container: {
    marginBottom: 8
  },
  containerSmall: {
    margin: 0,
    marginTop: 2
  },
  input: {
    ...TextStyles.textBodyBigSemibold,
    height: 80
  },
  inputSmall: {
    ...TextStyles.textBody,
    ...TextStyles.textSmallMixin,
    height: 40,
    lineHeight: '11px'
  },
  underlineFocusStyle: {
    borderColor: globalColorsDZ2.blue,
    borderBottom: 'solid 1px',
    transition: ''
  },
  errorStyle: {
    ...globalStyles.DZ2.fontRegular,
    color: globalColors.highRiskWarning,
    alignSelf: 'center',
    fontSize: 13,
    lineHeight: '17px',
    position: 'initial',
    marginTop: 4
  },
  hintStyle: {
    ...globalStyles.DZ2.fontRegular
  },
  floatingLabelStyle: {
    ...globalStyles.DZ2.fontRegular,
    alignSelf: 'center',
    position: 'inherit',
    top: 34
  }
}
<|endoftext|>


<commit_before>/* @flow */

import React, {Component} from 'react'
import {FlatButton} from 'material-ui'
import {Button} from '../common-adapters'
import commonStyles from '../styles/common'
import {globalColors} from '../styles/style-guide'
import {normal, checking, warning} from '../constants/tracker'
import flags from '../util/feature-flags'

import type {ActionProps} from './action.render'

export default class ActionRender extends Component {
  props: ActionProps;

  render (): ReactElement {
    if (flags.tracker2) {
      return this.render2()
    }
    return this.renderDefault()
  }

  renderDefault (): ReactElement {
    const {username, state, loggedIn} = this.props
    const styles = styles1

    if (!loggedIn) {
      return this.renderLoggedOut(styles)
    } else if (state === checking || !username) {
      return this.renderPending(styles)
    } else if (this.props.state === normal) {
      return this.renderNormal(styles, username)
    } else if (this.props.currentlyFollowing) {
      return this.renderChanged(styles)
    } else {
      return this.renderWarningNotFollowed(styles)
    }
  }

  render2 (): ReactElement {
    const styles = styles2
    return (

        <Button label='Close' onClick={() => this.props.onClose()} />

    )
  }

  renderPending (styles: Object): ReactElement {
    return (

 Loading...

    )
  }

  renderWarningNotFollowed (styles: Object): ReactElement {
    const title = this.props.failedProofsNotFollowingText

    return (

          {title}

 this.props.onFollowChecked(!this.props.shouldFollow)}>
          <i style={styles.check} className={`fa ${this.props.shouldFollow ? 'fa-check-square-o' : 'fa-square-o'}`}>
          Track

        <FlatButton style={commonStyles.primaryButton} label='Close' primary onClick={() => this.props.onMaybeTrack()} />

    )
  }

  renderChanged (styles: Object): ReactElement {
    const title = this.props.renderChangedTitle

    return (

          {title && {title}}

        <FlatButton style={commonStyles.secondaryButton} label='Untrack' onClick={() => this.props.onUnfollow()} />
        <FlatButton style={commonStyles.primaryButton} label='Retrack' primary onClick={() => this.props.onRefollow()} />

    )
  }

  renderNormal (styles: any, username: string): ReactElement {
    return (

          You'll see this card every time you access the folder.

 this.props.onFollowChecked(!this.props.shouldFollow)}>
          <i style={styles.check} className={`fa ${this.props.shouldFollow ? 'fa-check-square-o' : 'fa-square-o'}`}>
          Track

        <FlatButton style={commonStyles.primaryButton} label='Close' primary onClick={() => this.props.onMaybeTrack()} />

    )
  }

  renderLoggedOut (styles: Object): ReactElement {
    return (

          You should keybase login or keybase signup from the terminal for more options.

        <FlatButton style={commonStyles.primaryButton} label='Close' primary onClick={() => this.props.onClose()} />

    )
  }
}

ActionRender.propTypes = {
  state: React.PropTypes.any.isRequired,
  loggedIn: React.PropTypes.bool.isRequired,
  username: React.PropTypes.string,
  shouldFollow: React.PropTypes.bool.isRequired,
  onClose: React.PropTypes.func.isRequired,
  onMaybeTrack: React.PropTypes.func.isRequired,
  onRefollow: React.PropTypes.func.isRequired,
  onUnfollow: React.PropTypes.func.isRequired,
  onFollowChecked: React.PropTypes.func.isRequired,
  renderChangedTitle: React.PropTypes.string,
  failedProofsNotFollowingText: React.PropTypes.string.isRequired,
  currentlyFollowing: React.PropTypes.bool.isRequired
}

const styles1 = {
  normalContainer: {
    ...commonStyles.flexBoxRow,
    ...commonStyles.noSelect,
    alignItems: 'center',
    backgroundColor: 'white',
    justifyContent: 'flex-end',
    paddingLeft: 15,
    paddingRight: 15,
    height: 56
  },
  textContainer: {
    ...commonStyles.flexBoxRow,
    justifyContent: 'center',
    marginRight: 15,
    flex: 1,
    fontSize: 13,
    lineHeight: '17px'
  },
  youShouldFollow: {
    color: '#858596',
    maxWidth: 182,
    textAlign: 'center'
  },
  changedMessage: {
    ...commonStyles.fontBold,
    color: '#4444',
    textAlign: 'center'
  },
  command: {
    fontFamily: 'Courier',
    color: '#5D86B4',
    textAlign: 'center'
  },
  checkContainer: {
    ...commonStyles.clickable
  },
  check: {
    marginRight: 3,
    width: 17
  },
  track: {
    color: '#444444',
    fontSize: 15,
    marginRight: 3
  },
  eye: {
    color: '#444444',
    marginRight: 17,
    width: 14
  },
  flagWarning: {
    color: '#f5a623',
    width: 20
  },
  flagError: {
    color: '#d0021b',
    width: 20
  }
}

const styles2 = {
  container: {
    ...commonStyles.flexBoxRow,
    ...commonStyles.noSelect,
    backgroundColor: globalColors.white,
    opacity: 0.9,
    width: '100%',
    height: 61,
    boxShadow: '0px 0px 3px rgba(0, 0, 0, 0.15)',
    alignItems: 'center',
    justifyContent: 'flex-end',
    paddingTop: 15,
    paddingBottom: 18,
    paddingRight: 15,
    position: 'relative',
    zIndex: 1
  }
}
<commit_msg>Update styling for loading state in tracker/actionbar<commit_after>/* @flow */

import React, {Component} from 'react'
import {FlatButton} from 'material-ui'
import {Button} from '../common-adapters'
import commonStyles from '../styles/common'
import {globalColors} from '../styles/style-guide'
import {normal, checking, warning} from '../constants/tracker'
import flags from '../util/feature-flags'
import {Text} from '../common-adapters'

import type {ActionProps} from './action.render'

export default class ActionRender extends Component {
  props: ActionProps;

  render (): ReactElement {
    if (flags.tracker2) {
      return this.render2()
    }
    return this.renderDefault()
  }

  renderDefault (): ReactElement {
    const {username, state, loggedIn} = this.props
    const styles = styles1

    if (!loggedIn) {
      return this.renderLoggedOut(styles)
    } else if (state === checking || !username) {
      return this.renderPending(styles, username)
    } else if (this.props.state === normal) {
      return this.renderNormal(styles, username)
    } else if (this.props.currentlyFollowing) {
      return this.renderChanged(styles)
    } else {
      return this.renderWarningNotFollowed(styles)
    }
  }

  render2 (): ReactElement {
    const styles = styles2
    return (

        <Button label='Close' onClick={() => this.props.onClose()} />

    )
  }

  renderPending (styles: Object, username: ?string): ReactElement {
    const text: string = username ? `Verifying ${username}'s identity` : `Loading tracker information...`
    return (

<Text style={{textAlign: 'center', paddingTop: 8}} type='Body'>{text}</Text>

    )
  }

  renderWarningNotFollowed (styles: Object): ReactElement {
    const title = this.props.failedProofsNotFollowingText

    return (

          {title}

 this.props.onFollowChecked(!this.props.shouldFollow)}>
          <i style={styles.check} className={`fa ${this.props.shouldFollow ? 'fa-check-square-o' : 'fa-square-o'}`}>
          Track

        <FlatButton style={commonStyles.primaryButton} label='Close' primary onClick={() => this.props.onMaybeTrack()} />

    )
  }

  renderChanged (styles: Object): ReactElement {
    const title = this.props.renderChangedTitle

    return (

          {title && {title}}

        <FlatButton style={commonStyles.secondaryButton} label='Untrack' onClick={() => this.props.onUnfollow()} />
        <FlatButton style={commonStyles.primaryButton} label='Retrack' primary onClick={() => this.props.onRefollow()} />

    )
  }

  renderNormal (styles: any, username: string): ReactElement {
    return (

          You'll see this card every time you access the folder.

 this.props.onFollowChecked(!this.props.shouldFollow)}>
          <i style={styles.check} className={`fa ${this.props.shouldFollow ? 'fa-check-square-o' : 'fa-square-o'}`}>
          Track

        <FlatButton style={commonStyles.primaryButton} label='Close' primary onClick={() => this.props.onMaybeTrack()} />

    )
  }

  renderLoggedOut (styles: Object): ReactElement {
    return (

          You should keybase login or keybase signup from the terminal for more options.

        <FlatButton style={commonStyles.primaryButton} label='Close' primary onClick={() => this.props.onClose()} />

    )
  }
}

ActionRender.propTypes = {
  state: React.PropTypes.any.isRequired,
  loggedIn: React.PropTypes.bool.isRequired,
  username: React.PropTypes.string,
  shouldFollow: React.PropTypes.bool.isRequired,
  onClose: React.PropTypes.func.isRequired,
  onMaybeTrack: React.PropTypes.func.isRequired,
  onRefollow: React.PropTypes.func.isRequired,
  onUnfollow: React.PropTypes.func.isRequired,
  onFollowChecked: React.PropTypes.func.isRequired,
  renderChangedTitle: React.PropTypes.string,
  failedProofsNotFollowingText: React.PropTypes.string.isRequired,
  currentlyFollowing: React.PropTypes.bool.isRequired
}

const styles1 = {
  normalContainer: {
    ...commonStyles.flexBoxRow,
    ...commonStyles.noSelect,
    alignItems: 'center',
    backgroundColor: 'white',
    justifyContent: 'flex-end',
    paddingLeft: 15,
    paddingRight: 15,
    height: 56
  },
  textContainer: {
    ...commonStyles.flexBoxRow,
    justifyContent: 'center',
    marginRight: 15,
    flex: 1,
    fontSize: 13,
    lineHeight: '17px'
  },
  youShouldFollow: {
    color: '#858596',
    maxWidth: 182,
    textAlign: 'center'
  },
  changedMessage: {
    ...commonStyles.fontBold,
    color: '#4444',
    textAlign: 'center'
  },
  command: {
    fontFamily: 'Courier',
    color: '#5D86B4',
    textAlign: 'center'
  },
  checkContainer: {
    ...commonStyles.clickable
  },
  check: {
    marginRight: 3,
    width: 17
  },
  track: {
    color: '#444444',
    fontSize: 15,
    marginRight: 3
  },
  eye: {
    color: '#444444',
    marginRight: 17,
    width: 14
  },
  flagWarning: {
    color: '#f5a623',
    width: 20
  },
  flagError: {
    color: '#d0021b',
    width: 20
  }
}

const styles2 = {
  container: {
    ...commonStyles.flexBoxRow,
    ...commonStyles.noSelect,
    backgroundColor: globalColors.white,
    opacity: 0.9,
    width: '100%',
    height: 61,
    boxShadow: '0px 0px 3px rgba(0, 0, 0, 0.15)',
    alignItems: 'center',
    justifyContent: 'flex-end',
    paddingTop: 15,
    paddingBottom: 18,
    paddingRight: 15,
    position: 'relative',
    zIndex: 1
  }
}
<|endoftext|>


<commit_before>---
yuiCompress: !!bool false
---
(function($, window, document) {

        /**
         * jQuery event handler that should be triggered when navigating has
         * completed ('denvelop-navigated' event). This will animate some icons.
         */
    var animate = function(event, prevPage, newPage) {
            // stop spinning the cog-wheel and hide it
            gearRotating = false;
            // show the icon of the new page
            if (prevPage.id === newPage.id) {
                var icon = $('#nav-icon-' + newPage.id);
                if (icon.is(':animated')) {
                    icon.data('stop-hiding', true);
                } else {
                    setIconVisible(newPage.id, true);
                }
            } else {
                setIconVisible(newPage.id, true);
            }
        },
        /**
         * jQuery event handler that should be triggered when navigating starts
         * ('denvelop-navigating' event). This will show a spinning cog-wheel.
         */
        animateLoading = function(event, page) {
            // start spinning the cog-wheel and show it
            gearRotating = true;
            rotateSomewhat();
            gearObj.stop().animate({'top': 0}, 150);
            // hide the icon of the current page
            setIconVisible(page.id, false);
        },
        gear = null,
        gearObj = null,
        gearRotating = false,
        rotateSomewhat = function() {
            gear.stop()
                .attr({'transform': 'rotate(0 80 96)'})
                .animate({'transform': 'r45,80,96'}, 1000, function() {
                    if (gearRotating) {
                        // reset transformation and repeat it (so it looks infinite)
                        gear.attr({'transform': 'rotate(0 80 96)'});
                        rotateSomewhat();
                    } else {
                        // stop, but keep it spinning while it goes down
                        gear.stop()
                            .attr({'transform': 'rotate(0 80 96)'})
                            .animate({'transform': 'r45,80,96'}, 1000);
                        gearObj.stop().animate({'top': '20%'}, 150);
                    }
                });
        },
        /**
         * Show or hide a navigation icon.
         */
        setIconVisible = function(id, visible) {
            $('#nav-icon-' + id).css('display', 'block').stop().animate({
                'top': (visible ? '-50%' : '-100%'),
                'left': (visible ? '-8%' : '8%')
            }, function() {
                var icon = $(this);
                if (icon.data('stop-hiding') && !visible) {
                    icon.removeData('stop-hiding');
                    visible = true;
                }
                icon.css('z-index', (visible ? 7 : 2));
                if (!visible) {
                    icon.delay(200);
                }
                icon.animate({
                    'top': (visible ? '15%' : '28%'),
                    'left': (visible ? '15%' : '0%')
                }, function() {
                    icon.css('z-index', '');
                    icon.toggleClass('active', visible);
                    // maybe, the opposite needs to happen now
                    if (icon.data('stop-hiding') && !visible) {
                        icon.removeData('stop-hiding');
                        setIconVisible(id, true);
                    }
                });
            });
        },
        /**
         * Function that splits the envelope SVG in a foreground and background,
         * so that icons can be put 'in' the envelope.
         */
        splitEnvelope = function() {
            var bgWrapper = $('#envelope');
            svgObjOnLoad(bgWrapper, splitEnvelopeOnLoad);

            // append a margin element to cover icons sticking out of the bottom
            // of the envelope
            var marginEl = $('<div />');
            marginEl.css({
                'position': 'absolute',
                'top': parseInt(bgWrapper.css('marginTop'))
                        + bgWrapper.height(),
                'right': 0,
                'bottom': 0,
                'left': 0,
                'z-index': 4,
                'background': $('#header').css('background-color')
            });
            $('#logo').append(marginEl);
        },
        /**
         * Called when the envelope SVG element loads.
         */
        splitEnvelopeOnLoad = function() {
            if ($(this).data('loaded')) {
                return;
            }

            $(this).data('loaded', true);
            var bg = Snap(this),
                fgWrapper = $(this).clone();
            fgWrapper.addClass('logo-layer-fg')
                .on('load', function() {
                    var fg = Snap(fgWrapper.get(0));
                    fg.selectAll('path:not(:last-child)').remove();
                    bg.selectAll('path:last-child').remove();
                    // now show the gear icon, that is covered by the envelope fg
                    gearObj.css({'display': 'block', 'top': '20%'});
                })
                .appendTo($('#logo'));
        },
        /**
         * Called when the gear SVG element loads.
         */
        gearOnLoad = function() {
            if (gear === null) {
                gear = Snap(this).select('g');
            }
        },
        /**
         * Attach an onload event listener to an object element.
         * This works in both Chrome and Firefox.
         */
        svgObjOnLoad = function(obj, onLoad, onLoadParams) {
            if (typeof(onLoadParams) === 'undefined') {
                onLoadParams = [];
            }

            obj.on('load', onLoad);
            var objEl = obj.get(0);
            if (typeof(objEl.contentDocument) !== 'undefined' &&
                    objEl.contentDocument !== null &&
                    objEl.contentDocument.readyState === 'complete' &&
                    objEl.contentDocument.getElementsByTagName('svg').length > 0) {
                onLoad.apply(objEl, onLoadParams);
            }
        };

    $(function() {
        // make gear icon globally available for easy access
        gearObj = $('#loading-gear');
        svgObjOnLoad(gearObj, gearOnLoad);
        // split the envelope icon in parts, so that we can move icons in and
        // out of the envelope easily and also add a margin element that covers
        // the gear when it moves out of the envelope (and other icons too)
        splitEnvelope();
        // show navigation icon
        $('.nav-icon.active').css('display', 'block');
        // bind to the custom event that is fired as soon as a navigation link
        // is clicked and intercepted, but the page must still be loaded
        $(window).on('denvelop-navigating', animateLoading);
        // bind to the custom event that is fired when navigation is changed
        // and the event could be intercepted and handled using JS
        $(window).on('denvelop-navigated', animate);
    });

}(jQuery, window, document));
<commit_msg>Fix for icon loading (in Chrome?).<commit_after>---
yuiCompress: !!bool false
---
(function($, window, document) {

        /**
         * jQuery event handler that should be triggered when navigating has
         * completed ('denvelop-navigated' event). This will animate some icons.
         */
    var animate = function(event, prevPage, newPage) {
            // stop spinning the cog-wheel and hide it
            gearRotating = false;
            // show the icon of the new page
            if (prevPage.id === newPage.id) {
                var icon = $('#nav-icon-' + newPage.id);
                if (icon.is(':animated')) {
                    icon.data('stop-hiding', true);
                } else {
                    setIconVisible(newPage.id, true);
                }
            } else {
                setIconVisible(newPage.id, true);
            }
        },
        /**
         * jQuery event handler that should be triggered when navigating starts
         * ('denvelop-navigating' event). This will show a spinning cog-wheel.
         */
        animateLoading = function(event, page) {
            // start spinning the cog-wheel and show it
            gearRotating = true;
            rotateSomewhat();
            gearObj.stop().animate({'top': 0}, 150);
            // hide the icon of the current page
            setIconVisible(page.id, false);
        },
        gear = null,
        gearObj = null,
        gearRotating = false,
        rotateSomewhat = function() {
            gear.stop()
                .attr({'transform': 'rotate(0 80 96)'})
                .animate({'transform': 'r45,80,96'}, 1000, function() {
                    if (gearRotating) {
                        // reset transformation and repeat it (so it looks infinite)
                        gear.attr({'transform': 'rotate(0 80 96)'});
                        rotateSomewhat();
                    } else {
                        // stop, but keep it spinning while it goes down
                        gear.stop()
                            .attr({'transform': 'rotate(0 80 96)'})
                            .animate({'transform': 'r45,80,96'}, 1000);
                        gearObj.stop().animate({'top': '20%'}, 150);
                    }
                });
        },
        /**
         * Show or hide a navigation icon.
         */
        setIconVisible = function(id, visible) {
            $('#nav-icon-' + id).stop().animate({
                'top': (visible ? '-50%' : '-100%'),
                'left': (visible ? '-8%' : '8%')
            }, function() {
                var icon = $(this);
                if (icon.data('stop-hiding') && !visible) {
                    icon.removeData('stop-hiding');
                    visible = true;
                }
                icon.css('z-index', (visible ? 7 : 2));
                if (!visible) {
                    icon.delay(200);
                }
                icon.animate({
                    'top': (visible ? '15%' : '28%'),
                    'left': (visible ? '15%' : '0%')
                }, function() {
                    icon.css('z-index', '');
                    icon.toggleClass('active', visible);
                    // maybe, the opposite needs to happen now
                    if (icon.data('stop-hiding') && !visible) {
                        icon.removeData('stop-hiding');
                        setIconVisible(id, true);
                    }
                });
            });
        },
        /**
         * Function that splits the envelope SVG in a foreground and background,
         * so that icons can be put 'in' the envelope.
         */
        splitEnvelope = function() {
            var bgWrapper = $('#envelope');
            svgObjOnLoad(bgWrapper, splitEnvelopeOnLoad);

            // append a margin element to cover icons sticking out of the bottom
            // of the envelope
            var marginEl = $('<div />');
            marginEl.css({
                'position': 'absolute',
                'top': parseInt(bgWrapper.css('marginTop'))
                        + bgWrapper.height(),
                'right': 0,
                'bottom': 0,
                'left': 0,
                'z-index': 4,
                'background': $('#header').css('background-color')
            });
            $('#logo').append(marginEl);
        },
        /**
         * Called when the envelope SVG element loads.
         */
        splitEnvelopeOnLoad = function() {
            if ($(this).data('loaded')) {
                return;
            }

            $(this).data('loaded', true);
            var bg = Snap(this),
                fgWrapper = $(this).clone();
            fgWrapper.addClass('logo-layer-fg')
                .on('load', function() {
                    var fg = Snap(fgWrapper.get(0));
                    fg.selectAll('path:not(:last-child)').remove();
                    bg.selectAll('path:last-child').remove();
                    // now show the gear icon, that is covered by the envelope fg
                    gearObj.css({'display': 'block', 'top': '20%'});
                    // and show the other navigation icons
                    $('.nav-icon').css('display', 'block');
                })
                .appendTo($('#logo'));
        },
        /**
         * Called when the gear SVG element loads.
         */
        gearOnLoad = function() {
            if (gear === null) {
                gear = Snap(this).select('g');
            }
        },
        /**
         * Attach an onload event listener to an object element.
         * This works in both Chrome and Firefox.
         */
        svgObjOnLoad = function(obj, onLoad, onLoadParams) {
            if (typeof(onLoadParams) === 'undefined') {
                onLoadParams = [];
            }

            obj.on('load', onLoad);
            var objEl = obj.get(0);
            if (typeof(objEl.contentDocument) !== 'undefined' &&
                    objEl.contentDocument !== null &&
                    objEl.contentDocument.readyState === 'complete' &&
                    objEl.contentDocument.getElementsByTagName('svg').length > 0) {
                onLoad.apply(objEl, onLoadParams);
            }
        };

    $(function() {
        // make gear icon globally available for easy access
        gearObj = $('#loading-gear');
        svgObjOnLoad(gearObj, gearOnLoad);
        // split the envelope icon in parts, so that we can move icons in and
        // out of the envelope easily and also add a margin element that covers
        // the gear when it moves out of the envelope (and other icons too)
        splitEnvelope();
        // show navigation icon
        $('.nav-icon.active').css('display', 'block');
        // bind to the custom event that is fired as soon as a navigation link
        // is clicked and intercepted, but the page must still be loaded
        $(window).on('denvelop-navigating', animateLoading);
        // bind to the custom event that is fired when navigation is changed
        // and the event could be intercepted and handled using JS
        $(window).on('denvelop-navigated', animate);
    });

}(jQuery, window, document));
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var islogedin = false;
var routes = require('./routes/index.js');
var users = require('./routes/users.js');
var request = require('request');
var app = express();
var session = require('express-session');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/', routes);
var fs = require('fs');
var path = require('path');

app.use(express.static(__dirname + '/Saves_bin'));

app.use("/avatars", express.static(__dirname + '/avatars'));

app.get('/', function (req, res) {
var sess = req.session;
console.log(islogedin);
  res.redirect('http://localhost:3000');
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

var port = process.env.PORT || 3000;

app.listen(port, function () {
  console.log('Server listening at port %d', port);
});

module.exports = app;
<commit_msg>Some fixes<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var islogedin = false;
var routes = require('./routes/index.js');
var users = require('./routes/users.js');
var request = require('request');
var app = express();
var session = require('express-session');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/', routes);
var fs = require('fs');

app.use(express.static(__dirname + '/Saves_bin'));

app.use('/avatars', express.static(__dirname + '/avatars'));

app.get('/', function (req, res) {
var sess = req.session;
console.log(islogedin);
  res.redirect('http://localhost:3000');
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

var port = process.env.PORT || 3000;

app.listen(port, function () {
  console.log('Server listening at port %d', port);
});

module.exports = app;
<|endoftext|>


<commit_before>/**
 * @class  	Trimethyl
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

Ti.Trimethyl = true;
Alloy.CFG.T = Alloy.CFG.T || {};

///////////////////////
// Framework loaders //
///////////////////////

Alloy.Globals.Trimethyl = {

	loadDriver: function(parent, child, interface) {
		var sub = require('T/'+parent+'/'+child);
		if (sub == null) {
			Ti.API.warn("Trimethyl: Unable to load driver <" + child + "> of class <" + parent + ">");
		}

		return _.extend({}, interface, sub);
	}

};

////////////////////////////
// Alloy Globals Contants //
////////////////////////////

Alloy.Globals.SCREEN_WIDTH = OS_IOS ? Ti.Platform.displayCaps.platformWidth : Ti.Platform.displayCaps.platformWidth/Ti.Platform.displayCaps.logicalDensityFactor;
Alloy.Globals.SCREEN_HEIGHT = OS_IOS ? Ti.Platform.displayCaps.platformHeight : Ti.Platform.displayCaps.platformHeight/Ti.Platform.displayCaps.logicalDensityFactor;
Alloy.Globals.SCREEN_DENSITY = OS_ANDROID ? Ti.Platform.displayCaps.logicalDensityFactor : Titanium.Platform.displayCaps.dpi/160;
Alloy.Globals.SIMULATOR = Ti.Platform.model === 'Simulator' || Ti.Platform.model.indexOf('sdk') !== -1;

Alloy.Globals.SCREEN_RETINA = Alloy.Globals.SCREEN_DENSITY == 2;
Alloy.Globals.IOS7 = OS_IOS && Ti.Platform.version.split('.')[0] == 7;
Alloy.Globals.IOS8 = OS_IOS && Ti.Platform.version.split('.')[0] == 8;

//////////////////////////
// Global App Listeners //
//////////////////////////

Ti.App.addEventListener('openURL', function(e){
	Ti.Platform.openURL(e.url);
});<commit_msg>deep clone<commit_after>/**
 * @class  	Trimethyl
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

Ti.Trimethyl = true;
Alloy.CFG.T = Alloy.CFG.T || {};

///////////////////////
// Framework loaders //
///////////////////////

Alloy.Globals.Trimethyl = {

	loadDriver: function(parent, child, interface) {
		var sub = require('T/'+parent+'/'+child);
		if (sub == null) {
			Ti.API.warn("Trimethyl: Unable to load driver <" + child + "> of class <" + parent + ">");
		}

		return _.extend({}, interface, sub);
	}

};

////////////////////////////
// Alloy Globals Contants //
////////////////////////////

Alloy.Globals.SCREEN_WIDTH = OS_IOS ? Ti.Platform.displayCaps.platformWidth : Ti.Platform.displayCaps.platformWidth/Ti.Platform.displayCaps.logicalDensityFactor;
Alloy.Globals.SCREEN_HEIGHT = OS_IOS ? Ti.Platform.displayCaps.platformHeight : Ti.Platform.displayCaps.platformHeight/Ti.Platform.displayCaps.logicalDensityFactor;
Alloy.Globals.SCREEN_DENSITY = OS_ANDROID ? Ti.Platform.displayCaps.logicalDensityFactor : Titanium.Platform.displayCaps.dpi/160;
Alloy.Globals.SIMULATOR = Ti.Platform.model === 'Simulator' || Ti.Platform.model.indexOf('sdk') !== -1;

Alloy.Globals.SCREEN_RETINA = Alloy.Globals.SCREEN_DENSITY == 2;
Alloy.Globals.IOS7 = OS_IOS && Ti.Platform.version.split('.')[0] == 7;
Alloy.Globals.IOS8 = OS_IOS && Ti.Platform.version.split('.')[0] == 8;

//////////////////////////
// Global App Listeners //
//////////////////////////

Ti.App.addEventListener('openURL', function(e){
	Ti.Platform.openURL(e.url);
});

/////////////////////////////////////////////
// Extend underscore with awesome features //
/////////////////////////////////////////////

_.mixin({
	deepClone: function(object) {
		var clone = _.clone(object);
		_.each(clone, function(value, key) {
			if (_.isObject(value)) {
				clone[key] = _.deepClone(value);
			}
		});
		return clone;
	}
});<|endoftext|>


<commit_before>depthFirstSearch.js
<commit_msg>add solution<commit_after>// How do you implement Breadth First Search

function dfs(node){
  if(node){
    console.log(node.value);
    dfs(node.left);
    dfs(node.right);
  }
}
<|endoftext|>


<commit_before>core.Class("core.mvc.store.Abstract",
{
  include: [core.property.MGeneric, core.event.MEventTarget, core.util.MLogging],

  construct : function(path, config)
  {
    this.__activityTracker =
    {
      load : 0,
      save : 0,
      remove : 0,
      create : 0
    };

    if (!config) {
      config = {};
    }

    this.__path = path;

    var saveDebounce = config.saveDebounce || config.debounce || 0;
    this.save = core.util.Function.debounce(this.save, saveDebounce);

    var loadDebounce = config.loadDebounce || config.debounce || 0;
    this.load = core.util.Function.debounce(this.load, loadDebounce);

    var removeDebounce = config.removeDebounce || config.debounce || 0;
    this.remove = core.util.Function.debounce(this.remove, removeDebounce);

    var createDebounce = config.createDebounce || config.debounce || 0;
    this.create = core.util.Function.debounce(this.create, createDebounce);
  },

  events :
  {
    loading : core.event.Simple,
    loaded : core.event.Simple,

    saving : core.event.Simple,
    saved : core.event.Simple,

    creating : core.event.Simple,
    created : core.event.Simple,

    deleting : core.event.Simple,
    deleted : core.event.Simple,

    active : core.event.Simple,
    inactive : core.event.Simple
  },

  members :
  {
    /**
     * {String} Returns the REST communication path.
     */
    getPath : function() {
      return this.__path;
    },

    /**
     * {Boolean} Whether there are currently any requests running.
     */
    isActive : function()
    {
      var tracker = this.__activityTracker;
      return tracker.load > 0 || tracker.save > 0 || tracker.remove > 0 || tracker.create > 0;
    },

    /**
     * {Boolean} Whether there are currently requests active for loading data/entries.
     */
    isLoading : function() {
      return this.__activityTracker.load > 0;
    },

    /**
     * {Boolean} Whether there are currently requests active for saving data/entries.
     */
    isSaving : function() {
      return this.__activityTracker.save > 0;
    },

    /**
     * {Boolean} Whether there are currently requests active for removing data/entries.
     */
    isRemoving : function() {
      return this.__activityTracker.remove > 0;
    },

    /**
     * {Boolean} Whether there are currently requests active for creating data/entries.
     */
    isCreating : function() {
      return this.__activityTracker.create > 0;
    },

    /*
    ======================================================
      ABSTRACT METHOD/STUBS
    ======================================================
    */

    /**
     * Requests data with the given @action {String} and the optional
     * @config {Map}.
     */
    _request : function(action, config) {
      throw new Error("_request() is abstract!");
    },

    /**
     * Applying correction on outgoing @data {var}, typically the model/collection
     * for the given @type {String} of transaction.
     */
    _encode : function(data, type) {
      return data;
    },

    /**
     * Applying correction on incoming @data {var} as the result of
     * the given @type {String} of transaction.
     */
    _decode : function(data, type) {
      return data;
    },

    /*
    ======================================================
      ACTIVITY TRACKING
    ======================================================
    */

    /** {=Map} Keeping track of individual activities */
    __activityTracker : null,

    /**
     * Increments the counter for given @activity {String}.
     */
    __increaseActive : function(activity)
    {
      var wasActive = this.isActive();

      this.__activityTracker[activity]++;
      this.log("ACTIVITY TRACK: ", this.__activityTracker);

      if (!wasActive) {
        this.fireEvent("active");
      }
    },

    /**
     * Decrements the counter for given @activity {String}.
     */
    __decreaseActive : function(activity)
    {
      this.__activityTracker[activity]--;
      this.log("ACTIVITY TRACK: ", this.__activityTracker);

      if (!this.isActive()) {
        this.fireEvent("inactive");
      }
    },

    /*
    ======================================================
      ACTION :: SAVE
    ======================================================
    */

    /**
     * Saves the given @data {var}.
     */
    save : function(data)
    {
      this.__increaseActive("save");
      this.fireEvent("saving");
      this._request("save",
      {
        data : this._encode(data),
        success : this.__onSaveSucceeded,
        failed : this.__onSaveFailed
      });
    },

    // Internal event handler
    __onSaveSucceeded : function(data)
    {
      this.__decreaseActive("save");
      this.fireEvent("saved", this._decode(data, "save"));
    },

    // Internal event handler
    __onSaveFailed : function(msg)
    {
      this.warn("Unable to save data!", msg);
      this.__decreaseActive("save");
      this.fireEvent("saved", null);
    },

    /*
    ======================================================
      ACTION :: LOAD
    ======================================================
    */

    /**
     * Loads the data from e.g. a remote server.
     */
    load : function()
    {
      this.__increaseActive("load");
      this.fireEvent("loading");
      this._request("load",
      {
        success : this.__onLoadSucceeded,
        failed : this.__onLoadFailed
      });
    },

    // Internal event handler
    __onLoadSucceeded : function(data)
    {
      this.__decreaseActive("load");
      this.fireEvent("loaded", this._decode(data, "load"));
    },

    // Internal event handler
    __onLoadFailed : function(msg)
    {
      this.warn("Unable to load data!", msg);
      this.__decreaseActive("load");
      this.fireEvent("loaded", null);
    }
  }
});
<commit_msg>Renamed _request => _communicate<commit_after>core.Class("core.mvc.store.Abstract",
{
  include: [core.property.MGeneric, core.event.MEventTarget, core.util.MLogging],

  construct : function(path, config)
  {
    this.__activityTracker =
    {
      load : 0,
      save : 0,
      remove : 0,
      create : 0
    };

    if (!config) {
      config = {};
    }

    this.__path = path;

    var saveDebounce = config.saveDebounce || config.debounce || 0;
    this.save = core.util.Function.debounce(this.save, saveDebounce);

    var loadDebounce = config.loadDebounce || config.debounce || 0;
    this.load = core.util.Function.debounce(this.load, loadDebounce);

    var removeDebounce = config.removeDebounce || config.debounce || 0;
    this.remove = core.util.Function.debounce(this.remove, removeDebounce);

    var createDebounce = config.createDebounce || config.debounce || 0;
    this.create = core.util.Function.debounce(this.create, createDebounce);
  },

  events :
  {
    loading : core.event.Simple,
    loaded : core.event.Simple,

    saving : core.event.Simple,
    saved : core.event.Simple,

    creating : core.event.Simple,
    created : core.event.Simple,

    deleting : core.event.Simple,
    deleted : core.event.Simple,

    active : core.event.Simple,
    inactive : core.event.Simple
  },

  members :
  {
    /**
     * {String} Returns the REST communication path.
     */
    getPath : function() {
      return this.__path;
    },

    /**
     * {Boolean} Whether there are currently any requests running.
     */
    isActive : function()
    {
      var tracker = this.__activityTracker;
      return tracker.load > 0 || tracker.save > 0 || tracker.remove > 0 || tracker.create > 0;
    },

    /**
     * {Boolean} Whether there are currently requests active for loading data/entries.
     */
    isLoading : function() {
      return this.__activityTracker.load > 0;
    },

    /**
     * {Boolean} Whether there are currently requests active for saving data/entries.
     */
    isSaving : function() {
      return this.__activityTracker.save > 0;
    },

    /**
     * {Boolean} Whether there are currently requests active for removing data/entries.
     */
    isRemoving : function() {
      return this.__activityTracker.remove > 0;
    },

    /**
     * {Boolean} Whether there are currently requests active for creating data/entries.
     */
    isCreating : function() {
      return this.__activityTracker.create > 0;
    },

    /*
    ======================================================
      ABSTRACT METHOD/STUBS
    ======================================================
    */

    /**
     * Communicates data changes to the underlying storage using
     * the given @action {String} and the optional @config {Map}.
     */
    _communicate : function(action, config) {
      throw new Error("_communicate() is abstract!");
    },

    /**
     * Applying correction on outgoing @data {var}, typically the model/collection
     * for the given @type {String} of transaction.
     */
    _encode : function(data, type) {
      return data;
    },

    /**
     * Applying correction on incoming @data {var} as the result of
     * the given @type {String} of transaction.
     */
    _decode : function(data, type) {
      return data;
    },

    /*
    ======================================================
      ACTIVITY TRACKING
    ======================================================
    */

    /** {=Map} Keeping track of individual activities */
    __activityTracker : null,

    /**
     * Increments the counter for given @activity {String}.
     */
    __increaseActive : function(activity)
    {
      var wasActive = this.isActive();

      this.__activityTracker[activity]++;
      this.log("ACTIVITY TRACK: ", this.__activityTracker);

      if (!wasActive) {
        this.fireEvent("active");
      }
    },

    /**
     * Decrements the counter for given @activity {String}.
     */
    __decreaseActive : function(activity)
    {
      this.__activityTracker[activity]--;
      this.log("ACTIVITY TRACK: ", this.__activityTracker);

      if (!this.isActive()) {
        this.fireEvent("inactive");
      }
    },

    /*
    ======================================================
      ACTION :: SAVE
    ======================================================
    */

    /**
     * Saves the given @data {var}.
     */
    save : function(data)
    {
      this.__increaseActive("save");
      this.fireEvent("saving");
      this._communicate("save",
      {
        data : this._encode(data),
        success : this.__onSaveSucceeded,
        failed : this.__onSaveFailed
      });
    },

    // Internal event handler
    __onSaveSucceeded : function(data)
    {
      this.__decreaseActive("save");
      this.fireEvent("saved", this._decode(data, "save"));
    },

    // Internal event handler
    __onSaveFailed : function(msg)
    {
      this.warn("Unable to save data!", msg);
      this.__decreaseActive("save");
      this.fireEvent("saved", null);
    },

    /*
    ======================================================
      ACTION :: LOAD
    ======================================================
    */

    /**
     * Loads the data from e.g. a remote server.
     */
    load : function()
    {
      this.__increaseActive("load");
      this.fireEvent("loading");
      this._communicate("load",
      {
        success : this.__onLoadSucceeded,
        failed : this.__onLoadFailed
      });
    },

    // Internal event handler
    __onLoadSucceeded : function(data)
    {
      this.__decreaseActive("load");
      this.fireEvent("loaded", this._decode(data, "load"));
    },

    // Internal event handler
    __onLoadFailed : function(msg)
    {
      this.warn("Unable to load data!", msg);
      this.__decreaseActive("load");
      this.fireEvent("loaded", null);
    }
  }
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { addEvent, removeEvent } from 'helpers/listenerHelpers'
import NotiFeeds from './NotiFeeds'
import ChatFeeds from './ChatFeeds'
import { defaultChatSubject } from 'constants/defaultValues'
import { fetchNotifications } from 'redux/actions/NotiActions'
import ExecutionEnvironment from 'exenv'

class Notification extends Component {
  static propTypes = {
    chatMode: PropTypes.bool.isRequired,
    children: PropTypes.node,
    className: PropTypes.string,
    currentChatSubject: PropTypes.object,
    fetchNotifications: PropTypes.func.isRequired,
    myId: PropTypes.number,
    notifications: PropTypes.array.isRequired,
    position: PropTypes.string
  }

  state = {
    scrollPosition: ExecutionEnvironment.canUseDOM ? window.scrollY : 0,
    scrollLocked: false
  }

  componentDidMount() {
    const { fetchNotifications } = this.props
    addEvent(window, 'mousemove', this.onMouseMove)
    addEvent(window, 'scroll', this.onPageScroll)
    fetchNotifications()
  }

  componentWillUnmount() {
    if (ExecutionEnvironment.canUseDOM) {
      removeEvent(window, 'mousemove', this.onMouseMove)
      removeEvent(window, 'scroll', this.onPageScroll)
    }
  }

  render() {
    const {
      notifications,
      myId,
      className,
      currentChatSubject: { content = defaultChatSubject, loaded, ...subject },
      children
    } = this.props
    return (

            {children && (

                {children}

            )}
            {loaded && <ChatFeeds content={content} {...subject} />}
            {notifications.length > 0 && (
              <NotiFeeds
                notifications={notifications}
                myId={myId}
                style={{ marginTop: loaded && '1em' }}
              />
            )}

    )
  }

  handleScroll = () => {
    const { scrollHeight, clientHeight, scrollTop } = this.NotificationBox
    if (scrollTop === 0 || scrollHeight - clientHeight === scrollTop) {
      this.setState({ scrollLocked: true })
    } else {
      this.setState({ scrollLocked: false })
    }
  }

  onMouseMove = () => {
    const { scrollLocked } = this.state
    if (scrollLocked) this.setState({ scrollLocked: false })
  }

  onPageScroll = () => {
    const { chatMode } = this.props
    const { scrollLocked } = this.state
    if (scrollLocked) {
      window.scrollTo(0, this.state.scrollPosition)
    }
    if (!chatMode) {
      this.setState({ scrollPosition: window.scrollY })
    }
  }
}

export default connect(
  state => ({
    chatMode: state.ChatReducer.chatMode,
    myId: state.UserReducer.userId,
    notifications: state.NotiReducer.notifications,
    currentChatSubject: state.NotiReducer.currentChatSubject
  }),
  { fetchNotifications }
)(Notification)
<commit_msg>notification css change<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { addEvent, removeEvent } from 'helpers/listenerHelpers'
import NotiFeeds from './NotiFeeds'
import ChatFeeds from './ChatFeeds'
import { defaultChatSubject } from 'constants/defaultValues'
import { fetchNotifications } from 'redux/actions/NotiActions'
import ExecutionEnvironment from 'exenv'

class Notification extends Component {
  static propTypes = {
    chatMode: PropTypes.bool.isRequired,
    children: PropTypes.node,
    className: PropTypes.string,
    currentChatSubject: PropTypes.object,
    fetchNotifications: PropTypes.func.isRequired,
    myId: PropTypes.number,
    notifications: PropTypes.array.isRequired,
    position: PropTypes.string
  }

  state = {
    scrollPosition: ExecutionEnvironment.canUseDOM ? window.scrollY : 0,
    scrollLocked: false
  }

  componentDidMount() {
    const { fetchNotifications } = this.props
    addEvent(window, 'mousemove', this.onMouseMove)
    addEvent(window, 'scroll', this.onPageScroll)
    fetchNotifications()
  }

  componentWillUnmount() {
    if (ExecutionEnvironment.canUseDOM) {
      removeEvent(window, 'mousemove', this.onMouseMove)
      removeEvent(window, 'scroll', this.onPageScroll)
    }
  }

  render() {
    const {
      notifications,
      myId,
      className,
      currentChatSubject: { content = defaultChatSubject, loaded, ...subject },
      children
    } = this.props
    return (

 {
              this.NotificationBox = ref
            }}
          >
            {children && (

                {children}

            )}
            {loaded && <ChatFeeds content={content} {...subject} />}
            {notifications.length > 0 && (
              <NotiFeeds
                notifications={notifications}
                myId={myId}
                style={{ marginTop: loaded && '1rem' }}
              />
            )}

    )
  }

  handleScroll = () => {
    const { scrollHeight, clientHeight, scrollTop } = this.NotificationBox
    console.log(scrollTop, scrollHeight - clientHeight, scrollTop)
    if (scrollTop === 0 || scrollHeight - clientHeight === scrollTop) {
      this.setState({ scrollLocked: true })
    } else {
      this.setState({ scrollLocked: false })
    }
  }

  onMouseMove = () => {
    const { scrollLocked } = this.state
    if (scrollLocked) this.setState({ scrollLocked: false })
  }

  onPageScroll = () => {
    const { chatMode } = this.props
    const { scrollLocked } = this.state
    if (scrollLocked) {
      window.scrollTo(0, this.state.scrollPosition)
    }
    if (!chatMode) {
      this.setState({ scrollPosition: window.scrollY })
    }
  }
}

export default connect(
  state => ({
    chatMode: state.ChatReducer.chatMode,
    myId: state.UserReducer.userId,
    notifications: state.NotiReducer.notifications,
    currentChatSubject: state.NotiReducer.currentChatSubject
  }),
  { fetchNotifications }
)(Notification)
<|endoftext|>


<commit_before>function renderHub(dataUrl,containerId,detailUrl){
    var radius = 800 / 2; // SVG radius

    var cluster = d3.layout.cluster()
        .size([360, radius - 250]);

    var diagonal = d3.svg.diagonal.radial()
        .projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });

    var svg = d3.select("#" + containerId).append("svg")
        .attr("width", radius * 2)
        .attr("height", radius * 2)
        .append("g")
        .attr("transform", "translate(" + radius + "," + radius + ")");

    var _getNodeDetailTpl = function (){
        var tmp = null;
        return function (){
            if( !tmp ){
                tmp = $('#switch_node_detail').html();
            }
            return tmp;
        };
    }();

    var _showNodeDetail = function( d, e, contentHtmlTpl ){
        console.log(d, e, contentHtmlTpl)
        var $tg = $(e.target);
        if( false == $tg.is("g.box") ){
            $tg = $tg.closest("g.box");
        }
        $tg = $tg.find("circle");

        var offset = $tg.offset();
        var x = offset.left,
            y = offset.top;

        var contentTpl = '
' +
            '

' +
            '
{content}
' +
            '
';

        var offsetX = 0,
            offsetY = 0;
        var className = "nodeDetail";
        var _parseData = function ( data ){
            if( data ){
                for( var p in data ){
                    contentHtmlTpl = contentHtmlTpl.replace( '{' + p + '}', data[p] );
                }
                return contentHtmlTpl;
            }
            return "No data.";
        };
        var _updateContent = function( html ){
            return 	contentTpl.replace( "{content}", html );
        };
        var popPanel =  new PopupPanel({
            className: 'modalessDialog' + (className ? " " + className : ""),
            offsetX: offsetX,
            offsetY: offsetY,
            destroy: true,
            animate: false,
            closeHandler: function() {},
            content: contentTpl,
            initInterface: function($content) {
                var inst = this;
                $content.click(function(e) {
                    if( $(e.target).is('div.popup_close'))
                        inst.close(true);
                });

                $content.find("div.popup_content").html(_updateContent("loading..."));
                console.log(d)
                // nodeDetail_.json : fail data, nodeDetail.json: ok data.
                $.get( detailUrl, { node: d.id }, function(j){
                    if( j.result == 1 ){
                        $content.find("div.popup_content").html(_updateContent(_parseData( j.data )));
                    } else {
                        $content.find("div.popup_content").html(_updateContent( j.msg ));
                    }
                    popPanel.refresh();
                }, 'json' );
            }
        }).init().show(x, y);
    };
    d3.json(dataUrl, function(error, root) {
        if (error) throw error;

        var nodes = cluster.nodes(root);
        var link =  svg.selectAll("path.link")
            .data(cluster.links(nodes))
            .enter().append("path")
            .attr("class", function( d ){
                if( d['target']['status'] == 0 )
                    return "link error";
                return "link";
            })
            .attr("d", diagonal) ;

        var  _path  = function( node ){
            var len = link[0].length;
            for( var i = 0 ; i < len; i++){
                if( d3.select(link[0][i]).data()[0].target == d3.select(node).data()[0] ){
                    return d3.select(link[0][i]);
                }
            }
            return d3.select();
        };

        var node = svg.selectAll("g.node")
            .data(nodes)
            .enter().append("g")
            .attr("class", function(d){
                if( d['status'] == 0 )
                    return "node error";
                return "node";
            })
            .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; });

        node = node.append("g")
            .attr( "class", "box" )
            .on("mouseover", function (){
                _path(this.parentNode).classed( "hover", true );
            })
            .on("mouseout", function (){
                _path(this.parentNode).classed( "hover", false );
            })
            .on( "click", function( data ){
                _showNodeDetail( data, d3.event, _getNodeDetailTpl() );
            });

        node.append("rect")
            .attr("x","-5")
            .attr("y", "-5")
            .attr("width", "30px")
            .attr("height", "10px")
            //.attr("fill", "red"); // Fixed: g.box:hover 遇到空隙会闪烁
            .attr("fill", "transparent");

        node.append("circle")
            .attr("cx", "0.15em")
            .attr("r", 4.5);

        node.append("text")
            .attr("dy", ".31em")
            .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
            .attr("level", function(d) { return d.depth; })
            .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; })
            .text(function(d) { return d.name; }) ;
    });

    d3.select(self.frameElement).style("height", radius * 2 + "px");
}<commit_msg>Format code.<commit_after>function renderHub(dataUrl, containerId, detailUrl) {
    var radius = 800 / 2; // SVG radius

    var cluster = d3.layout.cluster()
        .size([360, radius - 250]);

    var diagonal = d3.svg.diagonal.radial()
        .projection(function(d) {
            return [d.y, d.x / 180 * Math.PI];
        });

    var svg = d3.select("#" + containerId).append("svg")
        .attr("width", radius * 2)
        .attr("height", radius * 2)
        .append("g")
        .attr("transform", "translate(" + radius + "," + radius + ")");

    var _getNodeDetailTpl = function() {
        var tmp = null;
        return function() {
            if (!tmp) {
                tmp = $('#switch_node_detail').html();
            }
            return tmp;
        };
    }();

    var _showNodeDetail = function(d, e, contentHtmlTpl) {
        console.log(d, e, contentHtmlTpl)
        var $tg = $(e.target);
        if (false == $tg.is("g.box")) {
            $tg = $tg.closest("g.box");
        }
        $tg = $tg.find("circle");

        var offset = $tg.offset();
        var x = offset.left,
            y = offset.top;

        var contentTpl = '
' +
            '

' +
            '
{content}
' +
            '
';

        var offsetX = 0,
            offsetY = 0;
        var className = "nodeDetail";
        var _parseData = function(data) {
            if (data) {
                for (var p in data) {
                    contentHtmlTpl = contentHtmlTpl.replace('{' + p + '}', data[p]);
                }
                return contentHtmlTpl;
            }
            return "No data.";
        };
        var _updateContent = function(html) {
            return contentTpl.replace("{content}", html);
        };
        var popPanel = new PopupPanel({
            className: 'modalessDialog' + (className ? " " + className : ""),
            offsetX: offsetX,
            offsetY: offsetY,
            destroy: true,
            animate: false,
            closeHandler: function() {},
            content: contentTpl,
            initInterface: function($content) {
                var inst = this;
                $content.click(function(e) {
                    if ($(e.target).is('div.popup_close'))
                        inst.close(true);
                });

                $content.find("div.popup_content").html(_updateContent("loading..."));
                console.log(d)
                // nodeDetail_.json : fail data, nodeDetail.json: ok data.
                $.get(detailUrl, {
                    node: d.id
                }, function(j) {
                    if (j.result == 1) {
                        $content.find("div.popup_content").html(_updateContent(_parseData(j.data)));
                    } else {
                        $content.find("div.popup_content").html(_updateContent(j.msg));
                    }
                    popPanel.refresh();
                }, 'json');
            }
        }).init().show(x, y);
    };
    d3.json(dataUrl, function(error, root) {
        if (error) throw error;

        var nodes = cluster.nodes(root);
        var link = svg.selectAll("path.link")
            .data(cluster.links(nodes))
            .enter().append("path")
            .attr("class", function(d) {
                if (d['target']['status'] == 0)
                    return "link error";
                return "link";
            })
            .attr("d", diagonal);

        var _path = function(node) {
            var len = link[0].length;
            for (var i = 0; i < len; i++) {
                if (d3.select(link[0][i]).data()[0].target == d3.select(node).data()[0]) {
                    return d3.select(link[0][i]);
                }
            }
            return d3.select();
        };

        var node = svg.selectAll("g.node")
            .data(nodes)
            .enter().append("g")
            .attr("class", function(d) {
                if (d['status'] == 0)
                    return "node error";
                return "node";
            })
            .attr("transform", function(d) {
                return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
            });

        node = node.append("g")
            .attr("class", "box")
            .on("mouseover", function() {
                _path(this.parentNode).classed("hover", true);
            })
            .on("mouseout", function() {
                _path(this.parentNode).classed("hover", false);
            })
            .on("click", function(data) {
                _showNodeDetail(data, d3.event, _getNodeDetailTpl());
            });

        node.append("rect")
            .attr("x", "-5")
            .attr("y", "-5")
            .attr("width", "30px")
            .attr("height", "10px")
        //.attr("fill", "red"); // Fixed: g.box:hover 遇到空隙会闪烁
        .attr("fill", "transparent");

        node.append("circle")
            .attr("cx", "0.15em")
            .attr("r", 4.5);

        node.append("text")
            .attr("dy", ".31em")
            .attr("text-anchor", function(d) {
                return d.x < 180 ? "start" : "end";
            })
            .attr("level", function(d) {
                return d.depth;
            })
            .attr("transform", function(d) {
                return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)";
            })
            .text(function(d) {
                return d.name;
            });
    });

    d3.select(self.frameElement).style("height", radius * 2 + "px");
}<|endoftext|>


<commit_before><commit_msg>add required field in safari<commit_after><|endoftext|>


<commit_before>function exit( status ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir
    // %        note 1: Should be considered expirimental. Please comment on this function.
    // *     example 1: exit();
    // *     returns 1: null

    var i;

    if (typeof status === 'string') {
        alert(status);
    }

    window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);

    var handlers = [
        'copy', 'cut', 'paste',
        'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
        'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
        'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
    ];

    function stopPropagation (e) {
        e.stopPropagation();
        // e.preventDefault(); // Stop for the form controls, etc., too?
    }
    for (i=0; i < handlers.length; i++) {
        window.addEventListener(handlers[i], stopPropagation, true);
    }

    throw '';
}<commit_msg>stopPropagation bug<commit_after>function exit( status ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir
    // +      input by: Paul
    // +   bugfixed by: Hyam Singer
    // %        note 1: Should be considered expirimental. Please comment on this function.
    // *     example 1: exit();
    // *     returns 1: null

    var i;

    if (typeof status === 'string') {
        alert(status);
    }

    window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);

    var handlers = [
        'copy', 'cut', 'paste',
        'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
        'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
        'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
    ];

    function stopPropagation (e) {
        e.stopPropagation();
        // e.preventDefault(); // Stop for the form controls, etc., too?
    }
    for (i=0; i < handlers.length; i++) {
        window.addEventListener(handlers[i], function (e) {e.stopPropagation();}, true);
    }

    throw '';
}<|endoftext|>