<commit_before>/*!
 * regjsgen 0.3.0
 * Copyright 2014-2017 Benjamin Tan <https://demoneaux.github.io/>
 * Available under MIT license <https://github.com/demoneaux/regjsgen/blob/master/LICENSE>
 */
;(function() {
  'use strict';

  // Used to determine if values are of the language type `Object`.
  var objectTypes = {
    'function': true,
    'object': true
  };

  // Used as a reference to the global object.
  var root = (objectTypes[typeof window] && window) || this;

  // Detect free variable `exports`.
  var freeExports = objectTypes[typeof exports] && exports;

  // Detect free variable `module`.
  var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;

  // Detect free variable `global` from Node.js or Browserified code and use it as `root`.
  var freeGlobal = freeExports && freeModule && typeof global == 'object' && global;
  if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) {
    root = freeGlobal;
  }

  // Used to check objects for own properties.
  var hasOwnProperty = Object.prototype.hasOwnProperty;

  /*--------------------------------------------------------------------------*/

  // Generates strings based on the given code points.
  // Based on https://mths.be/fromcodepoint v0.2.0 by @mathias.
  var stringFromCharCode = String.fromCharCode;
  var floor = Math.floor;
  function fromCodePoint() {
    var MAX_SIZE = 0x4000;
    var codeUnits = [];
    var highSurrogate;
    var lowSurrogate;
    var index = -1;
    var length = arguments.length;
    if (!length) {
      return '';
    }
    var result = '';
    while (++index < length) {
      var codePoint = Number(arguments[index]);
      if (
        !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
        codePoint < 0 || // not a valid Unicode code point
        codePoint > 0x10FFFF || // not a valid Unicode code point
        floor(codePoint) != codePoint // not an integer
      ) {
        throw RangeError('Invalid code point: ' + codePoint);
      }
      if (codePoint <= 0xFFFF) {
        // BMP code point
        codeUnits.push(codePoint);
      } else {
        // Astral code point; split in surrogate halves
        // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
        codePoint -= 0x10000;
        highSurrogate = (codePoint >> 10) + 0xD800;
        lowSurrogate = (codePoint % 0x400) + 0xDC00;
        codeUnits.push(highSurrogate, lowSurrogate);
      }
      if (index + 1 == length || codeUnits.length > MAX_SIZE) {
        result += stringFromCharCode.apply(null, codeUnits);
        codeUnits.length = 0;
      }
    }
    return result;
  }

  /*--------------------------------------------------------------------------*/

  // Ensures that nodes have the correct types.
  var assertTypeRegexMap = {};
  function assertType(type, expected) {
    if (expected.indexOf('|') == -1) {
      if (type == expected) {
        return;
      }

      throw Error('Invalid node type: ' + type + '; expected type: ' + expected);
    }

    expected = hasOwnProperty.call(assertTypeRegexMap, expected)
      ? assertTypeRegexMap[expected]
      : (assertTypeRegexMap[expected] = RegExp('^(?:' + expected + ')$'));

    if (expected.test(type)) {
      return;
    }

    throw Error('Invalid node type: ' + type + '; expected types: ' + expected);
  }

  /*--------------------------------------------------------------------------*/

  // Generates a regular expression string based on an AST.
  function generate(node) {
    var type = node.type;

    if (hasOwnProperty.call(generators, type)) {
      return generators[type](node);
    }

    throw Error('Invalid node type: ' + type);
  }

  /*--------------------------------------------------------------------------*/

  function generateAlternative(node) {
    assertType(node.type, 'alternative');

    var terms = node.body,
        i = -1,
        length = terms.length,
        result = '';

    while (++i < length) {
      result += generateTerm(terms[i]);
    }

    return result;
  }

  function generateAnchor(node) {
    assertType(node.type, 'anchor');

    switch (node.kind) {
      case 'start':
        return '^';
      case 'end':
        return '$';
      case 'boundary':
        return '\\b';
      case 'not-boundary':
        return '\\B';
      default:
        throw Error('Invalid assertion');
    }
  }

  function generateAtom(node) {
    assertType(node.type, 'anchor|characterClass|characterClassEscape|dot|group|reference|value');

    return generate(node);
  }

  function generateCharacterClass(node) {
    assertType(node.type, 'characterClass');

    var classRanges = node.body,
        i = -1,
        length = classRanges.length,
        result = '';

    if (node.negative) {
      result += '^';
    }

    while (++i < length) {
      result += generateClassAtom(classRanges[i]);
    }

    return '[' + result + ']';
  }

  function generateCharacterClassEscape(node) {
    assertType(node.type, 'characterClassEscape');

    return '\\' + node.value;
  }

  function generateUnicodePropertyEscape(node) {
    assertType(node.type, 'unicodePropertyEscape');

    return '\\' + (node.negative ? 'P' : 'p') + '{' + node.value + '}';
  }

  function generateCharacterClassRange(node) {
    assertType(node.type, 'characterClassRange');

    var min = node.min,
        max = node.max;

    if (min.type == 'characterClassRange' || max.type == 'characterClassRange') {
      throw Error('Invalid character class range');
    }

    return generateClassAtom(min) + '-' + generateClassAtom(max);
  }

  function generateClassAtom(node) {
    assertType(node.type, 'anchor|characterClassEscape|characterClassRange|dot|value');

    return generate(node);
  }

  function generateDisjunction(node) {
    assertType(node.type, 'disjunction');

    var body = node.body,
        i = -1,
        length = body.length,
        result = '';

    while (++i < length) {
      if (i != 0) {
        result += '|';
      }
      result += generate(body[i]);
    }

    return result;
  }

  function generateDot(node) {
    assertType(node.type, 'dot');

    return '.';
  }

  function generateGroup(node) {
    assertType(node.type, 'group');

    var result = '';

    switch (node.behavior) {
      case 'normal':
        break;
      case 'ignore':
        result += '?:';
        break;
      case 'lookahead':
        result += '?=';
        break;
      case 'negativeLookahead':
        result += '?!';
        break;
      default:
        throw Error('Invalid behaviour: ' + node.behaviour);
    }

    var body = node.body,
        i = -1,
        length = body.length;

    while (++i < length) {
      result += generate(body[i]);
    }

    return '(' + result + ')';
  }

  function generateQuantifier(node) {
    assertType(node.type, 'quantifier');

    var quantifier = '',
        min = node.min,
        max = node.max;

    if (max == null) {
      if (min == 0) {
        quantifier = '*';
      } else if (min == 1) {
        quantifier = '+';
      } else {
        quantifier = '{' + min + ',}';
      }
    } else if (min == max) {
      quantifier = '{' + min + '}';
    } else if (min == 0 && max == 1) {
      quantifier = '?';
    } else {
      quantifier = '{' + min + ',' + max + '}';
    }

    if (!node.greedy) {
      quantifier += '?';
    }

    return generateAtom(node.body[0]) + quantifier;
  }

  function generateReference(node) {
    assertType(node.type, 'reference');

    return '\\' + node.matchIndex;
  }

  function generateTerm(node) {
    assertType(node.type, 'anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|unicodePropertyEscape|value');

    return generate(node);
  }

  function generateValue(node) {
    assertType(node.type, 'value');

    var kind = node.kind,
        codePoint = node.codePoint;

    switch (kind) {
      case 'controlLetter':
        return '\\c' + fromCodePoint(codePoint + 64);
      case 'hexadecimalEscape':
        return '\\x' + ('00' + codePoint.toString(16).toUpperCase()).slice(-2);
      case 'identifier':
        return '\\' + fromCodePoint(codePoint);
      case 'null':
        return '\\' + codePoint;
      case 'octal':
        return '\\' + codePoint.toString(8);
      case 'singleEscape':
        switch (codePoint) {
          case 0x0008:
            return '\\b';
          case 0x0009:
            return '\\t';
          case 0x000A:
            return '\\n';
          case 0x000B:
            return '\\v';
          case 0x000C:
            return '\\f';
          case 0x000D:
            return '\\r';
          default:
            throw Error('Invalid codepoint: ' + codePoint);
        }
      case 'symbol':
        return fromCodePoint(codePoint);
      case 'unicodeEscape':
        return '\\u' + ('0000' + codePoint.toString(16).toUpperCase()).slice(-4);
      case 'unicodeCodePointEscape':
        return '\\u{' + codePoint.toString(16).toUpperCase() + '}';
      default:
        throw Error('Unsupported node kind: ' + kind);
    }
  }

  /*--------------------------------------------------------------------------*/

  // Used to generate strings for each node type.
  var generators = {
    'alternative': generateAlternative,
    'anchor': generateAnchor,
    'characterClass': generateCharacterClass,
    'characterClassEscape': generateCharacterClassEscape,
    'characterClassRange': generateCharacterClassRange,
    'unicodePropertyEscape': generateUnicodePropertyEscape,
    'disjunction': generateDisjunction,
    'dot': generateDot,
    'group': generateGroup,
    'quantifier': generateQuantifier,
    'reference': generateReference,
    'value': generateValue
  };

  /*--------------------------------------------------------------------------*/

  // Export regjsgen.
  // Some AMD build optimizers, like r.js, check for condition patterns like the following:
  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
    // Define as an anonymous module so it can be aliased through path mapping.
    define(function() {
      return {
        'generate': generate
      };
    });
  }
  // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
  else if (freeExports && freeModule) {
    // Export for CommonJS support.
    freeExports.generate = generate;
  }
  else {
    // Export to the global object.
    root.regjsgen = {
      'generate': generate
    };
  }
}.call(this));
<commit_msg>Simplify `fromCodePoint`.<commit_after>/*!
 * regjsgen 0.3.0
 * Copyright 2014-2017 Benjamin Tan <https://demoneaux.github.io/>
 * Available under MIT license <https://github.com/demoneaux/regjsgen/blob/master/LICENSE>
 */
;(function() {
  'use strict';

  // Used to determine if values are of the language type `Object`.
  var objectTypes = {
    'function': true,
    'object': true
  };

  // Used as a reference to the global object.
  var root = (objectTypes[typeof window] && window) || this;

  // Detect free variable `exports`.
  var freeExports = objectTypes[typeof exports] && exports;

  // Detect free variable `module`.
  var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;

  // Detect free variable `global` from Node.js or Browserified code and use it as `root`.
  var freeGlobal = freeExports && freeModule && typeof global == 'object' && global;
  if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) {
    root = freeGlobal;
  }

  // Used to check objects for own properties.
  var hasOwnProperty = Object.prototype.hasOwnProperty;

  /*--------------------------------------------------------------------------*/

  // Generates a string based on the given code point.
  // Based on https://mths.be/fromcodepoint by @mathias.
  function fromCodePoint() {
    var codePoint = Number(arguments[0]);

    if (
      !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
      codePoint < 0 || // not a valid Unicode code point
      codePoint > 0x10FFFF || // not a valid Unicode code point
      Math.floor(codePoint) != codePoint // not an integer
    ) {
      throw RangeError('Invalid code point: ' + codePoint);
    }

    if (codePoint <= 0xFFFF) {
      // BMP code point
      return String.fromCharCode(codePoint);
    } else {
      // Astral code point; split in surrogate halves
      // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
      codePoint -= 0x10000;
      var highSurrogate = (codePoint >> 10) + 0xD800;
      var lowSurrogate = (codePoint % 0x400) + 0xDC00;
      return String.fromCharCode(highSurrogate, lowSurrogate);
    }
  }

  /*--------------------------------------------------------------------------*/

  // Ensures that nodes have the correct types.
  var assertTypeRegexMap = {};
  function assertType(type, expected) {
    if (expected.indexOf('|') == -1) {
      if (type == expected) {
        return;
      }

      throw Error('Invalid node type: ' + type + '; expected type: ' + expected);
    }

    expected = hasOwnProperty.call(assertTypeRegexMap, expected)
      ? assertTypeRegexMap[expected]
      : (assertTypeRegexMap[expected] = RegExp('^(?:' + expected + ')$'));

    if (expected.test(type)) {
      return;
    }

    throw Error('Invalid node type: ' + type + '; expected types: ' + expected);
  }

  /*--------------------------------------------------------------------------*/

  // Generates a regular expression string based on an AST.
  function generate(node) {
    var type = node.type;

    if (hasOwnProperty.call(generators, type)) {
      return generators[type](node);
    }

    throw Error('Invalid node type: ' + type);
  }

  /*--------------------------------------------------------------------------*/

  function generateAlternative(node) {
    assertType(node.type, 'alternative');

    var terms = node.body,
        i = -1,
        length = terms.length,
        result = '';

    while (++i < length) {
      result += generateTerm(terms[i]);
    }

    return result;
  }

  function generateAnchor(node) {
    assertType(node.type, 'anchor');

    switch (node.kind) {
      case 'start':
        return '^';
      case 'end':
        return '$';
      case 'boundary':
        return '\\b';
      case 'not-boundary':
        return '\\B';
      default:
        throw Error('Invalid assertion');
    }
  }

  function generateAtom(node) {
    assertType(node.type, 'anchor|characterClass|characterClassEscape|dot|group|reference|value');

    return generate(node);
  }

  function generateCharacterClass(node) {
    assertType(node.type, 'characterClass');

    var classRanges = node.body,
        i = -1,
        length = classRanges.length,
        result = '';

    if (node.negative) {
      result += '^';
    }

    while (++i < length) {
      result += generateClassAtom(classRanges[i]);
    }

    return '[' + result + ']';
  }

  function generateCharacterClassEscape(node) {
    assertType(node.type, 'characterClassEscape');

    return '\\' + node.value;
  }

  function generateUnicodePropertyEscape(node) {
    assertType(node.type, 'unicodePropertyEscape');

    return '\\' + (node.negative ? 'P' : 'p') + '{' + node.value + '}';
  }

  function generateCharacterClassRange(node) {
    assertType(node.type, 'characterClassRange');

    var min = node.min,
        max = node.max;

    if (min.type == 'characterClassRange' || max.type == 'characterClassRange') {
      throw Error('Invalid character class range');
    }

    return generateClassAtom(min) + '-' + generateClassAtom(max);
  }

  function generateClassAtom(node) {
    assertType(node.type, 'anchor|characterClassEscape|characterClassRange|dot|value');

    return generate(node);
  }

  function generateDisjunction(node) {
    assertType(node.type, 'disjunction');

    var body = node.body,
        i = -1,
        length = body.length,
        result = '';

    while (++i < length) {
      if (i != 0) {
        result += '|';
      }
      result += generate(body[i]);
    }

    return result;
  }

  function generateDot(node) {
    assertType(node.type, 'dot');

    return '.';
  }

  function generateGroup(node) {
    assertType(node.type, 'group');

    var result = '';

    switch (node.behavior) {
      case 'normal':
        break;
      case 'ignore':
        result += '?:';
        break;
      case 'lookahead':
        result += '?=';
        break;
      case 'negativeLookahead':
        result += '?!';
        break;
      default:
        throw Error('Invalid behaviour: ' + node.behaviour);
    }

    var body = node.body,
        i = -1,
        length = body.length;

    while (++i < length) {
      result += generate(body[i]);
    }

    return '(' + result + ')';
  }

  function generateQuantifier(node) {
    assertType(node.type, 'quantifier');

    var quantifier = '',
        min = node.min,
        max = node.max;

    if (max == null) {
      if (min == 0) {
        quantifier = '*';
      } else if (min == 1) {
        quantifier = '+';
      } else {
        quantifier = '{' + min + ',}';
      }
    } else if (min == max) {
      quantifier = '{' + min + '}';
    } else if (min == 0 && max == 1) {
      quantifier = '?';
    } else {
      quantifier = '{' + min + ',' + max + '}';
    }

    if (!node.greedy) {
      quantifier += '?';
    }

    return generateAtom(node.body[0]) + quantifier;
  }

  function generateReference(node) {
    assertType(node.type, 'reference');

    return '\\' + node.matchIndex;
  }

  function generateTerm(node) {
    assertType(node.type, 'anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|unicodePropertyEscape|value');

    return generate(node);
  }

  function generateValue(node) {
    assertType(node.type, 'value');

    var kind = node.kind,
        codePoint = node.codePoint;

    if (typeof codePoint != 'number') {
      throw new Error('Invalid code point: ' + codePoint);
    }

    switch (kind) {
      case 'controlLetter':
        return '\\c' + fromCodePoint(codePoint + 64);
      case 'hexadecimalEscape':
        return '\\x' + ('00' + codePoint.toString(16).toUpperCase()).slice(-2);
      case 'identifier':
        return '\\' + fromCodePoint(codePoint);
      case 'null':
        return '\\' + codePoint;
      case 'octal':
        return '\\' + codePoint.toString(8);
      case 'singleEscape':
        switch (codePoint) {
          case 0x0008:
            return '\\b';
          case 0x0009:
            return '\\t';
          case 0x000A:
            return '\\n';
          case 0x000B:
            return '\\v';
          case 0x000C:
            return '\\f';
          case 0x000D:
            return '\\r';
          default:
            throw Error('Invalid code point: ' + codePoint);
        }
      case 'symbol':
        return fromCodePoint(codePoint);
      case 'unicodeEscape':
        return '\\u' + ('0000' + codePoint.toString(16).toUpperCase()).slice(-4);
      case 'unicodeCodePointEscape':
        return '\\u{' + codePoint.toString(16).toUpperCase() + '}';
      default:
        throw Error('Unsupported node kind: ' + kind);
    }
  }

  /*--------------------------------------------------------------------------*/

  // Used to generate strings for each node type.
  var generators = {
    'alternative': generateAlternative,
    'anchor': generateAnchor,
    'characterClass': generateCharacterClass,
    'characterClassEscape': generateCharacterClassEscape,
    'characterClassRange': generateCharacterClassRange,
    'unicodePropertyEscape': generateUnicodePropertyEscape,
    'disjunction': generateDisjunction,
    'dot': generateDot,
    'group': generateGroup,
    'quantifier': generateQuantifier,
    'reference': generateReference,
    'value': generateValue
  };

  /*--------------------------------------------------------------------------*/

  // Export regjsgen.
  // Some AMD build optimizers, like r.js, check for condition patterns like the following:
  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
    // Define as an anonymous module so it can be aliased through path mapping.
    define(function() {
      return {
        'generate': generate
      };
    });
  }
  // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
  else if (freeExports && freeModule) {
    // Export for CommonJS support.
    freeExports.generate = generate;
  }
  else {
    // Export to the global object.
    root.regjsgen = {
      'generate': generate
    };
  }
}.call(this));
<|endoftext|>


<commit_before>/**
 * leftClick event plugin
 *
 * Copyright (c) 2010 Filatov Dmitry (alpha@zforms.ru)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @version 1.0.0
 */

(function($) {

var leftClick = $.event.special.leftclick = {

    setup : function() {

        $(this).bind('click', leftClick.handler);

    },

    teardown : function() {

        $(this).unbind('click', leftClick.handler);

    },

    handler : function(e) {

        if(!e.button) {
            e.type = 'leftclick';
            $.event.handle.apply(this, arguments);
            e.type = 'click';
        }

    }

};

})(jQuery);<commit_msg>leftClick as module<commit_after>/**
 * leftClick event plugin
 *
 * Copyright (c) 2010 Filatov Dmitry (alpha@zforms.ru)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @version 1.0.0
 */

modules.define(['jquery'], function(provide, $) {

var leftClick = $.event.special.leftclick = {
    setup : function() {
        $(this).on('click', leftClick.handler);
    },

    teardown : function() {
        $(this).off('click', leftClick.handler);
    },

    handler : function(e) {
        if(!e.button) {
            e.type = 'leftclick';
            $.event.dispatch.apply(this, arguments);
            e.type = 'click';
        }
    }
};

provide($);

});<|endoftext|>


<commit_before>'use strict';

import React, { Component } from 'react'

const styles = {
  chatbubble: {
    backgroundColor: "#03b4f4",
    borderRadius: 20,
    clear: 'both',
    marginTop: 1,
    marginRight: 'auto',
    marginBottom: 1,
    marginLeft: 'auto',
    maxWidth: 425,
    paddingTop: 8,
    paddingBottom: 8,
    paddingLeft: 14,
    paddingRight: 14,
    width: '-webkit-fit-content'
  },
  chatbubbleOrientationNormal: {
    float: 'right'
  },
  recipientChatbubble : {
    backgroundColor: '#ccc'
  },
  recipientChatbubbleOrientationNormal: {
    float: 'left'
  },
  p: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '300',
    margin: 0,
  }
}

export default class ChatBubble extends Component {
  constructor(props) {
    super()
    this.state = {
      message: undefined,
      bubbleStyles: {
        text: {},
        chatbubble: {},
        userBubble: {}
      },
    }
  }

  componentDidMount() {
    this.setState({
      message: this.props.message,
      bubbleStyles: this.props.bubbleStyles?
        {
          text: this.props.bubbleStyles.text?this.props.bubbleStyles.text:{},
          chatbubble: this.props.bubbleStyles.chatbubble?this.props.bubbleStyles.chatbubble:{},
          userBubble: this.props.bubbleStyles.userBubble?this.props.bubbleStyles.userBubble:{}
        }
        : {text:{},chatbubble:{}}
    })
  }

  // IPR
  _parse_for_styles(message) {
    if (typeof(message) === "string") {
      var bolded_start = message.search(/__(\w+\s?)+__/);
      var bolded_end = message.slice(bolded_start+2).search(/__/)
      var bolded = message.slice(bolded_start + 2, bolded_start + bolded_end + 2)
      // Render text
      if (bolded_start != -1 && bolded_end != -1) {
        return (

            {this._parse_for_styles(message.slice(0, bolded_start))}
            {bolded}
            {this._parse_for_styles(message.slice(bolded_start + bolded_end + 4))}

        )
      }
      else {
        return {message}
      }
    }
    return message
  }

  // IPR
  _parse_for_links(message) {
    var i, j, str, last;
    if (message.search(/<a href=/) !== -1 && (i = message.search(//))) {
      last = message.slice(j+5, -1)
      return (

        {message.slice(0, i)}
        |">/))}>
          {message.slice(message.search(/'>|">/)+2, j-2)}

        {message.slice(j+2)}

      )
    }
    else {
      return
{message}

    }
  }

  render() {
    if (this.props.message.id) {
        return (

{this.props.message.message}

        )
    } else {
      return (

{this.props.message.message}

      )
    }
  }
}
<commit_msg>moved WillMount code to constructor<commit_after>'use strict';

import React, { Component } from 'react'

const styles = {
  chatbubble: {
    backgroundColor: "#03b4f4",
    borderRadius: 20,
    clear: 'both',
    marginTop: 1,
    marginRight: 'auto',
    marginBottom: 1,
    marginLeft: 'auto',
    maxWidth: 425,
    paddingTop: 8,
    paddingBottom: 8,
    paddingLeft: 14,
    paddingRight: 14,
    width: '-webkit-fit-content'
  },
  chatbubbleOrientationNormal: {
    float: 'right'
  },
  recipientChatbubble : {
    backgroundColor: '#ccc'
  },
  recipientChatbubbleOrientationNormal: {
    float: 'left'
  },
  p: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '300',
    margin: 0,
  }
}

export default class ChatBubble extends Component {
  constructor(props) {
    super()
    this.state = {
      message: props.message,
      bubbleStyles: props.bubbleStyles?
        {
          text: props.bubbleStyles.text?props.bubbleStyles.text:{},
          chatbubble: props.bubbleStyles.chatbubble?props.bubbleStyles.chatbubble:{},
          userBubble: props.bubbleStyles.userBubble?props.bubbleStyles.userBubble:{}
        }
        : {text:{},chatbubble:{}}
    }
  }

  componentDidMount() {}

  // IPR
  _parse_for_styles(message) {
    if (typeof(message) === "string") {
      var bolded_start = message.search(/__(\w+\s?)+__/);
      var bolded_end = message.slice(bolded_start+2).search(/__/)
      var bolded = message.slice(bolded_start + 2, bolded_start + bolded_end + 2)
      // Render text
      if (bolded_start != -1 && bolded_end != -1) {
        return (

            {this._parse_for_styles(message.slice(0, bolded_start))}
            {bolded}
            {this._parse_for_styles(message.slice(bolded_start + bolded_end + 4))}

        )
      }
      else {
        return {message}
      }
    }
    return message
  }

  // IPR
  _parse_for_links(message) {
    var i, j, str, last;
    if (message.search(/<a href=/) !== -1 && (i = message.search(//))) {
      last = message.slice(j+5, -1)
      return (

        {message.slice(0, i)}
        |">/))}>
          {message.slice(message.search(/'>|">/)+2, j-2)}

        {message.slice(j+2)}

      )
    }
    else {
      return
{message}

    }
  }

  render() {
    if (this.props.message.id) {
        return (

{this.props.message.message}

        )
    } else {
      return (

{this.props.message.message}

      )
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { Animated, View } from 'react-native';
import { Svg, Path, G } from 'react-native-svg';

export default class CircularProgress extends React.PureComponent {
  polarToCartesian(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180.0;
    return {
      x: centerX + radius * Math.cos(angleInRadians),
      y: centerY + radius * Math.sin(angleInRadians),
    };
  }

  circlePath(x, y, radius, startAngle, endAngle) {
    var start = this.polarToCartesian(x, y, radius, endAngle * 0.9999);
    var end = this.polarToCartesian(x, y, radius, startAngle);
    var largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1';
    var d = ['M', start.x, start.y, 'A', radius, radius, 0, largeArcFlag, 0, end.x, end.y];
    return d.join(' ');
  }

  clampFill = fill => Math.min(100, Math.max(0, fill));

  render() {
    const {
      size,
      width,
      backgroundWidth,
      tintColor,
      tintTransparency,
      backgroundColor,
      style,
      rotation,
      lineCap,
      fillLineCap = lineCap,
      arcSweepAngle,
      fill,
      children,
      childrenContainerStyle,
      padding,
      renderCap,
      dashedBackground,
      dashedTint
    } = this.props;

    const maxWidthCircle = backgroundWidth ? Math.max(width, backgroundWidth) : width;
    const sizeWithPadding = size / 2 + padding / 2;
    const radius = size / 2 - maxWidthCircle / 2 - padding / 2;

    const currentFillAngle = (arcSweepAngle * this.clampFill(fill)) / 100;
    const backgroundPath = this.circlePath(
      sizeWithPadding,
      sizeWithPadding,
      radius,
      tintTransparency ? 0 : currentFillAngle,
      arcSweepAngle
    );
    const circlePath = this.circlePath(
      sizeWithPadding,
      sizeWithPadding,
      radius,
      0,
      currentFillAngle
    );
    const coordinate = this.polarToCartesian(
      sizeWithPadding,
      sizeWithPadding,
      radius,
      currentFillAngle
    );
    const cap = this.props.renderCap ? this.props.renderCap({ center: coordinate }) : null;

    const offset = size - maxWidthCircle * 2;

    const localChildrenContainerStyle = {
      ...{
        position: 'absolute',
        left: maxWidthCircle + padding / 2,
        top: maxWidthCircle + padding / 2,
        width: offset,
        height: offset,
        borderRadius: offset / 2,
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'hidden',
      },
      ...childrenContainerStyle,
    }

    const strokeDasharrayTint = dashedTint.gap > 0 ?
      Object.values(dashedTint)
      .map(value => parseInt(value))
      : null;

    const strokeDasharrayBackground = dashedBackground.gap > 0 ?
      Object.values(dashedBackground)
      .map(value => parseInt(value))
      : null;

    return (
      <View style={style}>
        <Svg width={size + padding} height={size + padding}>
          <G rotation={rotation} originX={(size + padding) / 2} originY={(size + padding) / 2}>
            {backgroundColor && (
              <Path
                d={backgroundPath}
                stroke={backgroundColor}
                strokeWidth={backgroundWidth || width}
                strokeLinecap={lineCap}
                strokeDasharray={strokeDasharrayBackground}
                fill="transparent"
              />
            )}
            {fill > 0 && (
              <Path
                d={circlePath}
                stroke={tintColor}
                strokeWidth={width}
                strokeLinecap={fillLineCap}
                strokeDasharray={strokeDasharrayTint}
                fill="transparent"
              />
            )}
            {cap}
          </G>
        </Svg>
        {children && <View style={localChildrenContainerStyle}>{children(fill)}</View>}
      </View>
    );
  }
}

CircularProgress.propTypes = {
  style: PropTypes.object,
  size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.instanceOf(Animated.Value),
  ]),
  fill: PropTypes.number.isRequired,
  width: PropTypes.number.isRequired,
  backgroundWidth: PropTypes.number,
  tintColor: PropTypes.string,
  tintTransparency: PropTypes.bool,
  backgroundColor: PropTypes.string,
  rotation: PropTypes.number,
  lineCap: PropTypes.string,
  arcSweepAngle: PropTypes.number,
  children: PropTypes.func,
  childrenContainerStyle: PropTypes.object,
  padding: PropTypes.number,
  renderCap: PropTypes.func,
  dashedBackground: PropTypes.object,
  dashedTint: PropTypes.object
};

CircularProgress.defaultProps = {
  tintColor: 'black',
  tintTransparency: true,
  rotation: 90,
  lineCap: 'butt',
  arcSweepAngle: 360,
  padding: 0,
  dashedBackground: { width: 0, gap: 0 },
  dashedTint: { width: 0, gap: 0 },
};
<commit_msg>chain isRequired<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { Animated, View } from 'react-native';
import { Svg, Path, G } from 'react-native-svg';

export default class CircularProgress extends React.PureComponent {
  polarToCartesian(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180.0;
    return {
      x: centerX + radius * Math.cos(angleInRadians),
      y: centerY + radius * Math.sin(angleInRadians),
    };
  }

  circlePath(x, y, radius, startAngle, endAngle) {
    var start = this.polarToCartesian(x, y, radius, endAngle * 0.9999);
    var end = this.polarToCartesian(x, y, radius, startAngle);
    var largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1';
    var d = ['M', start.x, start.y, 'A', radius, radius, 0, largeArcFlag, 0, end.x, end.y];
    return d.join(' ');
  }

  clampFill = fill => Math.min(100, Math.max(0, fill));

  render() {
    const {
      size,
      width,
      backgroundWidth,
      tintColor,
      tintTransparency,
      backgroundColor,
      style,
      rotation,
      lineCap,
      fillLineCap = lineCap,
      arcSweepAngle,
      fill,
      children,
      childrenContainerStyle,
      padding,
      renderCap,
      dashedBackground,
      dashedTint
    } = this.props;

    const maxWidthCircle = backgroundWidth ? Math.max(width, backgroundWidth) : width;
    const sizeWithPadding = size / 2 + padding / 2;
    const radius = size / 2 - maxWidthCircle / 2 - padding / 2;

    const currentFillAngle = (arcSweepAngle * this.clampFill(fill)) / 100;
    const backgroundPath = this.circlePath(
      sizeWithPadding,
      sizeWithPadding,
      radius,
      tintTransparency ? 0 : currentFillAngle,
      arcSweepAngle
    );
    const circlePath = this.circlePath(
      sizeWithPadding,
      sizeWithPadding,
      radius,
      0,
      currentFillAngle
    );
    const coordinate = this.polarToCartesian(
      sizeWithPadding,
      sizeWithPadding,
      radius,
      currentFillAngle
    );
    const cap = this.props.renderCap ? this.props.renderCap({ center: coordinate }) : null;

    const offset = size - maxWidthCircle * 2;

    const localChildrenContainerStyle = {
      ...{
        position: 'absolute',
        left: maxWidthCircle + padding / 2,
        top: maxWidthCircle + padding / 2,
        width: offset,
        height: offset,
        borderRadius: offset / 2,
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'hidden',
      },
      ...childrenContainerStyle,
    }

    const strokeDasharrayTint = dashedTint.gap > 0 ?
      Object.values(dashedTint)
      .map(value => parseInt(value))
      : null;

    const strokeDasharrayBackground = dashedBackground.gap > 0 ?
      Object.values(dashedBackground)
      .map(value => parseInt(value))
      : null;

    return (
      <View style={style}>
        <Svg width={size + padding} height={size + padding}>
          <G rotation={rotation} originX={(size + padding) / 2} originY={(size + padding) / 2}>
            {backgroundColor && (
              <Path
                d={backgroundPath}
                stroke={backgroundColor}
                strokeWidth={backgroundWidth || width}
                strokeLinecap={lineCap}
                strokeDasharray={strokeDasharrayBackground}
                fill="transparent"
              />
            )}
            {fill > 0 && (
              <Path
                d={circlePath}
                stroke={tintColor}
                strokeWidth={width}
                strokeLinecap={fillLineCap}
                strokeDasharray={strokeDasharrayTint}
                fill="transparent"
              />
            )}
            {cap}
          </G>
        </Svg>
        {children && <View style={localChildrenContainerStyle}>{children(fill)}</View>}
      </View>
    );
  }
}

CircularProgress.propTypes = {
  style: PropTypes.object,
  size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.instanceOf(Animated.Value),
  ]).isRequired,
  fill: PropTypes.number.isRequired,
  width: PropTypes.number.isRequired,
  backgroundWidth: PropTypes.number,
  tintColor: PropTypes.string,
  tintTransparency: PropTypes.bool,
  backgroundColor: PropTypes.string,
  rotation: PropTypes.number,
  lineCap: PropTypes.string,
  arcSweepAngle: PropTypes.number,
  children: PropTypes.func,
  childrenContainerStyle: PropTypes.object,
  padding: PropTypes.number,
  renderCap: PropTypes.func,
  dashedBackground: PropTypes.object,
  dashedTint: PropTypes.object
};

CircularProgress.defaultProps = {
  tintColor: 'black',
  tintTransparency: true,
  rotation: 90,
  lineCap: 'butt',
  arcSweepAngle: 360,
  padding: 0,
  dashedBackground: { width: 0, gap: 0 },
  dashedTint: { width: 0, gap: 0 },
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2015 S-Core Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define([
    './plugin',
    'webida-lib/plugins/workbench/plugin',
    'webida-lib/app',
    'webida-lib/widgets/views/splitviewcontainer',
    'webida-lib/widgets/views/viewmanager',
    'webida-lib/widgets/dialogs/buttoned-dialog/ButtonedDialog',
    'dojo/dom-style',
    'dojo/dom-geometry',
    'dojo/topic',
    'external/lodash/lodash.min',
    'webida-lib/util/logger/logger-client',
    './EditorManager'
], function (
    editors,
    workbench,
    ide,
    SplitViewContainer,
    vm,
    ButtonedDialog,
    domStyle,
    geometry,
    topic,
    _,
    Logger,
    EditorManager
) {
    'use strict';

    var logger = new Logger();
    //logger.setConfig('level', Logger.LEVELS.log);
    //logger.off();

    var editorManager = EditorManager.getInstance();

    var paneElement = $('
')[0];

    /**
     * Compatibility
     */
    function _getPartRegistry() {
        var page = workbench.getCurrentPage();
        return page.getPartRegistry();
    }

    function getPanel() {
        var docFrag = document.createDocumentFragment();
        docFrag.appendChild(paneElement);
        return docFrag;
    }

    var QUIT = 'Quit';

    function createDialog(file, title, action, canceled) {
    	console.log('createDialog('+file+', '+title+', action, canceled)');
        var dialog = new ButtonedDialog({
            title: 'Unsaved Changes in the File to ' + title,
            buttons: [
                {
                    caption: 'Save and ' + title,
                    methodOnClick: 'saveAndAction'
                },
                {
                    caption: title + ' without Saving',
                    methodOnClick: 'actionWithoutSaving'
                },
                {
                    caption: 'Cancel',
                    methodOnClick: 'canceled'
                }
            ],
            methodOnEnter: 'saveAnd' + title,
            saveAndAction: function () {
                if (title === QUIT) {
                    var registry = _getPartRegistry();
                    var parts = registry.getDirtyParts();
                    parts.forEach(function(part) {
                        part.save();
                    });
                    action();
                    dialog.hide();
                } else {
                    editorManager.requestSave(file.getPath(), null, function() {
                        action();
                        dialog.hide();
                    });
                }
            },
            actionWithoutSaving: function () {
                action();
                this.hide();
            },
            canceled: function () {
                if (canceled) {
                    canceled();
                }
                this.hide();
            },
            buttonsWidth: '140px',
            onHide: function () {
                dialog.destroyRecursive();
            },
            dialogClass: 'buttoned-dialog-text-only'
        });

        var name = file.name;
        if (title === QUIT) {
            name = file;
        }
        dialog.setContentArea(' File "' + name  + '" has unsaved changes. ' +
                ' Save and ' + title + ' this file? ');
        dialog.show();
    }

    function onPanelAppended() {
        var $elemTab = $('

');
        $(paneElement).append($elemTab);

        editors.splitViewContainer = new SplitViewContainer();
        editors.splitViewContainer.init({
            'splitCount': 2,
            'verticalSplit': false,
            'smartVisible': true,
            'rotatable': true
        }, 'editor-tab');
        vm.addToGroup(editors.splitViewContainer, 'editorView');

        topic.subscribe('editor-panel-resize', function () {
            var borderContainer = editors.splitViewContainer.widgetObject;
            var children = borderContainer.getChildren();
            var totalW = 5;  // including margin and splitter size
            var totalH = 5;  // including margin and splitter size
            var width, height;
            var child;
            var i;
            var ratioW, ratioH;
            for (i = 0; i < children.length; i++) {
                child = children[i];
                totalW += geometry.getMarginBox(child.domNode).w;
                totalH += geometry.getMarginBox(child.domNode).h;
            }

            for (i = 1; i < children.length; i++) {
                child = children[i];
                width = geometry.getMarginBox(child.domNode).w;
                height = geometry.getMarginBox(child.domNode).h;
                ratioW = ((width - 2) * 100 / totalW) + '%';
                ratioH = ((height - 2) * 100 / totalH) + '%';
                //console.log('total : ' +totalW+ ', content : '+ i  + ' : ' + width + ', ratio : '+ratioW);
                if (child.get('region') === 'right') {
                    if ($(child.domNode).css('width').split('%').length > 1) {
                        continue;
                    }
                    domStyle.set(child.domNode, 'width', ratioW);
                } else if (child.get('region') === 'bottom') {
                    if ($(child.domNode).css('height').split('%').length > 1) {
                        continue;
                    }
                    domStyle.set(child.domNode, 'height', ratioH);
                }
            }

        });

        /* viewcontainer supports 'dblclick' event
        var vcList = editors.splitViewContainer.getViewContainers();
        _.forEach(vcList, function (vc) {
            dojo.connect(vc.tabContainer, 'onDblClick', function (ev) {
                if (ev.currentTarget === vc.tabContainer.domNode) {
                    var parent = ev.srcElement.parentNode;
                    while (parent && parent.parentNode) {
                        if (parent === vc.tabContainer.domNode.firstElementChild) {
                            workbench.toggleFullScreen();
                            break;
                        }
                        parent = parent.parentNode;
                    }
                }
            });
        });
        */

        topic.subscribe('view.selected', function(event) {
            var view = event.view;
            var vc = event.viewContainer;
            if (!vc || (vc.getParent() !== editors.splitViewContainer)) {
                return;
            }
            if (view.partContainer) {
                var registry = _getPartRegistry();
                var part = view.partContainer.getPart();
                var currentPart = registry.getCurrentEditorPart();
                if (part !== currentPart) {
                    registry.setCurrentEditorPart(part);
                }
            }
        });

        topic.subscribe('view.focused', function(event) {
            var view = event.view;
            logger.info('view = ', view);
            var vc = event.viewContainer;
            if (!vc || (vc.getParent() !== editors.splitViewContainer)) {
                return;
            }
            if (view.partContainer) {
                var registry = _getPartRegistry();
                var part = view.partContainer.getPart();
                var currentPart = registry.getCurrentEditorPart();
                if (part !== currentPart) {
                    registry.setCurrentEditorPart(part);
                }
            }
        });

        topic.subscribe('view.quit', function () {

            ide.unregisterBeforeUnloadChecker('checkModifiedFiles');

            var ds;
            var registry = _getPartRegistry();
            var parts = registry.getDirtyParts();
            parts.forEach(function(part){
            	ds = part.getDataSource();
            	modifiedFileNames.push(ds.getPersistance().getName());
            });

            var action = function closeWindow() {

                try {
                    window.focus();

                    if (!window.opener) {
                        alert('Quit does not work when IDE was opened by a direct URL.\n' +
                              'Please close the browser tab to quit the IDE.');
                    } else {
                        //window.opener = window;
                        window.close();
                    }
                } catch (e) {
                    logger.log('First try to close App failed', e);

                    try {
                        window.open('', '_self', '');
                        window.close();
                    } catch (e) {
                        logger.log('Second try to close App failed', e);
                    }
                }
            };

            var cancel = function cancelSaveBeforeUnload() {
                ide.registerBeforeUnloadChecker('checkModifiedFiles', checkModifiedFiles);
            };

            if (parts.length > 0) {
                createDialog(modifiedFileNames.join(', '), QUIT, action, cancel);
            } else {
                action();
            }
        });

        function checkModifiedFiles() {

            var keys = Object.keys(editors.files);
            var modifiedFileNames = [];
            var len = keys.length;
            var part;
            for (var i = 0; i < len; i++) {
                var key = keys[i];
                var file = editors.files[key];
                part = editors.getPart(file);
                if (part.isDirty()) {
                    modifiedFileNames.push(file.name);
                }
            }

            if (modifiedFileNames.length > 0) {
                return 'You have unsaved changes in files: ' + modifiedFileNames.join(', ');
            }
        }

        ide.registerBeforeUnloadChecker('checkModifiedFiles', checkModifiedFiles);

        var lastStatus = ide.registerStatusContributorAndGetLastStatus('editor-view', function () {
            var status = {};
            var cursorDefault = {col: 0, row: 0};
            var splitVc = editors.splitViewContainer;
            var viewContainers = splitVc.getViewContainers();
            var vc, i, j;
            var totalW = 0;
            var totalH = 0;
            for (i = 0; i < viewContainers.length; i++) {
                vc = viewContainers[i];
                if (vc.getViewList().length > 0) {
                    totalW += geometry.getContentBox(vc.topContainer.domNode).w;
                    totalH += geometry.getContentBox(vc.topContainer.domNode).h;
                }
            }

            // status.viewContainers
            status.viewContainers = [];
            for (i = 0; i < viewContainers.length; i++) {
                vc = viewContainers[i];
                var viewList = vc.getViewList();
                var tabs = [];
                var selfile;
                var width = 0;
                var height = 0;
                if (viewList.length > 0) {
                    for (j = 0; j < viewList.length; j++) {
                        var view = viewList[j];
                        var file = editors.getFileByViewId(view.getId());
                        var cursor = editors.getCursor(file) || cursorDefault;
                        var foldings = file.viewer ? file.viewer.getFoldings() : [];
                                // temporary solution
                                // TODO: see why file.viewer sometimes is null.
                        tabs.push([cursor.col, cursor.row, file.path, foldings, file.openWithPart]);
                        console.log('--* path : ' + file.path);
                    }
                    selfile = editors.getFileByViewId(vc.getSelectedView().getId());
                    width = domStyle.get(vc.topContainer.domNode, 'width');
                    height = domStyle.get(vc.topContainer.domNode, 'height');

                    width = geometry.getContentBox(vc.topContainer.domNode).w;
                    height = geometry.getContentBox(vc.topContainer.domNode).h;
                    if (width > 0) {
                        width = parseInt((width * 100 / totalW), 10) + '%';
                    }
                    if (height > 0) {
                        height = parseInt((height * 100 / totalH), 10) + '%';
                    }
                }
                status.viewContainers.push({
                    tabs: tabs,
                    selected: selfile && selfile.path,
                    width: width,
                    height: height
                });
            }

            // status.viewLayout
            if (viewContainers.length > 0) {
                status.viewLayout = {
                    count: splitVc.get('splitCount'),
                    vertical: splitVc.get('verticalSplit')
                };
            }

            // status.recentFiles
            status.recentFiles = editors.recentFiles.exportToPlainArray();

            return status;
        });

        logger.info('lastStatus = ', lastStatus);

        if (lastStatus && lastStatus.viewContainers) {
            setTimeout(function () {
                editors.onloadPendingFilesCount = _.reduce(lastStatus.viewContainers, function (memo, vc) {
                    return memo + vc.tabs.length;
                }, 0);

                var tab;
                var openFileWithNamespace = function (path, opt, pos, foldings) {
                	topic.publish('editor/open', path, opt, function (file) {
                        logger.info('pos = ', pos);

                        _.defer(function () {
                            if (file.viewer && file.viewer.setCursor) {
                                file.viewer.setCursor(pos);
                            }
                            if (file.viewer && foldings) {
                                _.each(foldings, function (fold) {
                                    file.viewer.foldCodeRange(fold);
                                });
                            }
                        });

                        logger.log('opened file "' + path + '"');
                    });
                };

                var path = null;
                var opt = null;
                var pos = null;
                var vc;

                if (lastStatus.viewLayout && lastStatus.viewLayout.vertical) {
                    if (lastStatus.viewLayout.vertical === true) {
                        editors.splitViewContainer.set('verticalSplit', true);
                    } else {
                        editors.splitViewContainer.set('verticalSplit', false);
                    }
                }

                for (var i = 0; i < lastStatus.viewContainers.length; i++) {
                    vc = lastStatus.viewContainers[i];
                    var siblingList = [];
                    var j;
                    for (j = 0; j < vc.tabs.length; j++) {
                        siblingList.push(vc.tabs[j][2]);
                    }

                    for (j = 0; j < vc.tabs.length; j++) {
                        tab = vc.tabs[j];
                        opt = {};
                        path = tab[2];
                        if (path === vc.selected) {
                            opt.show = true;
                        } else {
                            opt.show = false;
                        }
                        opt.cellIndex = i;
                        opt.siblingList = siblingList;
                        opt.openWithPart = tab[4];
                        pos = {};
                        pos.col = tab[0];
                        pos.row = tab[1];
                        openFileWithNamespace(path, opt, pos, tab[3]);
                    }

                    var viewContainers = editors.splitViewContainer.getViewContainers();
                    //console.log($(viewContainers[i].topContainer.domNode).css('width'));
                    if (i > 0 && (vc.tabs.length > 0)) {
                        $(viewContainers[i].topContainer.domNode).css('width', vc.width);
                        $(viewContainers[i].topContainer.domNode).css('height', vc.height);
                    }
                }

                if (lastStatus.recentFiles) {
                    editors.recentFiles.importFromPlainArray(lastStatus.recentFiles);
                }
            }, 50);
        }
    }

    return {
        getPanel: getPanel,
        onPanelAppended: onPanelAppended
    };
});
<commit_msg>[TASK] Subscription for 'view.selected' removed<commit_after>/*
 * Copyright (c) 2012-2015 S-Core Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define([
    './plugin',
    'webida-lib/plugins/workbench/plugin',
    'webida-lib/app',
    'webida-lib/widgets/views/splitviewcontainer',
    'webida-lib/widgets/views/viewmanager',
    'webida-lib/widgets/dialogs/buttoned-dialog/ButtonedDialog',
    'dojo/dom-style',
    'dojo/dom-geometry',
    'dojo/topic',
    'external/lodash/lodash.min',
    'webida-lib/util/logger/logger-client',
    './EditorManager'
], function (
    editors,
    workbench,
    ide,
    SplitViewContainer,
    vm,
    ButtonedDialog,
    domStyle,
    geometry,
    topic,
    _,
    Logger,
    EditorManager
) {
    'use strict';

    var logger = new Logger();
    //logger.setConfig('level', Logger.LEVELS.log);
    //logger.off();

    var editorManager = EditorManager.getInstance();

    var paneElement = $('
')[0];

    /**
     * Compatibility
     */
    function _getPartRegistry() {
        var page = workbench.getCurrentPage();
        return page.getPartRegistry();
    }

    function getPanel() {
        var docFrag = document.createDocumentFragment();
        docFrag.appendChild(paneElement);
        return docFrag;
    }

    var QUIT = 'Quit';

    function createDialog(file, title, action, canceled) {
    	console.log('createDialog('+file+', '+title+', action, canceled)');
        var dialog = new ButtonedDialog({
            title: 'Unsaved Changes in the File to ' + title,
            buttons: [
                {
                    caption: 'Save and ' + title,
                    methodOnClick: 'saveAndAction'
                },
                {
                    caption: title + ' without Saving',
                    methodOnClick: 'actionWithoutSaving'
                },
                {
                    caption: 'Cancel',
                    methodOnClick: 'canceled'
                }
            ],
            methodOnEnter: 'saveAnd' + title,
            saveAndAction: function () {
                if (title === QUIT) {
                    var registry = _getPartRegistry();
                    var parts = registry.getDirtyParts();
                    parts.forEach(function(part) {
                        part.save();
                    });
                    action();
                    dialog.hide();
                } else {
                    editorManager.requestSave(file.getPath(), null, function() {
                        action();
                        dialog.hide();
                    });
                }
            },
            actionWithoutSaving: function () {
                action();
                this.hide();
            },
            canceled: function () {
                if (canceled) {
                    canceled();
                }
                this.hide();
            },
            buttonsWidth: '140px',
            onHide: function () {
                dialog.destroyRecursive();
            },
            dialogClass: 'buttoned-dialog-text-only'
        });

        var name = file.name;
        if (title === QUIT) {
            name = file;
        }
        dialog.setContentArea(' File "' + name  + '" has unsaved changes. ' +
                ' Save and ' + title + ' this file? ');
        dialog.show();
    }

    function onPanelAppended() {
        var $elemTab = $('

');
        $(paneElement).append($elemTab);

        editors.splitViewContainer = new SplitViewContainer();
        editors.splitViewContainer.init({
            'splitCount': 2,
            'verticalSplit': false,
            'smartVisible': true,
            'rotatable': true
        }, 'editor-tab');
        vm.addToGroup(editors.splitViewContainer, 'editorView');

        topic.subscribe('editor-panel-resize', function () {
            var borderContainer = editors.splitViewContainer.widgetObject;
            var children = borderContainer.getChildren();
            var totalW = 5;  // including margin and splitter size
            var totalH = 5;  // including margin and splitter size
            var width, height;
            var child;
            var i;
            var ratioW, ratioH;
            for (i = 0; i < children.length; i++) {
                child = children[i];
                totalW += geometry.getMarginBox(child.domNode).w;
                totalH += geometry.getMarginBox(child.domNode).h;
            }

            for (i = 1; i < children.length; i++) {
                child = children[i];
                width = geometry.getMarginBox(child.domNode).w;
                height = geometry.getMarginBox(child.domNode).h;
                ratioW = ((width - 2) * 100 / totalW) + '%';
                ratioH = ((height - 2) * 100 / totalH) + '%';
                //console.log('total : ' +totalW+ ', content : '+ i  + ' : ' + width + ', ratio : '+ratioW);
                if (child.get('region') === 'right') {
                    if ($(child.domNode).css('width').split('%').length > 1) {
                        continue;
                    }
                    domStyle.set(child.domNode, 'width', ratioW);
                } else if (child.get('region') === 'bottom') {
                    if ($(child.domNode).css('height').split('%').length > 1) {
                        continue;
                    }
                    domStyle.set(child.domNode, 'height', ratioH);
                }
            }

        });

        /* viewcontainer supports 'dblclick' event
        var vcList = editors.splitViewContainer.getViewContainers();
        _.forEach(vcList, function (vc) {
            dojo.connect(vc.tabContainer, 'onDblClick', function (ev) {
                if (ev.currentTarget === vc.tabContainer.domNode) {
                    var parent = ev.srcElement.parentNode;
                    while (parent && parent.parentNode) {
                        if (parent === vc.tabContainer.domNode.firstElementChild) {
                            workbench.toggleFullScreen();
                            break;
                        }
                        parent = parent.parentNode;
                    }
                }
            });
        });
        */

        topic.subscribe('view.focused', function(event) {
        	logger.info('view.focused');
            var view = event.view;
            //logger.info('view = ', view);
            var vc = event.viewContainer;
            if (!vc || (vc.getParent() !== editors.splitViewContainer)) {
                return;
            }
            if (view.partContainer) {
                var registry = _getPartRegistry();
                var part = view.partContainer.getPart();
                var currentPart = registry.getCurrentEditorPart();
                if (part !== currentPart) {
                    registry.setCurrentEditorPart(part);
                }
            }
        });

        topic.subscribe('view.quit', function () {

            ide.unregisterBeforeUnloadChecker('checkModifiedFiles');

            var ds;
            var registry = _getPartRegistry();
            var parts = registry.getDirtyParts();
            parts.forEach(function(part){
            	ds = part.getDataSource();
            	modifiedFileNames.push(ds.getPersistance().getName());
            });

            var action = function closeWindow() {

                try {
                    window.focus();

                    if (!window.opener) {
                        alert('Quit does not work when IDE was opened by a direct URL.\n' +
                              'Please close the browser tab to quit the IDE.');
                    } else {
                        //window.opener = window;
                        window.close();
                    }
                } catch (e) {
                    logger.log('First try to close App failed', e);

                    try {
                        window.open('', '_self', '');
                        window.close();
                    } catch (e) {
                        logger.log('Second try to close App failed', e);
                    }
                }
            };

            var cancel = function cancelSaveBeforeUnload() {
                ide.registerBeforeUnloadChecker('checkModifiedFiles', checkModifiedFiles);
            };

            if (parts.length > 0) {
                createDialog(modifiedFileNames.join(', '), QUIT, action, cancel);
            } else {
                action();
            }
        });

        function checkModifiedFiles() {

            var keys = Object.keys(editors.files);
            var modifiedFileNames = [];
            var len = keys.length;
            var part;
            for (var i = 0; i < len; i++) {
                var key = keys[i];
                var file = editors.files[key];
                part = editors.getPart(file);
                if (part.isDirty()) {
                    modifiedFileNames.push(file.name);
                }
            }

            if (modifiedFileNames.length > 0) {
                return 'You have unsaved changes in files: ' + modifiedFileNames.join(', ');
            }
        }

        ide.registerBeforeUnloadChecker('checkModifiedFiles', checkModifiedFiles);

        var lastStatus = ide.registerStatusContributorAndGetLastStatus('editor-view', function () {
            var status = {};
            var cursorDefault = {col: 0, row: 0};
            var splitVc = editors.splitViewContainer;
            var viewContainers = splitVc.getViewContainers();
            var vc, i, j;
            var totalW = 0;
            var totalH = 0;
            for (i = 0; i < viewContainers.length; i++) {
                vc = viewContainers[i];
                if (vc.getViewList().length > 0) {
                    totalW += geometry.getContentBox(vc.topContainer.domNode).w;
                    totalH += geometry.getContentBox(vc.topContainer.domNode).h;
                }
            }

            // status.viewContainers
            status.viewContainers = [];
            for (i = 0; i < viewContainers.length; i++) {
                vc = viewContainers[i];
                var viewList = vc.getViewList();
                var tabs = [];
                var selfile;
                var width = 0;
                var height = 0;
                if (viewList.length > 0) {
                    for (j = 0; j < viewList.length; j++) {
                        var view = viewList[j];
                        var file = editors.getFileByViewId(view.getId());
                        var cursor = editors.getCursor(file) || cursorDefault;
                        var foldings = file.viewer ? file.viewer.getFoldings() : [];
                                // temporary solution
                                // TODO: see why file.viewer sometimes is null.
                        tabs.push([cursor.col, cursor.row, file.path, foldings, file.openWithPart]);
                        console.log('--* path : ' + file.path);
                    }
                    selfile = editors.getFileByViewId(vc.getSelectedView().getId());
                    width = domStyle.get(vc.topContainer.domNode, 'width');
                    height = domStyle.get(vc.topContainer.domNode, 'height');

                    width = geometry.getContentBox(vc.topContainer.domNode).w;
                    height = geometry.getContentBox(vc.topContainer.domNode).h;
                    if (width > 0) {
                        width = parseInt((width * 100 / totalW), 10) + '%';
                    }
                    if (height > 0) {
                        height = parseInt((height * 100 / totalH), 10) + '%';
                    }
                }
                status.viewContainers.push({
                    tabs: tabs,
                    selected: selfile && selfile.path,
                    width: width,
                    height: height
                });
            }

            // status.viewLayout
            if (viewContainers.length > 0) {
                status.viewLayout = {
                    count: splitVc.get('splitCount'),
                    vertical: splitVc.get('verticalSplit')
                };
            }

            // status.recentFiles
            status.recentFiles = editors.recentFiles.exportToPlainArray();

            return status;
        });

        logger.info('lastStatus = ', lastStatus);

        if (lastStatus && lastStatus.viewContainers) {
            setTimeout(function () {
                editors.onloadPendingFilesCount = _.reduce(lastStatus.viewContainers, function (memo, vc) {
                    return memo + vc.tabs.length;
                }, 0);

                var tab;
                var openFileWithNamespace = function (path, opt, pos, foldings) {
                	topic.publish('editor/open', path, opt, function (file) {
                        logger.info('pos = ', pos);

                        _.defer(function () {
                            if (file.viewer && file.viewer.setCursor) {
                                file.viewer.setCursor(pos);
                            }
                            if (file.viewer && foldings) {
                                _.each(foldings, function (fold) {
                                    file.viewer.foldCodeRange(fold);
                                });
                            }
                        });

                        logger.log('opened file "' + path + '"');
                    });
                };

                var path = null;
                var opt = null;
                var pos = null;
                var vc;

                if (lastStatus.viewLayout && lastStatus.viewLayout.vertical) {
                    if (lastStatus.viewLayout.vertical === true) {
                        editors.splitViewContainer.set('verticalSplit', true);
                    } else {
                        editors.splitViewContainer.set('verticalSplit', false);
                    }
                }

                for (var i = 0; i < lastStatus.viewContainers.length; i++) {
                    vc = lastStatus.viewContainers[i];
                    var siblingList = [];
                    var j;
                    for (j = 0; j < vc.tabs.length; j++) {
                        siblingList.push(vc.tabs[j][2]);
                    }

                    for (j = 0; j < vc.tabs.length; j++) {
                        tab = vc.tabs[j];
                        opt = {};
                        path = tab[2];
                        if (path === vc.selected) {
                            opt.show = true;
                        } else {
                            opt.show = false;
                        }
                        opt.cellIndex = i;
                        opt.siblingList = siblingList;
                        opt.openWithPart = tab[4];
                        pos = {};
                        pos.col = tab[0];
                        pos.row = tab[1];
                        openFileWithNamespace(path, opt, pos, tab[3]);
                    }

                    var viewContainers = editors.splitViewContainer.getViewContainers();
                    //console.log($(viewContainers[i].topContainer.domNode).css('width'));
                    if (i > 0 && (vc.tabs.length > 0)) {
                        $(viewContainers[i].topContainer.domNode).css('width', vc.width);
                        $(viewContainers[i].topContainer.domNode).css('height', vc.height);
                    }
                }

                if (lastStatus.recentFiles) {
                    editors.recentFiles.importFromPlainArray(lastStatus.recentFiles);
                }
            }, 50);
        }
    }

    return {
        getPanel: getPanel,
        onPanelAppended: onPanelAppended
    };
});
<|endoftext|>


<commit_before>/**
 * EventEmitter v3.1.6
 * https://github.com/Wolfy87/EventEmitter
 *
 * Oliver Caldwell (http://oli.me.uk)
 * Creative Commons Attribution 3.0 Unported License (http://creativecommons.org/licenses/by/3.0/)
 */(function(e){"use strict";function t(){this._events={},this._maxListeners=10}function n(e,t,n,r,i){this.type=e,this.listener=t,this.scope=n,this.once=r,this.instance=i}n.prototype.fire=function(e){this.listener.apply(this.scope||this.instance,e);if(this.once){var t=this.instance.listeners(this.type).length;this.instance.removeListener(this.type,this.listener,this.scope);if(t!==this.instance.listeners(this.type).length)return!1}},t.prototype.eachListener=function(e,t){var n=null,r=null,i=null;if(this._events.hasOwnProperty(e)){r=this._events[e];for(n=r.length;n--;){i=t.call(this,r[n],n);if(i===!1)n-=1;else if(i===!0)break}}return this},t.prototype.addListener=function(e,t,r,i){return this._events.hasOwnProperty(e)||(this._events[e]=[]),this._events[e].push(new n(e,t,r,i,this)),this.emit("newListener",e,t,r,i),this._maxListeners&&!this._events[e].warned&&this._events[e].length>this._maxListeners&&(typeof console!="undefined"&&console.warn("Possible EventEmitter memory leak detected. "+this._events[e].length+" listeners added. Use emitter.setMaxListeners() to increase limit."),this._events[e].warned=!0),this},t.prototype.on=t.prototype.addListener,t.prototype.once=function(e,t,n){return this.addListener(e,t,n,!0)},t.prototype.removeListener=function(e,t,n){return this.eachListener(e,function(r,i){r.listener===t&&(!n||r.scope===n)&&this._events[e].splice(i,1)}),this._events[e]&&this._events[e].length===0&&delete this._events[e],this},t.prototype.off=t.prototype.removeListener,t.prototype.removeAllListeners=function(e){return e&&this._events.hasOwnProperty(e)?delete this._events[e]:e||(this._events={}),this},t.prototype.listeners=function(e){if(this._events.hasOwnProperty(e)){var t=[];return this.eachListener(e,function(e){t.push(e.listener)}),t}return[]},t.prototype.emit=function(e){var t=[],n=null;for(n=1;n<arguments.length;n+=1)t.push(arguments[n]);return this.eachListener(e,function(e){return e.fire(t)}),this},t.prototype.setMaxListeners=function(e){return this._maxListeners=e,this},t.extend=function(){var e={},t=this.prototype,n=null;for(n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e},typeof define=="function"&&define.amd&&define(function(){return t}),e.EventEmitter=t})(this);<commit_msg>Recompiled the minified version.<commit_after>/**
 * EventEmitter v3.1.7
 * https://github.com/Wolfy87/EventEmitter
 *
 * Oliver Caldwell (http://oli.me.uk)
 * Creative Commons Attribution 3.0 Unported License (http://creativecommons.org/licenses/by/3.0/)
 */(function(e){"use strict";function t(){this._events={},this._maxListeners=10}function n(e,t,n,r,i){this.type=e,this.listener=t,this.scope=n,this.once=r,this.instance=i}n.prototype.fire=function(e){this.listener.apply(this.scope||this.instance,e);if(this.once){var t=this.instance.listeners(this.type).length;this.instance.removeListener(this.type,this.listener,this.scope);if(t!==this.instance.listeners(this.type).length)return!1}},t.prototype.eachListener=function(e,t){var n=null,r=null,i=null;if(this._events.hasOwnProperty(e)){r=this._events[e];for(n=0;n<r.length;n+=1){i=t.call(this,r[n],n);if(i===!1)n-=1;else if(i===!0)break}}return this},t.prototype.addListener=function(e,t,r,i){return this._events.hasOwnProperty(e)||(this._events[e]=[]),this._events[e].push(new n(e,t,r,i,this)),this.emit("newListener",e,t,r,i),this._maxListeners&&!this._events[e].warned&&this._events[e].length>this._maxListeners&&(typeof console!="undefined"&&console.warn("Possible EventEmitter memory leak detected. "+this._events[e].length+" listeners added. Use emitter.setMaxListeners() to increase limit."),this._events[e].warned=!0),this},t.prototype.on=t.prototype.addListener,t.prototype.once=function(e,t,n){return this.addListener(e,t,n,!0)},t.prototype.removeListener=function(e,t,n){return this.eachListener(e,function(r,i){r.listener===t&&(!n||r.scope===n)&&this._events[e].splice(i,1)}),this._events[e]&&this._events[e].length===0&&delete this._events[e],this},t.prototype.off=t.prototype.removeListener,t.prototype.removeAllListeners=function(e){return e&&this._events.hasOwnProperty(e)?delete this._events[e]:e||(this._events={}),this},t.prototype.listeners=function(e){if(this._events.hasOwnProperty(e)){var t=[];return this.eachListener(e,function(e){t.push(e.listener)}),t}return[]},t.prototype.emit=function(e){var t=[],n=null;for(n=1;n<arguments.length;n+=1)t.push(arguments[n]);return this.eachListener(e,function(e){return e.fire(t)}),this},t.prototype.setMaxListeners=function(e){return this._maxListeners=e,this},t.extend=function(){var e={},t=this.prototype,n=null;for(n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e},typeof define=="function"&&define.amd&&define(function(){return t}),e.EventEmitter=t})(this);<|endoftext|>


<commit_before>
setTimeout(function(){
  removeAD();
},1000);

function removeAD(){
	if(/.*\.qq\.com.*/.test(location.href)){//qq.coms
	   $("div[bosszone='rightAD'],.l_qq_com").remove();
	}

	//$("iframe").remove();

	$("[class]").each(function(){
	  var classArr= this.className.split(" ");
	  for(var i in classArr){
		var name=classArr[i];
		if(name&&test(name)){//判断为广告就移除
			 $(this).remove();
		}
	  }
	})

	$("[id]").each(function(){
		var id= this.id;
		if(id&&test(id)){//判断为广告就移除
			 $(this).remove();
		}
	});
}

function test(val){
	val=$.trim(val);
	if(isAllow(val)){
	  return false;
	}
	if(val=='sina_keyword_ad_area2')
	var arr=["_ad$","^ad_",".*_ad_.*","-ad$","^ad-",".*-ad-.*"];
	for(var i in arr){
	  if(new RegExp(arr[i],"i").test(val)){
		return true;
	  }
	}
	return false;
}

function isAllow(val){
	var arr=["sina_keyword_ad_area2"];
	for(var i in arr){
	  if( val==arr[i]){
		return true;
	  }
	}
	return false;
}
<commit_msg>删除新浪广告<commit_after>
setTimeout(function(){
  removeAD();
},1000);

function removeAD(){
	if(/.*\.qq\.com.*/.test(location.href)){//qq.coms
	   $("div[bosszone='rightAD'],.l_qq_com").remove();
	}

	//$("iframe").remove();

	$("[class]").each(function(){
	  var classArr= this.className.split(" ");
	  for(var i in classArr){
		var name=classArr[i];
		if(name&&test(name)){//判断为广告就移除
			 $(this).remove();
			 console.log("remove class:"+name);
		}
	  }
	})

	$("[id]").each(function(){
		var id= this.id;
		if(id&&test(id)){//判断为广告就移除
			 $(this).remove();
			 console.log("remove id:"+id);
		}
	});
}

function test(val){
	val=$.trim(val);
	if(isAllow(val)){
	  return false;
	}
	if(val=='sina_keyword_ad_area2')
	var arr=["_ad$","^ad_",".*_ad_.*","-ad$","^ad-",".*-ad-.*",'sinaad.*'];
	for(var i in arr){
	  if(new RegExp(arr[i],"i").test(val)){
		return true;
	  }
	}
	return false;
}

function isAllow(val){
	var arr=["sina_keyword_ad_area2"];
	for(var i in arr){
	  if( val==arr[i]){
		return true;
	  }
	}
	return false;
}
<|endoftext|>


<commit_before>const { Router } = require('express');

const router = Router();

const exampleData = [
  {
    id: 1,
    name: 'Tara Simmmons',
    email: 'tara.simmmons55@example.com'
  },
  {
    id: 2,
    name: 'Willie Romero',
    email: 'willie.romero57@example.com'
  },
  {
    id: 3,
    name: 'Holly Barnes',
    email: 'holly.barnes11@example.com'
  }
];

router.get('/users', (req, res) => res.send(exampleData));

router.use('/enums', require('./routes/Enums'));

router.use('/locations', require('./routes/Location'));

module.exports = router;
<commit_msg>:fire: Removed backend users code<commit_after>const { Router } = require('express');

const router = Router();

router.use('/enums', require('./routes/Enums'));

router.use('/locations', require('./routes/Location'));

module.exports = router;
<|endoftext|>


<commit_before>export default class Point {
  constructor(x, y, size = 1) {
    this.x = x;
    this.y = y;
    this.size = size;
  }

  static random(width, height) {
    return new Point(~~(Math.random() * width), ~~(Math.random() * height));
  }

  static from({x,y, size}) {
    return new Point(x, y, size);
  }

  move([x = 0, y = 0]) {
    return new Point(this.x + x, this.y + y);
  }

  wrap(width, height) {
    return new Point((this.x + width) % width, (this.y + height) % height);
  }

  inflate(size = 1.5) {
    return new Point(this.x, this.y, this.size * size);
  }

  equals(other) {
    return other && this.x === other.x && this.y === other.y;
  }
}
<commit_msg>wrap point even better<commit_after>function wrap(num, to) {
  num = num % to;
  if (num < 0) num+=to;
  return num;
}

export default class Point {
  constructor(x, y, size = 1) {
    this.x = x;
    this.y = y;
    this.size = size;
  }

  static random(width, height) {
    return new Point(~~(Math.random() * width), ~~(Math.random() * height));
  }

  static from({x,y, size}) {
    return new Point(x, y, size);
  }

  move([x = 0, y = 0]) {
    return new Point(this.x + x, this.y + y);
  }

  wrap(width, height) {
    return new Point(wrap(this.x, width), wrap(this.y, height));
  }

  inflate(size = 1.5) {
    return new Point(this.x, this.y, this.size * size);
  }

  equals(other) {
    return other && this.x === other.x && this.y === other.y;
  }
}
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Editor = function () {

	var SIGNALS = signals;

	this.signals = {

		// script

		editScript: new SIGNALS.Signal(),

		// player

		startPlayer: new SIGNALS.Signal(),
		stopPlayer: new SIGNALS.Signal(),

		// actions

		// showDialog: new SIGNALS.Signal(),

		// notifications

		editorCleared: new SIGNALS.Signal(),

		savingStarted: new SIGNALS.Signal(),
		savingFinished: new SIGNALS.Signal(),

		themeChanged: new SIGNALS.Signal(),

		transformModeChanged: new SIGNALS.Signal(),
		snapChanged: new SIGNALS.Signal(),
		spaceChanged: new SIGNALS.Signal(),
		rendererChanged: new SIGNALS.Signal(),

		sceneGraphChanged: new SIGNALS.Signal(),

		cameraChanged: new SIGNALS.Signal(),

		geometryChanged: new SIGNALS.Signal(),

		objectSelected: new SIGNALS.Signal(),
		objectFocused: new SIGNALS.Signal(),

		objectAdded: new SIGNALS.Signal(),
		objectChanged: new SIGNALS.Signal(),
		objectRemoved: new SIGNALS.Signal(),

		helperAdded: new SIGNALS.Signal(),
		helperRemoved: new SIGNALS.Signal(),

		materialChanged: new SIGNALS.Signal(),

		scriptAdded: new SIGNALS.Signal(),
		scriptChanged: new SIGNALS.Signal(),
		scriptRemoved: new SIGNALS.Signal(),

		fogTypeChanged: new SIGNALS.Signal(),
		fogColorChanged: new SIGNALS.Signal(),
		fogParametersChanged: new SIGNALS.Signal(),
		windowResize: new SIGNALS.Signal(),

		showGridChanged: new SIGNALS.Signal()

	};

	this.config = new Config();
	this.history = new History( this );
	this.storage = new Storage();
	this.loader = new Loader( this );

	this.camera = new THREE.PerspectiveCamera( 50, 1, 1, 100000 );
	this.camera.position.set( 500, 250, 500 );
	this.camera.lookAt( new THREE.Vector3() );
	this.camera.name = 'Camera';

	this.scene = new THREE.Scene();
	this.scene.name = 'Scene';

	this.sceneHelpers = new THREE.Scene();

	this.object = {};
	this.geometries = {};
	this.materials = {};
	this.textures = {};
	this.scripts = {};

	this.selected = null;
	this.helpers = {};

};

Editor.prototype = {

	setTheme: function ( value ) {

		document.getElementById( 'theme' ).href = value;

		this.signals.themeChanged.dispatch( value );

	},

	/*
	showDialog: function ( value ) {

		this.signals.showDialog.dispatch( value );

	},
	*/

	//

	setScene: function ( scene ) {

		this.scene.uuid = scene.uuid;
		this.scene.name = scene.name;
		this.scene.userData = JSON.parse( JSON.stringify( scene.userData ) );

		// avoid render per object

		this.signals.sceneGraphChanged.active = false;

		while ( scene.children.length > 0 ) {

			this.addObject( scene.children[ 0 ] );

		}

		this.signals.sceneGraphChanged.active = true;
		this.signals.sceneGraphChanged.dispatch();

	},

	//

	addObject: function ( object ) {

		var scope = this;

		object.traverse( function ( child ) {

			if ( child.geometry !== undefined ) scope.addGeometry( child.geometry );
			if ( child.material !== undefined ) scope.addMaterial( child.material );

			scope.addHelper( child );

		} );

		this.scene.add( object );

		this.signals.objectAdded.dispatch( object );
		this.signals.sceneGraphChanged.dispatch();

	},

	moveObject: function ( object, parent, before ) {

		if ( parent === undefined ) {

			parent = this.scene;

		}

		parent.add( object );

		// sort children array

		if ( before !== undefined ) {

			var index = parent.children.indexOf( before );
			parent.children.splice( index, 0, object );
			parent.children.pop();

		}

		this.signals.sceneGraphChanged.dispatch();

	},

	nameObject: function ( object, name ) {

		object.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	removeObject: function ( object ) {

		if ( object.parent === null ) return; // avoid deleting the camera or scene

		var scope = this;

		object.traverse( function ( child ) {

			scope.removeHelper( child );

		} );

		object.parent.remove( object );

		this.signals.objectRemoved.dispatch( object );
		this.signals.sceneGraphChanged.dispatch();

	},

	addGeometry: function ( geometry ) {

		this.geometries[ geometry.uuid ] = geometry;

	},

	setGeometryName: function ( geometry, name ) {

		geometry.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	addMaterial: function ( material ) {

		this.materials[ material.uuid ] = material;

	},

	setMaterialName: function ( material, name ) {

		material.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	addTexture: function ( texture ) {

		this.textures[ texture.uuid ] = texture;

	},

	//

	addHelper: function () {

		var geometry = new THREE.SphereGeometry( 20, 4, 2 );
		var material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );

		return function ( object ) {

			var helper;

			if ( object instanceof THREE.Camera ) {

				helper = new THREE.CameraHelper( object, 10 );

			} else if ( object instanceof THREE.PointLight ) {

				helper = new THREE.PointLightHelper( object, 10 );

			} else if ( object instanceof THREE.DirectionalLight ) {

				helper = new THREE.DirectionalLightHelper( object, 20 );

			} else if ( object instanceof THREE.SpotLight ) {

				helper = new THREE.SpotLightHelper( object, 10 );

			} else if ( object instanceof THREE.HemisphereLight ) {

				helper = new THREE.HemisphereLightHelper( object, 10 );

			} else if ( object instanceof THREE.SkinnedMesh ) {

				helper = new THREE.SkeletonHelper( object );

			} else {

				// no helper for this object type
				return;

			}

			var picker = new THREE.Mesh( geometry, material );
			picker.name = 'picker';
			picker.userData.object = object;
			picker.visible = false;
			helper.add( picker );

			this.sceneHelpers.add( helper );
			this.helpers[ object.id ] = helper;

			this.signals.helperAdded.dispatch( helper );

		};

	}(),

	removeHelper: function ( object ) {

		if ( this.helpers[ object.id ] !== undefined ) {

			var helper = this.helpers[ object.id ];
			helper.parent.remove( helper );

			delete this.helpers[ object.id ];

			this.signals.helperRemoved.dispatch( helper );

		}

	},

	//

	addScript: function ( object, script ) {

		if ( this.scripts[ object.uuid ] === undefined ) {

			this.scripts[ object.uuid ] = [];

		}

		this.scripts[ object.uuid ].push( script );

		this.signals.scriptAdded.dispatch( script );

	},

	removeScript: function ( object, script ) {

		if ( this.scripts[ object.uuid ] === undefined ) return;

		var index = this.scripts[ object.uuid ].indexOf( script );

		if ( index !== - 1 ) {

			this.scripts[ object.uuid ].splice( index, 1 );

		}

		this.signals.scriptRemoved.dispatch( script );

	},

	//

	select: function ( object ) {

		if ( this.selected === object ) return;

		var uuid = null;

		if ( object !== null ) {

			uuid = object.uuid;

		}

		this.selected = object;

		this.config.setKey( 'selected', uuid );
		this.signals.objectSelected.dispatch( object );

	},

	selectById: function ( id ) {

		if ( id === this.camera.id ) {

			this.select( this.camera );
			return;

		}

		this.select( this.scene.getObjectById( id, true ) );

	},

	selectByUuid: function ( uuid ) {

		var scope = this;

		this.scene.traverse( function ( child ) {

			if ( child.uuid === uuid ) {

				scope.select( child );

			}

		} );

	},

	deselect: function () {

		this.select( null );

	},

	focus: function ( object ) {

		this.signals.objectFocused.dispatch( object );

	},

	focusById: function ( id ) {

		this.focus( this.scene.getObjectById( id, true ) );

	},

	clear: function () {

		this.history.clear();

		this.camera.position.set( 500, 250, 500 );
		this.camera.lookAt( new THREE.Vector3() );

		var objects = this.scene.children;

		while ( objects.length > 0 ) {

			this.removeObject( objects[ 0 ] );

		}

		this.geometries = {};
		this.materials = {};
		this.textures = {};
		this.scripts = {};

		this.deselect();

		this.signals.editorCleared.dispatch();

	},

	//

	fromJSON: function ( json ) {

		var loader = new THREE.ObjectLoader();

		// backwards

		if ( json.scene === undefined ) {

			this.setScene( loader.parse( json ) );
			return;

		}

		// TODO: Clean this up somehow

		var camera = loader.parse( json.camera );

		this.camera.position.copy( camera.position );
		this.camera.rotation.copy( camera.rotation );
		this.camera.aspect = camera.aspect;
		this.camera.near = camera.near;
		this.camera.far = camera.far;

		this.setScene( loader.parse( json.scene ) );
		this.scripts = json.scripts;

	},

	toJSON: function () {

		return {

			project: {
				vr: this.config.getKey( 'project/vr' )
			},
			camera: this.camera.toJSON(),
			scene: this.scene.toJSON(),
			scripts: this.scripts

		};

	}

}
<commit_msg>Editor: Fixed pickers.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Editor = function () {

	var SIGNALS = signals;

	this.signals = {

		// script

		editScript: new SIGNALS.Signal(),

		// player

		startPlayer: new SIGNALS.Signal(),
		stopPlayer: new SIGNALS.Signal(),

		// actions

		// showDialog: new SIGNALS.Signal(),

		// notifications

		editorCleared: new SIGNALS.Signal(),

		savingStarted: new SIGNALS.Signal(),
		savingFinished: new SIGNALS.Signal(),

		themeChanged: new SIGNALS.Signal(),

		transformModeChanged: new SIGNALS.Signal(),
		snapChanged: new SIGNALS.Signal(),
		spaceChanged: new SIGNALS.Signal(),
		rendererChanged: new SIGNALS.Signal(),

		sceneGraphChanged: new SIGNALS.Signal(),

		cameraChanged: new SIGNALS.Signal(),

		geometryChanged: new SIGNALS.Signal(),

		objectSelected: new SIGNALS.Signal(),
		objectFocused: new SIGNALS.Signal(),

		objectAdded: new SIGNALS.Signal(),
		objectChanged: new SIGNALS.Signal(),
		objectRemoved: new SIGNALS.Signal(),

		helperAdded: new SIGNALS.Signal(),
		helperRemoved: new SIGNALS.Signal(),

		materialChanged: new SIGNALS.Signal(),

		scriptAdded: new SIGNALS.Signal(),
		scriptChanged: new SIGNALS.Signal(),
		scriptRemoved: new SIGNALS.Signal(),

		fogTypeChanged: new SIGNALS.Signal(),
		fogColorChanged: new SIGNALS.Signal(),
		fogParametersChanged: new SIGNALS.Signal(),
		windowResize: new SIGNALS.Signal(),

		showGridChanged: new SIGNALS.Signal()

	};

	this.config = new Config();
	this.history = new History( this );
	this.storage = new Storage();
	this.loader = new Loader( this );

	this.camera = new THREE.PerspectiveCamera( 50, 1, 1, 100000 );
	this.camera.position.set( 500, 250, 500 );
	this.camera.lookAt( new THREE.Vector3() );
	this.camera.name = 'Camera';

	this.scene = new THREE.Scene();
	this.scene.name = 'Scene';

	this.sceneHelpers = new THREE.Scene();

	this.object = {};
	this.geometries = {};
	this.materials = {};
	this.textures = {};
	this.scripts = {};

	this.selected = null;
	this.helpers = {};

};

Editor.prototype = {

	setTheme: function ( value ) {

		document.getElementById( 'theme' ).href = value;

		this.signals.themeChanged.dispatch( value );

	},

	/*
	showDialog: function ( value ) {

		this.signals.showDialog.dispatch( value );

	},
	*/

	//

	setScene: function ( scene ) {

		this.scene.uuid = scene.uuid;
		this.scene.name = scene.name;
		this.scene.userData = JSON.parse( JSON.stringify( scene.userData ) );

		// avoid render per object

		this.signals.sceneGraphChanged.active = false;

		while ( scene.children.length > 0 ) {

			this.addObject( scene.children[ 0 ] );

		}

		this.signals.sceneGraphChanged.active = true;
		this.signals.sceneGraphChanged.dispatch();

	},

	//

	addObject: function ( object ) {

		var scope = this;

		object.traverse( function ( child ) {

			if ( child.geometry !== undefined ) scope.addGeometry( child.geometry );
			if ( child.material !== undefined ) scope.addMaterial( child.material );

			scope.addHelper( child );

		} );

		this.scene.add( object );

		this.signals.objectAdded.dispatch( object );
		this.signals.sceneGraphChanged.dispatch();

	},

	moveObject: function ( object, parent, before ) {

		if ( parent === undefined ) {

			parent = this.scene;

		}

		parent.add( object );

		// sort children array

		if ( before !== undefined ) {

			var index = parent.children.indexOf( before );
			parent.children.splice( index, 0, object );
			parent.children.pop();

		}

		this.signals.sceneGraphChanged.dispatch();

	},

	nameObject: function ( object, name ) {

		object.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	removeObject: function ( object ) {

		if ( object.parent === null ) return; // avoid deleting the camera or scene

		var scope = this;

		object.traverse( function ( child ) {

			scope.removeHelper( child );

		} );

		object.parent.remove( object );

		this.signals.objectRemoved.dispatch( object );
		this.signals.sceneGraphChanged.dispatch();

	},

	addGeometry: function ( geometry ) {

		this.geometries[ geometry.uuid ] = geometry;

	},

	setGeometryName: function ( geometry, name ) {

		geometry.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	addMaterial: function ( material ) {

		this.materials[ material.uuid ] = material;

	},

	setMaterialName: function ( material, name ) {

		material.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	addTexture: function ( texture ) {

		this.textures[ texture.uuid ] = texture;

	},

	//

	addHelper: function () {

		var geometry = new THREE.SphereGeometry( 20, 4, 2 );
		var material = new THREE.MeshBasicMaterial( { color: 0xff0000, visible: false } );

		return function ( object ) {

			var helper;

			if ( object instanceof THREE.Camera ) {

				helper = new THREE.CameraHelper( object, 10 );

			} else if ( object instanceof THREE.PointLight ) {

				helper = new THREE.PointLightHelper( object, 10 );

			} else if ( object instanceof THREE.DirectionalLight ) {

				helper = new THREE.DirectionalLightHelper( object, 20 );

			} else if ( object instanceof THREE.SpotLight ) {

				helper = new THREE.SpotLightHelper( object, 10 );

			} else if ( object instanceof THREE.HemisphereLight ) {

				helper = new THREE.HemisphereLightHelper( object, 10 );

			} else if ( object instanceof THREE.SkinnedMesh ) {

				helper = new THREE.SkeletonHelper( object );

			} else {

				// no helper for this object type
				return;

			}

			var picker = new THREE.Mesh( geometry, material );
			picker.name = 'picker';
			picker.userData.object = object;
			helper.add( picker );

			this.sceneHelpers.add( helper );
			this.helpers[ object.id ] = helper;

			this.signals.helperAdded.dispatch( helper );

		};

	}(),

	removeHelper: function ( object ) {

		if ( this.helpers[ object.id ] !== undefined ) {

			var helper = this.helpers[ object.id ];
			helper.parent.remove( helper );

			delete this.helpers[ object.id ];

			this.signals.helperRemoved.dispatch( helper );

		}

	},

	//

	addScript: function ( object, script ) {

		if ( this.scripts[ object.uuid ] === undefined ) {

			this.scripts[ object.uuid ] = [];

		}

		this.scripts[ object.uuid ].push( script );

		this.signals.scriptAdded.dispatch( script );

	},

	removeScript: function ( object, script ) {

		if ( this.scripts[ object.uuid ] === undefined ) return;

		var index = this.scripts[ object.uuid ].indexOf( script );

		if ( index !== - 1 ) {

			this.scripts[ object.uuid ].splice( index, 1 );

		}

		this.signals.scriptRemoved.dispatch( script );

	},

	//

	select: function ( object ) {

		if ( this.selected === object ) return;

		var uuid = null;

		if ( object !== null ) {

			uuid = object.uuid;

		}

		this.selected = object;

		this.config.setKey( 'selected', uuid );
		this.signals.objectSelected.dispatch( object );

	},

	selectById: function ( id ) {

		if ( id === this.camera.id ) {

			this.select( this.camera );
			return;

		}

		this.select( this.scene.getObjectById( id, true ) );

	},

	selectByUuid: function ( uuid ) {

		var scope = this;

		this.scene.traverse( function ( child ) {

			if ( child.uuid === uuid ) {

				scope.select( child );

			}

		} );

	},

	deselect: function () {

		this.select( null );

	},

	focus: function ( object ) {

		this.signals.objectFocused.dispatch( object );

	},

	focusById: function ( id ) {

		this.focus( this.scene.getObjectById( id, true ) );

	},

	clear: function () {

		this.history.clear();

		this.camera.position.set( 500, 250, 500 );
		this.camera.lookAt( new THREE.Vector3() );

		var objects = this.scene.children;

		while ( objects.length > 0 ) {

			this.removeObject( objects[ 0 ] );

		}

		this.geometries = {};
		this.materials = {};
		this.textures = {};
		this.scripts = {};

		this.deselect();

		this.signals.editorCleared.dispatch();

	},

	//

	fromJSON: function ( json ) {

		var loader = new THREE.ObjectLoader();

		// backwards

		if ( json.scene === undefined ) {

			this.setScene( loader.parse( json ) );
			return;

		}

		// TODO: Clean this up somehow

		var camera = loader.parse( json.camera );

		this.camera.position.copy( camera.position );
		this.camera.rotation.copy( camera.rotation );
		this.camera.aspect = camera.aspect;
		this.camera.near = camera.near;
		this.camera.far = camera.far;

		this.setScene( loader.parse( json.scene ) );
		this.scripts = json.scripts;

	},

	toJSON: function () {

		return {

			project: {
				vr: this.config.getKey( 'project/vr' )
			},
			camera: this.camera.toJSON(),
			scene: this.scene.toJSON(),
			scripts: this.scripts

		};

	}

}
<|endoftext|>