<commit_before>/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at http://www.mozillapopcorn.org/butter-license.txt */

define(
[
  "core/logger",
//  "core/eventmanager",
  "util/dragndrop"
],
function(
  Logger,
//  EventManagerWrapper,
  DragNDrop
) {

  return function( media ){

    var _media = media,
        _zoom = 1,
        _this = this;

    var _element = document.createElement( "div" ),
        _container = document.createElement( "div" );

    _element.appendChild( _container );

    _element.className = "tracks-container-wrapper";
    _container.className = "tracks-container";

    _container.addEventListener( "mousedown", function( e ){
      _this.deselectOthers();
    }, false );

    DragNDrop.droppable( _element, {
      drop: function( dropped, mousePosition ) {
        if ( dropped.getAttribute( "data-butter-draggable-type" ) === "plugin" ) {
          var newTrack = butter.currentMedia.addTrack(),
              trackRect = newTrack.view.element.getBoundingClientRect(),
              left = mousePosition[ 0 ] - trackRect.left,
              start = left / trackRect.width * newTrack.view.duration;

          newTrack.view.dispatch( "plugindropped", {
            start: start,
            track: newTrack,
            type: dropped.getAttribute( "data-butter-plugin-type" )
          });
        }
      }
    });

    this.orderTracks = function( orderedTracks ){
      for( var i=0, l=orderedTracks.length; i<l; ++i ){
        var trackElement = orderedTracks[ i ].view.element;
        if( trackElement !== _container.childNodes[ i ] ){
          orderedTracks[ i ].order = i;
          _container.insertBefore( trackElement, _container.childNodes[ i + 1 ] );
        } //if
      } //for
    }; //orderTracks

    this.deselectOthers = function() {
      for( var i = 0; i < butter.selectedEvents.length; i++ ) {
        butter.selectedEvents[ i ].selected = false;
      } // for
      butter.selectedEvents = [];
      return _this;
    }; //deselectOthers

    function resetContainer() {
      _container.style.width = _media.duration * _zoom + "px";
    } //resetContainer

    _media.listen( "mediaready", function(){
      resetContainer();
      var tracks = _media.tracks;
      for( var i=0, il=tracks.length; i<il; ++i ){
        var trackView = tracks[ i ].view;
        _container.appendChild( trackView.element );
        trackView.duration = _media.duration;
        trackView.zoom = _zoom;
      } //for
    });

    function onTrackAdded( e ){
      var trackView = e.data.view;
      _container.appendChild( trackView.element );
      trackView.duration = _media.duration;
      trackView.zoom = _zoom;
      trackView.parent = _this;
    }

    var existingTracks = _media.tracks;
    for( var i=0; i<existingTracks.length; ++i ){
      onTrackAdded({
        data: existingTracks[ i ]
      });
    }

    _media.listen( "trackadded", onTrackAdded );

    _media.listen( "trackremoved", function( e ){
      var trackView = e.data.view;
      _container.removeChild( trackView.element );
    });

    _this.update = function(){
      resetContainer();
    };

    Object.defineProperties( this, {
      zoom: {
        enumerable: true,
        get: function(){ return _zoom; },
        set: function( val ){
          _zoom = val;
          resetContainer();
          var tracks = _media.tracks;
          for( var i=0, il=tracks.length; i<il; ++i ){
            tracks[ i ].view.zoom = _zoom;
          } //for
        }
      },
      element: {
        enumerable: true,
        get: function(){
          return _element;
        }
      },
      width: {
        enumerable: true,
        get: function(){
          return _element.getBoundingClientRect().width;
        }
      },
      height: {
        enumerable: true,
        get: function(){
          return _element.getBoundingClientRect().height;
        }
      },
      scrollWidth: {
        enumerable: true,
        get: function(){
          return _element.scrollWidth;
        }
      },
      scrollHeight: {
        enumerable: true,
        get: function(){
          return _element.scrollHeight;
        }
      },
      vScroll: {
        enumerable: true,
        get: function(){
          return _element.scrollTop / _element.scrollHeight;
        },
        set: function( val ){
          _element.scrollTop = _element.scrollHeight * val;
        }
      },
      hScroll: {
        enumerable: true,
        get: function(){
          return _element.scrollLeft / _element.scrollWidth;
        },
        set: function( val ){
          _element.scrollLeft = _element.scrollWidth * val;
        }
      },
      container: {
        enumerable: true,
        get: function(){
          return _container;
        }
      }
    });

  };

});

<commit_msg>Remove commented code in track-container.js<commit_after>/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at http://www.mozillapopcorn.org/butter-license.txt */

define(
[
  "core/logger",
  "util/dragndrop"
],
function(
  Logger,
  DragNDrop
) {

  return function( media ){

    var _media = media,
        _zoom = 1,
        _this = this;

    var _element = document.createElement( "div" ),
        _container = document.createElement( "div" );

    _element.appendChild( _container );

    _element.className = "tracks-container-wrapper";
    _container.className = "tracks-container";

    _container.addEventListener( "mousedown", function( e ){
      _this.deselectOthers();
    }, false );

    DragNDrop.droppable( _element, {
      drop: function( dropped, mousePosition ) {
        if ( dropped.getAttribute( "data-butter-draggable-type" ) === "plugin" ) {
          var newTrack = butter.currentMedia.addTrack(),
              trackRect = newTrack.view.element.getBoundingClientRect(),
              left = mousePosition[ 0 ] - trackRect.left,
              start = left / trackRect.width * newTrack.view.duration;

          newTrack.view.dispatch( "plugindropped", {
            start: start,
            track: newTrack,
            type: dropped.getAttribute( "data-butter-plugin-type" )
          });
        }
      }
    });

    this.orderTracks = function( orderedTracks ){
      for( var i=0, l=orderedTracks.length; i<l; ++i ){
        var trackElement = orderedTracks[ i ].view.element;
        if( trackElement !== _container.childNodes[ i ] ){
          orderedTracks[ i ].order = i;
          _container.insertBefore( trackElement, _container.childNodes[ i + 1 ] );
        } //if
      } //for
    }; //orderTracks

    this.deselectOthers = function() {
      for( var i = 0; i < butter.selectedEvents.length; i++ ) {
        butter.selectedEvents[ i ].selected = false;
      } // for
      butter.selectedEvents = [];
      return _this;
    }; //deselectOthers

    function resetContainer() {
      _container.style.width = _media.duration * _zoom + "px";
    } //resetContainer

    _media.listen( "mediaready", function(){
      resetContainer();
      var tracks = _media.tracks;
      for( var i=0, il=tracks.length; i<il; ++i ){
        var trackView = tracks[ i ].view;
        _container.appendChild( trackView.element );
        trackView.duration = _media.duration;
        trackView.zoom = _zoom;
      } //for
    });

    function onTrackAdded( e ){
      var trackView = e.data.view;
      _container.appendChild( trackView.element );
      trackView.duration = _media.duration;
      trackView.zoom = _zoom;
      trackView.parent = _this;
    }

    var existingTracks = _media.tracks;
    for( var i=0; i<existingTracks.length; ++i ){
      onTrackAdded({
        data: existingTracks[ i ]
      });
    }

    _media.listen( "trackadded", onTrackAdded );

    _media.listen( "trackremoved", function( e ){
      var trackView = e.data.view;
      _container.removeChild( trackView.element );
    });

    _this.update = function(){
      resetContainer();
    };

    Object.defineProperties( this, {
      zoom: {
        enumerable: true,
        get: function(){ return _zoom; },
        set: function( val ){
          _zoom = val;
          resetContainer();
          var tracks = _media.tracks;
          for( var i=0, il=tracks.length; i<il; ++i ){
            tracks[ i ].view.zoom = _zoom;
          } //for
        }
      },
      element: {
        enumerable: true,
        get: function(){
          return _element;
        }
      },
      width: {
        enumerable: true,
        get: function(){
          return _element.getBoundingClientRect().width;
        }
      },
      height: {
        enumerable: true,
        get: function(){
          return _element.getBoundingClientRect().height;
        }
      },
      scrollWidth: {
        enumerable: true,
        get: function(){
          return _element.scrollWidth;
        }
      },
      scrollHeight: {
        enumerable: true,
        get: function(){
          return _element.scrollHeight;
        }
      },
      vScroll: {
        enumerable: true,
        get: function(){
          return _element.scrollTop / _element.scrollHeight;
        },
        set: function( val ){
          _element.scrollTop = _element.scrollHeight * val;
        }
      },
      hScroll: {
        enumerable: true,
        get: function(){
          return _element.scrollLeft / _element.scrollWidth;
        },
        set: function( val ){
          _element.scrollLeft = _element.scrollWidth * val;
        }
      },
      container: {
        enumerable: true,
        get: function(){
          return _container;
        }
      }
    });

  };

});

<|endoftext|>


<commit_before>module.exports = {
  env: {
    browser: false,
    node: true,
    commonjs: true
  },

  globals: {
    document: false,
    navigator: false,
    window: false
  },

  plugins: [
    'import'
  ],

  'extends': 'eslint:recommended',

  rules: {
    // Pre v1 eslint defaults
    'no-alert': 2,
    'no-array-constructor': 2,
    'no-caller': 2,
    'no-catch-shadow': 2,
    'no-eval': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-implied-eval': 2,
    'no-iterator': 2,
    'no-label-var': 2,
    'no-labels': 2,
    'no-lone-blocks': 2,
    'no-loop-func': 2,
    'no-multi-spaces': 2,
    'no-multi-str': 2,
    'no-native-reassign': 2,
    'no-new': 2,
    'no-new-func': 2,
    'no-new-object': 2,
    'no-new-wrappers': 2,
    'no-octal-escape': 2,
    'no-process-exit': 2,
    'no-proto': 2,
    'no-return-assign': 2,
    'no-script-url': 2,
    'no-sequences': 2,
    'no-shadow': 2,
    'no-shadow-restricted-names': 2,
    'no-spaced-func': 2,
    'no-trailing-spaces': 2,
    'no-undef-init': 2,
    'no-unused-expressions': 2,
    'no-use-before-define': 2,
    'no-with': 2,
    camelcase: 2,
    'consistent-return': 2,
    'dot-notation': [2, {allowKeywords: true}],
    'eol-last': 2,
    'no-extra-parens': [2, 'functions'],
    'key-spacing': [2, {beforeColon: false, afterColon: true}],
    'new-parens': 2,
    semi: 2,
    'semi-spacing': [2, {before: false, after: true}],
    'space-infix-ops': 2,
    'space-unary-ops': [2, {words: true, nonwords: false}],
    yoda: [2, 'never'],

    // Custom
    'no-underscore-dangle': 0,
    'comma-dangle': [2, 'never'],
    'comma-spacing': [2, {before: false, after: true}],
    'comma-style': [2, 'last'],
    curly: [2, 'multi-line'],
    'space-before-function-paren': [2, {anonymous: 'always', named: 'never'}],
    'space-before-blocks': [2, 'always'],
    'space-in-parens': [2, 'never'],
    'object-curly-spacing': [2, 'never'],
    'computed-property-spacing': [2, 'never'],
    'array-bracket-spacing': [2, 'never'],
    'block-spacing': [2, 'never'],
    'no-mixed-spaces-and-tabs': 2,
    'spaced-comment': [2, 'always'],
    'no-console': 2,
    'no-undef': 2,
    radix: 2,
    'no-else-return': 2,
    'no-var': 2,
    'brace-style': [2, 'stroustrup', {allowSingleLine: true}],
    'func-names': 2,
    'object-shorthand': [2, 'always'],
    'prefer-const': 2,
    'arrow-parens': [2, 'always'],
    'prefer-arrow-callback': 2,
    'prefer-template': 2,
    'jsx-quotes': [2, 'prefer-single'],
    'no-empty-pattern': 2,
    'no-magic-numbers': [2, {enforceConst: true, ignoreArrayIndexes: true, ignore: [-1, 0, 1, 2]}],
    'func-style': [2, 'expression', {allowArrowFunctions: true}],
    'arrow-body-style': [2, 'as-needed'],
    'no-case-declarations': 2,
    'no-constant-condition': 2,
    'prefer-spread': 2,
    'callback-return': [2, ['callback', 'cb', 'next', '_cb']],
    'consistent-this': [2, 'self'],
    'linebreak-style': [2, 'unix'],
    'no-empty': 2,
    'no-extra-semi': 2,
    // Remove since es7 class properties arent supported
    // https://github.com/babel/eslint-plugin-babel/issues/12
    // "no-invalid-this": 2,
    'quote-props': [2, 'as-needed', {keywords: true}],
    'no-useless-concat': 2,
    'no-nested-ternary': 2,
    'no-path-concat': 2,

    // eslint v2 rules
    'array-callback-return': 2,
    'no-implicit-globals': 2,
    'prefer-rest-params': 2,
    'no-unmodified-loop-condition': 2,
    'keyword-spacing': 2,
    'no-extra-label': 2,
    'no-new-symbol': 2,
    'no-self-assign': 2,
    'no-unused-labels': 2,
    'no-useless-constructor': 2,
    'no-whitespace-before-property': 2,
    'template-curly-spacing': [2, 'never'],
    'no-duplicate-imports': 2,
    'no-useless-escape': 2,
    'no-unsafe-finally': 2,
    'no-useless-computed-key': 2,
    'no-mixed-operators': 2,
    'rest-spread-spacing': [2, 'never'],

    // Import plugin
    'import/no-unresolved': [2, {commonjs: true}],
    'import/named': 2,
    'import/default': 2,
    'import/namespace': 2,
    'import/export': 2,
    'import/no-named-as-default': 2,
    'import/no-named-as-default-member': 2,
    'import/no-extraneous-dependencies': 2,
    'import/no-mutable-exports': 2,
    'import/imports-first': 0,
    'import/no-duplicates': 2,
    'import/order': [2, {groups: ['builtin', 'external', 'internal', ['parent', 'sibling'], 'index']}],
    'import/newline-after-import': 2,
    'import/prefer-default-export': 0,

    // Some stuff copied from standard
    'accessor-pairs': 2,
    'arrow-spacing': [2, {before: true, after: true}],
    'constructor-super': 2,
    'dot-location': [2, 'property'],
    eqeqeq: [2, 'allow-null'],
    'generator-star-spacing': [2, {before: true, after: true}],
    'handle-callback-err': [2, '^(err|error)$'],
    indent: [2, 2, {SwitchCase: 0}],
    'new-cap': [2, {newIsCap: true, capIsNew: false}],
    'no-class-assign': 2,
    'no-cond-assign': 2,
    'no-const-assign': 2,
    'no-control-regex': 2,
    'no-debugger': 2,
    'no-delete-var': 2,
    'no-dupe-args': 2,
    'no-dupe-class-members': 2,
    'no-dupe-keys': 2,
    'no-duplicate-case': 2,
    'no-empty-character-class': 2,
    'no-ex-assign': 2,
    'no-extra-boolean-cast': 2,
    'no-fallthrough': 2,
    'no-floating-decimal': 2,
    'no-func-assign': 2,
    'no-inner-declarations': [2, 'functions'],
    'no-invalid-regexp': 2,
    'no-irregular-whitespace': 2,
    'no-multiple-empty-lines': [2, {max: 1}],
    'no-negated-in-lhs': 2,
    'no-new-require': 2,
    'no-obj-calls': 2,
    'no-octal': 2,
    'no-redeclare': 2,
    'no-regex-spaces': 2,
    'no-self-compare': 2,
    'no-sparse-arrays': 2,
    'no-this-before-super': 2,
    'no-throw-literal': 2,
    'no-unexpected-multiline': 2,
    'no-unneeded-ternary': [2, {defaultAssignment: false}],
    'no-unreachable': 2,
    'no-unused-vars': [2, {vars: 'all', args: 'none'}],
    'no-useless-call': 2,
    'one-var': [2, {initialized: 'never'}],
    'operator-linebreak': [2, 'after', {overrides: {'?': 'before', ':': 'before'}}],
    'padded-blocks': [2, 'never'],
    quotes: [2, 'single', 'avoid-escape'],
    'use-isnan': 2,
    'valid-typeof': 2,
    'wrap-iife': [2, 'any']
  }
};
<commit_msg>new rules in eslint 3.3.0<commit_after>module.exports = {
  env: {
    browser: false,
    node: true,
    commonjs: true
  },

  globals: {
    document: false,
    navigator: false,
    window: false
  },

  plugins: [
    'import'
  ],

  'extends': 'eslint:recommended',

  rules: {
    // Pre v1 eslint defaults
    'no-alert': 2,
    'no-array-constructor': 2,
    'no-caller': 2,
    'no-catch-shadow': 2,
    'no-eval': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-implied-eval': 2,
    'no-iterator': 2,
    'no-label-var': 2,
    'no-labels': 2,
    'no-lone-blocks': 2,
    'no-loop-func': 2,
    'no-multi-spaces': 2,
    'no-multi-str': 2,
    'no-native-reassign': 2,
    'no-new': 2,
    'no-new-func': 2,
    'no-new-object': 2,
    'no-new-wrappers': 2,
    'no-octal-escape': 2,
    'no-process-exit': 2,
    'no-proto': 2,
    'no-return-assign': 2,
    'no-script-url': 2,
    'no-sequences': 2,
    'no-shadow': 2,
    'no-shadow-restricted-names': 2,
    'no-spaced-func': 2,
    'no-trailing-spaces': 2,
    'no-undef-init': 2,
    'no-unused-expressions': 2,
    'no-use-before-define': 2,
    'no-with': 2,
    camelcase: 2,
    'consistent-return': 2,
    'dot-notation': [2, {allowKeywords: true}],
    'eol-last': 2,
    'no-extra-parens': [2, 'functions'],
    'key-spacing': [2, {beforeColon: false, afterColon: true}],
    'new-parens': 2,
    semi: 2,
    'semi-spacing': [2, {before: false, after: true}],
    'space-infix-ops': 2,
    'space-unary-ops': [2, {words: true, nonwords: false}],
    yoda: [2, 'never'],

    // Custom
    'no-underscore-dangle': 0,
    'comma-dangle': [2, 'never'],
    'comma-spacing': [2, {before: false, after: true}],
    'comma-style': [2, 'last'],
    curly: [2, 'multi-line'],
    'space-before-function-paren': [2, {anonymous: 'always', named: 'never'}],
    'space-before-blocks': [2, 'always'],
    'space-in-parens': [2, 'never'],
    'object-curly-spacing': [2, 'never'],
    'computed-property-spacing': [2, 'never'],
    'array-bracket-spacing': [2, 'never'],
    'block-spacing': [2, 'never'],
    'no-mixed-spaces-and-tabs': 2,
    'spaced-comment': [2, 'always'],
    'no-console': 2,
    'no-undef': 2,
    radix: 2,
    'no-else-return': 2,
    'no-var': 2,
    'brace-style': [2, 'stroustrup', {allowSingleLine: true}],
    'func-names': 2,
    'object-shorthand': [2, 'always'],
    'prefer-const': 2,
    'arrow-parens': [2, 'always'],
    'prefer-arrow-callback': 2,
    'prefer-template': 2,
    'jsx-quotes': [2, 'prefer-single'],
    'no-empty-pattern': 2,
    'no-magic-numbers': [2, {enforceConst: true, ignoreArrayIndexes: true, ignore: [-1, 0, 1, 2]}],
    'func-style': [2, 'expression', {allowArrowFunctions: true}],
    'arrow-body-style': [2, 'as-needed'],
    'no-case-declarations': 2,
    'no-constant-condition': 2,
    'prefer-spread': 2,
    'callback-return': [2, ['callback', 'cb', 'next', '_cb']],
    'consistent-this': [2, 'self'],
    'linebreak-style': [2, 'unix'],
    'no-empty': 2,
    'no-extra-semi': 2,
    // Remove since es7 class properties arent supported
    // https://github.com/babel/eslint-plugin-babel/issues/12
    // "no-invalid-this": 2,
    'quote-props': [2, 'as-needed', {keywords: true}],
    'no-useless-concat': 2,
    'no-nested-ternary': 2,
    'no-path-concat': 2,
    'func-call-spacing': [2, 'never'],
    'no-template-curly-in-string': 2,
    'no-unsafe-negation': 2,
    'no-global-assign': 2,

    // eslint v2 rules
    'array-callback-return': 2,
    'no-implicit-globals': 2,
    'prefer-rest-params': 2,
    'no-unmodified-loop-condition': 2,
    'keyword-spacing': 2,
    'no-extra-label': 2,
    'no-new-symbol': 2,
    'no-self-assign': 2,
    'no-unused-labels': 2,
    'no-useless-constructor': 2,
    'no-whitespace-before-property': 2,
    'template-curly-spacing': [2, 'never'],
    'no-duplicate-imports': 2,
    'no-useless-escape': 2,
    'no-unsafe-finally': 2,
    'no-useless-computed-key': 2,
    'no-mixed-operators': 2,
    'rest-spread-spacing': [2, 'never'],

    // Import plugin
    'import/no-unresolved': [2, {commonjs: true}],
    'import/named': 2,
    'import/default': 2,
    'import/namespace': 2,
    'import/export': 2,
    'import/no-named-as-default': 2,
    'import/no-named-as-default-member': 2,
    'import/no-extraneous-dependencies': 2,
    'import/no-mutable-exports': 2,
    'import/imports-first': 0,
    'import/no-duplicates': 2,
    'import/order': [2, {groups: ['builtin', 'external', 'internal', ['parent', 'sibling'], 'index']}],
    'import/newline-after-import': 2,
    'import/prefer-default-export': 0,

    // Some stuff copied from standard
    'accessor-pairs': 2,
    'arrow-spacing': [2, {before: true, after: true}],
    'constructor-super': 2,
    'dot-location': [2, 'property'],
    eqeqeq: [2, 'allow-null'],
    'generator-star-spacing': [2, {before: true, after: true}],
    'handle-callback-err': [2, '^(err|error)$'],
    indent: [2, 2, {SwitchCase: 0}],
    'new-cap': [2, {newIsCap: true, capIsNew: false}],
    'no-class-assign': 2,
    'no-cond-assign': 2,
    'no-const-assign': 2,
    'no-control-regex': 2,
    'no-debugger': 2,
    'no-delete-var': 2,
    'no-dupe-args': 2,
    'no-dupe-class-members': 2,
    'no-dupe-keys': 2,
    'no-duplicate-case': 2,
    'no-empty-character-class': 2,
    'no-ex-assign': 2,
    'no-extra-boolean-cast': 2,
    'no-fallthrough': 2,
    'no-floating-decimal': 2,
    'no-func-assign': 2,
    'no-inner-declarations': [2, 'functions'],
    'no-invalid-regexp': 2,
    'no-irregular-whitespace': 2,
    'no-multiple-empty-lines': [2, {max: 1}],
    'no-negated-in-lhs': 2,
    'no-new-require': 2,
    'no-obj-calls': 2,
    'no-octal': 2,
    'no-redeclare': 2,
    'no-regex-spaces': 2,
    'no-self-compare': 2,
    'no-sparse-arrays': 2,
    'no-this-before-super': 2,
    'no-throw-literal': 2,
    'no-unexpected-multiline': 2,
    'no-unneeded-ternary': [2, {defaultAssignment: false}],
    'no-unreachable': 2,
    'no-unused-vars': [2, {vars: 'all', args: 'none'}],
    'no-useless-call': 2,
    'one-var': [2, {initialized: 'never'}],
    'operator-linebreak': [2, 'after', {overrides: {'?': 'before', ':': 'before'}}],
    'padded-blocks': [2, 'never'],
    quotes: [2, 'single', 'avoid-escape'],
    'use-isnan': 2,
    'valid-typeof': 2,
    'wrap-iife': [2, 'any']
  }
};
<|endoftext|>


<commit_before>init();
animate();

var renderer, scene, camera, controls;

function init () {

	// width and height of the window
	var width = window.innerWidth;
	var height = window.innerHeight;

	// WebGl render's options is set to antialias (smooth edges)
	renderer = new THREE.WebGLRenderer({ antialias: true });

	// set render's size to the window size
	renderer.setSize(width, height);

	// add the render's canvas to the document
	/*
		document.body is the element that contains the content for
		the document. In documents with <body> contents, returns the
		<body> element, and in frameset documents, this returns the o
		utermost <frameset> element.
	*/
	document.body.appendChild(renderer.domElement);

	// defines the scene
	scene = new THREE.Scene;

	var floorTexture = new THREE.ImageUtils.loadTexture( 'images/floor_tile.jpg' );
	floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
	floorTexture.repeat.set( 100, 100 );
	var floorMaterial = new THREE.MeshPhongMaterial( { map: floorTexture, side: THREE.DoubleSide } );
	var floorGeometry = new THREE.PlaneGeometry(1000, 1000, 1, 1);
	var floor = new THREE.Mesh(floorGeometry, floorMaterial);

	floor.position.y = -5.5;
	floor.rotation.x = Math.PI / 2;
	floor.receiveShadow = true;
	scene.add(floor);

	var axes = new THREE.AxisHelper(200);
	scene.add(axes);

	// cubegeometry width, height and depth is 100
	var cubeGeometry = new THREE.CubeGeometry(7.625*2,11*2,2.75*2);

	// the material of the cube is Lambert because of the lighting use
	// later in this program, and the color of the cube is black.
	var cubeMaterial = new THREE.MeshLambertMaterial({ color: "red" });

	// In Three.js the objects that are being drawn on the screen
	// are called meshes.
	var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
	cube.position.set(0,15,0);
	scene.add(cube);

	// "To render something, first we need to add the camera to the scene,
	// so the renderer knows from which point of view it should render stuff."
	// Args: (field of view, aspect ratio, near, far)
	camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 10000);

	// objects created in Three.js have their position set in the
	// middle of the scene (x: 0, y: 0, z: 0) by default.
	// we have to move the camera back and up a little.
	camera.position.y = 10;
	camera.position.z = 50;

	// Controls
	controls = new THREE.OrbitControls(camera, renderer.domElement);

	// add the camera to the scene and render the scene using this camera.
	scene.add(camera);

	// camera looks at the cube
	camera.lookAt(cube.position);
	/*
	var skyboxGeometry = new THREE.CubeGeometry(10000, 10000, 10000);
	var skyboxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.BackSide });
	var skybox = new THREE.Mesh(skyboxGeometry, skyboxMaterial);
	scene.add(skybox);
	*/
	// lighting for the scene
    var pointLight = new THREE.PointLight("white");
	pointLight.position.set(0, 300, 200);
	scene.add(pointLight);

	pointLight = new THREE.PointLight("white");
	pointLight.position.set(0, -300, -200);
	scene.add(pointLight);

	pointLight = new THREE.PointLight("white");
	pointLight.position.set(200, 300, 0);
	scene.add(pointLight);

	pointLight = new THREE.PointLight("white");
	pointLight.position.set(200, -300, 0);
	scene.add(pointLight);

	var loader = new THREE.ColladaLoader();

	loader.options.convertUpAxis = true;
	loader.load( '1865_Bookcase.dae', function ( collada ) {
		var dae = collada.scene;
	    var skin = collada.skins[0];
		dae.position.set(-10,0,85);	//x,z,y- if you think in blender dimensions ;)
		dae.scale.set(70,70,70);
		scene.add(dae);
	});

	renderer.render(scene, camera);
}

// Renders the scene and updates the render as needed.
function animate() {
	requestAnimationFrame(animate);
	renderer.render(scene, camera);
    controls.update();
}

<commit_msg>updated main.js<commit_after>init();
animate();

var renderer, scene, camera, controls;

function init () {

	// width and height of the window
	var width = window.innerWidth;
	var height = window.innerHeight;

	// WebGl render's options is set to antialias (smooth edges)
	renderer = new THREE.WebGLRenderer({ antialias: true });

	// set render's size to the window size
	renderer.setSize(width, height);

	// add the render's canvas to the document
	/*
		document.body is the element that contains the content for
		the document. In documents with <body> contents, returns the
		<body> element, and in frameset documents, this returns the o
		utermost <frameset> element.
	*/
	document.body.appendChild(renderer.domElement);

	// defines the scene
	scene = new THREE.Scene;

	var floorTexture = new THREE.ImageUtils.loadTexture( 'images/floor_tile.jpg' );
	floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
	floorTexture.repeat.set( 100, 100 );
	var floorMaterial = new THREE.MeshPhongMaterial( { map: floorTexture, side: THREE.DoubleSide } );
	var floorGeometry = new THREE.PlaneGeometry(1000, 1000, 1, 1);
	var floor = new THREE.Mesh(floorGeometry, floorMaterial);

	floor.position.y = -5.5;
	floor.rotation.x = Math.PI / 2;
	floor.receiveShadow = true;
	scene.add(floor);

	var axes = new THREE.AxisHelper(200);
	scene.add(axes);

	// cubegeometry width, height and depth is 100
	var cubeGeometry = new THREE.CubeGeometry(7.625*2,11*2,2.75*2);

	// the material of the cube is Lambert because of the lighting use
	// later in this program, and the color of the cube is black.
	var cubeMaterial = new THREE.MeshLambertMaterial({ color: "red" });

	// In Three.js the objects that are being drawn on the screen
	// are called meshes.
	var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
	cube.position.set(0,37,0);
	scene.add(cube);
	/*
	var materialArray = [
		new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/cereal_right.jpg' ) } ),
		new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/cereal_top.jpg' ) } ),
		new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/cereal_front.jpg' ) } ),
		new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/cereal_back.jpg' ) } ),
		new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/cereal_bottom.jpg' ) } ),
		new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'images/cereal_left.jpg' ) } )
	];

	var DiceBlue = new THREE.Mesh(cube, new THREE.MeshFaceMaterial(materialArray));
	scene.add( DiceBlue );
	*/
	/*
	var materials = [
	    new THREE.MeshPhongMaterial( { map: loadAndRender('images/cereal_left.jpg') } ),
	    new THREE.MeshPhongMaterial( { map: loadAndRender('images/cereal_right.jpg') } ),
	    new THREE.MeshPhongMaterial( { map: loadAndRender('images/cereal_top.jpg') } ),
	    new THREE.MeshPhongMaterial( { map: loadAndRender('images/cereal_bottom.jpg') } ),
	    new THREE.MeshPhongMaterial( { map: loadAndRender('images/cereal_front.jpg') } ),
	    new THREE.MeshPhongMaterial( { map: loadAndRender('images/cereal_back.jpg') } )
	];

	var cubeMesh = new THREE.Mesh(cube, new THREE.MeshFaceMaterial(materials));
	cubeMesh.castShadow = true;
	cubeMesh.receiveShadow = true;
	scene.add(cubeMesh);
*/

	// "To render something, first we need to add the camera to the scene,
	// so the renderer knows from which point of view it should render stuff."
	// Args: (field of view, aspect ratio, near, far)
	camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 10000);

	// objects created in Three.js have their position set in the
	// middle of the scene (x: 0, y: 0, z: 0) by default.
	// we have to move the camera back and up a little.
	camera.position.y = 70;
	camera.position.z = 400;

	// Controls
	controls = new THREE.OrbitControls(camera, renderer.domElement);

	// add the camera to the scene and render the scene using this camera.
	scene.add(camera);

	// camera looks at the cube
	camera.lookAt(cube.position);

	var skyboxGeometry = new THREE.CubeGeometry(10000, 10000, 10000);
	var skyboxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.BackSide });
	var skybox = new THREE.Mesh(skyboxGeometry, skyboxMaterial);
	scene.add(skybox);

	// lighting for the scene
    var pointLight = new THREE.PointLight("white");
	pointLight.position.set(0, 300, 200);
	scene.add(pointLight);

	pointLight = new THREE.PointLight("white");
	pointLight.position.set(0, -300, -200);
	scene.add(pointLight);

	pointLight = new THREE.PointLight("white");
	pointLight.position.set(200, 300, 0);
	scene.add(pointLight);

	pointLight = new THREE.PointLight("white");
	pointLight.position.set(200, -300, 0);
	scene.add(pointLight);

	var loader = new THREE.ColladaLoader();

	loader.options.convertUpAxis = true;
	loader.load( '1865_Bookcase.dae', function ( collada ) {
		var dae = collada.scene;
	    var skin = collada.skins[0];
		dae.position.set(-10,90,85);	//x,z,y- if you think in blender dimensions ;)
		dae.scale.set(70,70,70);
		scene.add(dae);
	});

	renderer.render(scene, camera);
}

// Renders the scene and updates the render as needed.
function animate() {
	requestAnimationFrame(animate);
	renderer.render(scene, camera);
    controls.update();
}

<|endoftext|>


<commit_before>define( [ 'collection/Map', 'render/Camera2D', 'lib/Detector', 'lib/Three', 'core/Math' ], function( _Map, _Camera2D, _Detector, _Three, _Math ) {

  var SceneManager = function() {
    this.cameras = new _Map();
    this.cameraIterator = this.cameras.iterator();
    this.scenes = new _Map();
  };

  SceneManager.DEFAULT_CAMERA_ID = 'default_camera_id';
  SceneManager.DEFAULT_SCENE_ID = 'default_scene_id';

  SceneManager.prototype.init = function( bgcolor, width, height, target ) {
    // If its not supported, instantiate the canvas renderer to support all non WebGL browsers
    this.renderer = _Detector.webgl ? new _Three.WebGLRenderer( {
      antialias : false
    } ) : new _Three.CanvasRenderer();

    // Set the background color of the renderer, with full opacity
    this.renderer.setClearColor( ( bgcolor ) ? bgcolor : 0xFFFFFF, 1 );

    // if no dimensions are provided, get the size of the inner window (content area) to create a full size renderer
    this.canvasWidth = ( width ) ? width : window.innerWidth - 25;
    this.canvasHeight = ( height ) ? height : window.innerHeight - 25;

    // since the rendering area is actually 3D, a Z translation on camera is required.
    this.z = _Math.max( this.canvasWidth, this.canvasHeight );

    // set the renderer size
    this.renderer.setSize( this.canvasWidth, this.canvasHeight );

    // attach a canvas tag on the body
    var body = ( target ) ? target : document.getElementsByTagName( 'body' )[ 0 ];
    body.appendChild( this.renderer.domElement );
  };

  // create a Three.scene
  SceneManager.prototype.createScene = function( sceneId ) {
    this.scenes.put( sceneId ? sceneId : this.DEFAULT_SCENE_ID, new _Three.Scene() );
  };

  // create a camera to a scene
  SceneManager.prototype.createCamera = function( cameraId, sceneId, width, height ) {
    var scene = this.scenes.get( ( sceneId ) ? sceneId : this.DEFAULT_SCENE_ID );

    if ( !cameraId ) {
      cameraId = this.DEFAULT_CAMERA_ID;
    }

    if ( !width ) {
      width = this.canvasWidth;
    }

    if ( !height ) {
      height = this.canvasHeight;
    }

    if ( scene ) {
      // left, right, top, bottom, near, far
      var camera = new _Camera2D( width / -2, width / 2, height / 2, height / -2, 1, _Math.max( width, height ) );

      camera.addScene( ( sceneId ) ? sceneId : this.DEFAULT_SCENE_ID );
      this.cameras.put( cameraId, camera );

    } else {
      console.log( 'Scene not found:' + sceneId );
      return;
    }
  };

  SceneManager.prototype.attachToScene = function( gameObject, sceneId ) {
  // TODO encontra todos os componentes renderizáveis e registra na cena
  // this.sceneManager.getScene( sceneId ? sceneId : SceneManager.DEFAULT_SCENE_ID ).add( object );
  };

  SceneManager.prototype.render = function() {
    var camera, scene;

    this.cameraIterator.first();

    // iterate all cameras
    while ( this.cameraIterator.hasNext() ) {
      camera = this.cameraIterator.next();
      camera.sceneIterator.first();

      // iterate all scenes registered to render on this camera
      while ( camera.sceneIterator.hasNext() ) {
        scene = this.scenes.get( camera.sceneIterator.next() );

        // TODO render based on ObjectManager tree hierarchy
        if ( scene ) {
          this.renderer.render( scene, camera.cam );
        }
      }
    }
  };

  return SceneManager;
} );
<commit_msg>Improving rendering pipeline<commit_after>define( [ 'collection/Map', 'render/Camera2D', 'lib/Detector', 'lib/Three', 'core/Math' ], function( _Map, _Camera2D, _Detector, _Three, _Math ) {

  var SceneManager = function() {
    this.cameras = new _Map();
    this.cameraIterator = this.cameras.iterator();
    this.scenes = new _Map();
  };

  SceneManager.DEFAULT_CAMERA_ID = 'default_camera_id';
  SceneManager.DEFAULT_SCENE_ID = 'default_scene_id';

  SceneManager.prototype.init = function( bgcolor, width, height, target ) {
    // If its not supported, instantiate the canvas renderer to support all non WebGL browsers
    this.renderer = _Detector.webgl ? new _Three.WebGLRenderer( {
      antialias : false
    } ) : new _Three.CanvasRenderer();

    // Set the background color of the renderer, with full opacity
    this.renderer.setClearColor( ( bgcolor ) ? bgcolor : 0xFFFFFF, 1 );

    // if no dimensions are provided, get the size of the inner window (content area) to create a full size renderer
    this.canvasWidth = ( width ) ? width : window.innerWidth - 25;
    this.canvasHeight = ( height ) ? height : window.innerHeight - 25;

    // since the rendering area is actually 3D, a Z translation on camera is required.
    this.z = _Math.max( this.canvasWidth, this.canvasHeight );

    // set the renderer size
    this.renderer.setSize( this.canvasWidth, this.canvasHeight );

    // attach a canvas tag on the body
    var body = ( target ) ? target : document.getElementsByTagName( 'body' )[ 0 ];
    body.appendChild( this.renderer.domElement );
  };

  // create a Three.scene
  SceneManager.prototype.createScene = function( sceneId ) {
    this.scenes.put( sceneId ? sceneId : this.DEFAULT_SCENE_ID, new _Three.Scene() );
  };

  // create a camera to a scene
  SceneManager.prototype.createCamera = function( cameraId, sceneId, width, height ) {
    var scene = this.scenes.get( ( sceneId ) ? sceneId : this.DEFAULT_SCENE_ID );

    if ( !cameraId ) {
      cameraId = this.DEFAULT_CAMERA_ID;
    }

    if ( !width ) {
      width = this.canvasWidth;
    }

    if ( !height ) {
      height = this.canvasHeight;
    }

    if ( scene ) {
      // left, right, top, bottom, near, far
      var camera = new _Camera2D( width / -2, width / 2, height / 2, height / -2, 1, _Math.max( width, height ) );

      camera.addScene( ( sceneId ) ? sceneId : this.DEFAULT_SCENE_ID );
      this.cameras.put( cameraId, camera );

    } else {
      console.log( 'Scene not found:' + sceneId );
      return;
    }
  };

  // find all renderable components of a given Game Object and attach the on the scene to be rendered
  SceneManager.prototype.attachToScene = function( gameObject, sceneId ) {
    var list = gameObject.listRenderableComponents();
    var scene = this.scenes.get( sceneId ? sceneId : SceneManager.DEFAULT_SCENE_ID );

    for( var  i = 0, len = list.length; i < len; i++  ){
      scene.add( list[i].getMesh() );
    }

  };

  SceneManager.prototype.render = function() {
    var camera, scene;

    this.cameraIterator.first();

    // iterate all cameras
    while ( this.cameraIterator.hasNext() ) {
      camera = this.cameraIterator.next();
      camera.sceneIterator.first();

      // iterate all scenes registered to render on this camera
      while ( camera.sceneIterator.hasNext() ) {
        scene = this.scenes.get( camera.sceneIterator.next() );

        if ( scene ) {
          this.renderer.render( scene, camera.cam );
        }
      }
    }
  };

  return SceneManager;
} );
<|endoftext|>


<commit_before>const {promisify} = require('util');
const fs = require('fs');
const path = require('path');
const symlink = promisify(fs.symlink);
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const mkdirp = promisify(require('mkdirp'));
const chokidar = require('chokidar');
const chalk = require('chalk');
const log = require('../utils/log');
const globby = require('globby');
const timer = require('../utils/timer');
const ora = require('ora');
const sharp = require('sharp');
const config = require('../utils/config-store').getConfig();
const isProd = process.env.NODE_ENV === 'production';

// @todo Consider moving this to a place to share
const boltImageSizes = [
  50,
  100,
  200,
  320,
  480,
  640,
  800,
  1024,
  1366,
  1536,
  1920,
  2560,
  2880,
];

async function processImage(file, set) {
  if (config.verbosity > 2) {
    log.dim(`Processing image: ${file}`);
  }
  // If `set.base` is `images/` and `file` is `images/header/main.png`, then `fileId` is `header/main.png`
  const fileId = path.relative(set.base, file);
  const newPath = path.join(set.dist, fileId);
  const pathInfo = path.parse(newPath);
  // pathInfo.ext and pathInfo.name are ignored if pathInfo.base exists
  delete pathInfo.base;

  await mkdirp(pathInfo.dir);

  // We add `null` to beginning b/c we want the original file too
  const sizes = [null, ...boltImageSizes];

  let originalFileBuffer;
  if (isProd) {
    // we want to read the original file once, instead of reading for each size
    originalFileBuffer = await readFile(file);
  }

  return Promise.all(sizes.map(async (size) => {
    const isOrig = size === null;
    const sizeSuffix = size ? `-${size}` : '';
    const thisPathInfo = Object.assign({}, pathInfo, {
      name: `${pathInfo.name}${sizeSuffix}`,
    });
    const newSizedPath = path.format(thisPathInfo);

    if (isOrig) {// original file

    } else {// resized file
      // no need to resize these file extensions
      if (pathInfo.ext === '.svg' || pathInfo.ext === '.gif') {
        return;
      }
    }

    if (isProd) {
      if (isOrig) {
        await writeFile(newSizedPath, originalFileBuffer);
      } else {
        // http://sharp.pixelplumbing.com/en/stable/
        await sharp(originalFileBuffer)
          .resize(size)
          .toFile(newSizedPath);
      }
    } else {
      // Not prod, so let's be quick.
      // Symlinking works even if the original file is not served
      const symlinkPath = path.relative(thisPathInfo.dir, file);
      try {
        await symlink(symlinkPath, newSizedPath);
      } catch (error) {
        // If it's the error for symlink already exists, we don't care.
        if (error.code !== 'EEXIST') {
          log.errorAndExit(`Problem when attempting to symlink ${file} to ${newSizedPath}.`, error);
        }
      }
    }
  }));
}

async function processImages() {
  if (!config.images) {
    return;
  }
  const startMessage = chalk.blue('Processing images...');
  const startTime = timer.start();
  let spinner;
  if (config.verbosity > 2) {
    console.log(startMessage);
  } else {
    spinner = ora(startMessage).start();
  }

  return Promise.all(config.images.sets.map(async (set) => {
    const imagePaths = await globby(path.join(set.base, set.glob));
    return Promise.all(imagePaths.map(imagePath => processImage(imagePath, set)));
  })).then(() => {// When it's all done
    const endMessage = chalk.green(`Processed images in ${timer.end(startTime)}`);
    if (config.verbosity > 2) {
      console.log(endMessage);
    } else {
      spinner.succeed(endMessage);
    }
  });
}

module.exports = {
  processImages,
};
<commit_msg>Using config.prod flag in Image Tasks<commit_after>const {promisify} = require('util');
const fs = require('fs');
const path = require('path');
const symlink = promisify(fs.symlink);
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const mkdirp = promisify(require('mkdirp'));
const chokidar = require('chokidar');
const chalk = require('chalk');
const log = require('../utils/log');
const globby = require('globby');
const timer = require('../utils/timer');
const ora = require('ora');
const sharp = require('sharp');
const config = require('../utils/config-store').getConfig();

// @todo Consider moving this to a place to share
const boltImageSizes = [
  50,
  100,
  200,
  320,
  480,
  640,
  800,
  1024,
  1366,
  1536,
  1920,
  2560,
  2880,
];

async function processImage(file, set) {
  if (config.verbosity > 2) {
    log.dim(`Processing image: ${file}`);
  }
  // If `set.base` is `images/` and `file` is `images/header/main.png`, then `fileId` is `header/main.png`
  const fileId = path.relative(set.base, file);
  const newPath = path.join(set.dist, fileId);
  const pathInfo = path.parse(newPath);
  // pathInfo.ext and pathInfo.name are ignored if pathInfo.base exists
  delete pathInfo.base;

  await mkdirp(pathInfo.dir);

  // We add `null` to beginning b/c we want the original file too
  const sizes = [null, ...boltImageSizes];

  let originalFileBuffer;
  if (config.prod) {
    // we want to read the original file once, instead of reading for each size
    originalFileBuffer = await readFile(file);
  }

  return Promise.all(sizes.map(async (size) => {
    const isOrig = size === null;
    const sizeSuffix = size ? `-${size}` : '';
    const thisPathInfo = Object.assign({}, pathInfo, {
      name: `${pathInfo.name}${sizeSuffix}`,
    });
    const newSizedPath = path.format(thisPathInfo);

    if (isOrig) {// original file

    } else {// resized file
      // no need to resize these file extensions
      if (pathInfo.ext === '.svg' || pathInfo.ext === '.gif') {
        return;
      }
    }

    if (config.prod) {
      if (isOrig) {
        await writeFile(newSizedPath, originalFileBuffer);
      } else {
        // http://sharp.pixelplumbing.com/en/stable/
        await sharp(originalFileBuffer)
          .resize(size)
          .toFile(newSizedPath);
      }
    } else {
      // Not prod, so let's be quick.
      // Symlinking works even if the original file is not served
      const symlinkPath = path.relative(thisPathInfo.dir, file);
      try {
        await symlink(symlinkPath, newSizedPath);
      } catch (error) {
        // If it's the error for symlink already exists, we don't care.
        if (error.code !== 'EEXIST') {
          log.errorAndExit(`Problem when attempting to symlink ${file} to ${newSizedPath}.`, error);
        }
      }
    }
  }));
}

async function processImages() {
  if (!config.images) {
    return;
  }
  const startMessage = chalk.blue('Processing images...');
  const startTime = timer.start();
  let spinner;
  if (config.verbosity > 2) {
    console.log(startMessage);
  } else {
    spinner = ora(startMessage).start();
  }

  return Promise.all(config.images.sets.map(async (set) => {
    const imagePaths = await globby(path.join(set.base, set.glob));
    return Promise.all(imagePaths.map(imagePath => processImage(imagePath, set)));
  })).then(() => {// When it's all done
    const endMessage = chalk.green(`Processed images in ${timer.end(startTime)}`);
    if (config.verbosity > 2) {
      console.log(endMessage);
    } else {
      spinner.succeed(endMessage);
    }
  });
}

module.exports = {
  processImages,
};
<|endoftext|>


<commit_before>/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var svgSdf = require('svg-path-sdf');
var rgba = require('color-normalize');

var Registry = require('../../registry');
var Lib = require('../../lib');
var Drawing = require('../../components/drawing');
var AxisIDs = require('../../plots/cartesian/axis_ids');

var formatColor = require('../../lib/gl_format_color');
var subTypes = require('../scatter/subtypes');
var makeBubbleSizeFn = require('../scatter/make_bubble_size_func');

var constants = require('./constants');
var DESELECTDIM = require('../../constants/interactions').DESELECTDIM;

function convertStyle(gd, trace) {
    var i;

    var opts = {
        marker: null,
        line: null,
        fill: null,
        errorX: null,
        errorY: null,
        selected: null,
        unselected: null
    };

    if(trace.visible !== true) return opts;

    if(subTypes.hasMarkers(trace)) {
        opts.marker = convertMarkerStyle(trace);
        opts.selected = convertMarkerSelection(trace, trace.selected);
        opts.unselected = convertMarkerSelection(trace, trace.unselected);

        if(!trace.unselected && Array.isArray(trace.marker.opacity)) {
            var mo = trace.marker.opacity;
            opts.unselected.opacity = new Array(mo.length);
            for(i = 0; i < mo.length; i++) {
                opts.unselected.opacity[i] = DESELECTDIM * mo[i];
            }
        }

        // FIXME: if only trace.selected provided, trace.unselected remains empty
        // cc @etienne
    }

    if(subTypes.hasLines(trace)) {
        opts.line = {
            overlay: true,
            thickness: trace.line.width,
            color: trace.line.color,
            opacity: trace.opacity
        };

        var dashes = (constants.DASHES[trace.line.dash] || [1]).slice();
        for(i = 0; i < dashes.length; ++i) {
            dashes[i] *= trace.line.width;
        }
        opts.line.dashes = dashes;
    }

    if(trace.error_x && trace.error_x.visible) {
        opts.errorX = convertErrorBarStyle(trace, trace.error_x);
    }

    if(trace.error_y && trace.error_y.visible) {
        opts.errorY = convertErrorBarStyle(trace, trace.error_y);
    }

    if(!!trace.fill && trace.fill !== 'none') {
        opts.fill = {
            closed: true,
            fill: trace.fillcolor,
            thickness: 0
        };
    }

    return opts;
}

function convertMarkerStyle(trace) {
    var count = trace._length || trace._commonLength;
    var optsIn = trace.marker;
    var optsOut = {};
    var i;

    var multiSymbol = Array.isArray(optsIn.symbol);
    var multiColor = Lib.isArrayOrTypedArray(optsIn.color);
    var multiLineColor = Lib.isArrayOrTypedArray(optsIn.line.color);
    var multiOpacity = Lib.isArrayOrTypedArray(optsIn.opacity);
    var multiSize = Lib.isArrayOrTypedArray(optsIn.size);
    var multiLineWidth = Lib.isArrayOrTypedArray(optsIn.line.width);

    var isOpen;
    if(!multiSymbol) isOpen = constants.OPEN_RE.test(optsIn.symbol);

    // prepare colors
    if(multiSymbol || multiColor || multiLineColor || multiOpacity) {
        optsOut.colors = new Array(count);
        optsOut.borderColors = new Array(count);

        var colors = formatColor(optsIn, optsIn.opacity, count);
        var borderColors = formatColor(optsIn.line, optsIn.opacity, count);

        if(!Array.isArray(borderColors[0])) {
            var borderColor = borderColors;
            borderColors = Array(count);
            for(i = 0; i < count; i++) {
                borderColors[i] = borderColor;
            }
        }
        if(!Array.isArray(colors[0])) {
            var color = colors;
            colors = Array(count);
            for(i = 0; i < count; i++) {
                colors[i] = color;
            }
        }

        optsOut.colors = colors;
        optsOut.borderColors = borderColors;

        for(i = 0; i < count; i++) {
            if(multiSymbol) {
                var symbol = optsIn.symbol[i];
                isOpen = constants.OPEN_RE.test(symbol);
            }
            if(isOpen) {
                borderColors[i] = colors[i].slice();
                colors[i] = colors[i].slice();
                colors[i][3] = 0;
            }
        }

        optsOut.opacity = trace.opacity;
    } else {
        if(isOpen) {
            optsOut.color = rgba(optsIn.color, 'uint8');
            optsOut.color[3] = 0;
            optsOut.borderColor = rgba(optsIn.color, 'uint8');
        } else {
            optsOut.color = rgba(optsIn.color, 'uint8');
            optsOut.borderColor = rgba(optsIn.line.color, 'uint8');
        }

        optsOut.opacity = trace.opacity * optsIn.opacity;
    }

    // prepare symbols
    if(multiSymbol) {
        optsOut.markers = new Array(count);
        for(i = 0; i < count; i++) {
            optsOut.markers[i] = getSymbolSdf(optsIn.symbol[i]);
        }
    } else {
        optsOut.marker = getSymbolSdf(optsIn.symbol);
    }

    // prepare sizes
    var markerSizeFunc = makeBubbleSizeFn(trace);
    var s;

    if(multiSize || multiLineWidth) {
        var sizes = optsOut.sizes = new Array(count);
        var borderSizes = optsOut.borderSizes = new Array(count);
        var sizeTotal = 0;
        var sizeAvg;

        if(multiSize) {
            for(i = 0; i < count; i++) {
                sizes[i] = markerSizeFunc(optsIn.size[i]);
                sizeTotal += sizes[i];
            }
            sizeAvg = sizeTotal / count;
        } else {
            s = markerSizeFunc(optsIn.size);
            for(i = 0; i < count; i++) {
                sizes[i] = s;
            }
        }

        // See  https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798
        if(multiLineWidth) {
            for(i = 0; i < count; i++) {
                borderSizes[i] = markerSizeFunc(optsIn.line.width[i]);
            }
        } else {
            s = markerSizeFunc(optsIn.line.width);
            for(i = 0; i < count; i++) {
                borderSizes[i] = s;
            }
        }

        optsOut.sizeAvg = sizeAvg;
    } else {
        optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10);
        optsOut.borderSizes = markerSizeFunc(optsIn.line.width);
    }

    return optsOut;
}

function convertMarkerSelection(trace, target) {
    var optsIn = trace.marker;
    var optsOut = {};

    if(!target) return optsOut;

    if(target.marker && target.marker.symbol) {
        optsOut = convertMarkerStyle(Lib.extendFlat({}, optsIn, target.marker));
    } else if(target.marker) {
        if(target.marker.size) optsOut.sizes = target.marker.size;
        if(target.marker.color) optsOut.colors = target.marker.color;
        if(target.marker.opacity !== undefined) optsOut.opacity = target.marker.opacity;
    }

    return optsOut;
}

function convertErrorBarStyle(trace, target) {
    var optsOut = {
        capSize: target.width * 2,
        lineWidth: target.thickness,
        color: target.color
    };

    if(target.copy_ystyle) {
        optsOut = trace.error_y;
    }

    return optsOut;
}

var SYMBOL_SDF_SIZE = constants.SYMBOL_SDF_SIZE;
var SYMBOL_SIZE = constants.SYMBOL_SIZE;
var SYMBOL_STROKE = constants.SYMBOL_STROKE;
var SYMBOL_SDF = {};
var SYMBOL_SVG_CIRCLE = Drawing.symbolFuncs[0](SYMBOL_SIZE * 0.05);

function getSymbolSdf(symbol) {
    if(symbol === 'circle') return null;

    var symbolPath, symbolSdf;
    var symbolNumber = Drawing.symbolNumber(symbol);
    var symbolFunc = Drawing.symbolFuncs[symbolNumber % 100];
    var symbolNoDot = !!Drawing.symbolNoDot[symbolNumber % 100];
    var symbolNoFill = !!Drawing.symbolNoFill[symbolNumber % 100];

    var isDot = constants.DOT_RE.test(symbol);

    // get symbol sdf from cache or generate it
    if(SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol];

    if(isDot && !symbolNoDot) {
        symbolPath = symbolFunc(SYMBOL_SIZE * 1.1) + SYMBOL_SVG_CIRCLE;
    }
    else {
        symbolPath = symbolFunc(SYMBOL_SIZE);
    }

    symbolSdf = svgSdf(symbolPath, {
        w: SYMBOL_SDF_SIZE,
        h: SYMBOL_SDF_SIZE,
        viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE],
        stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE
    });
    SYMBOL_SDF[symbol] = symbolSdf;

    return symbolSdf || null;
}

function convertLinePositions(gd, trace, positions) {
    var count = positions.length / 2;
    var linePositions;
    var i;

    if(subTypes.hasLines(trace) && count) {
        if(trace.line.shape === 'hv') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                }
                else {
                    linePositions.push(positions[i * 2]);
                    linePositions.push(positions[i * 2 + 1]);
                    linePositions.push(positions[i * 2 + 2]);
                    linePositions.push(positions[i * 2 + 1]);
                }
            }
            linePositions.push(positions[positions.length - 2]);
            linePositions.push(positions[positions.length - 1]);
        } else if(trace.line.shape === 'vh') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                }
                else {
                    linePositions.push(positions[i * 2]);
                    linePositions.push(positions[i * 2 + 1]);
                    linePositions.push(positions[i * 2]);
                    linePositions.push(positions[i * 2 + 3]);
                }
            }
            linePositions.push(positions[positions.length - 2]);
            linePositions.push(positions[positions.length - 1]);
        } else {
            linePositions = positions;
        }
    }

    // If we have data with gaps, we ought to use rect joins
    // FIXME: get rid of this
    var hasNaN = false;
    for(i = 0; i < linePositions.length; i++) {
        if(isNaN(linePositions[i])) {
            hasNaN = true;
            break;
        }
    }

    var join = (hasNaN || linePositions.length > constants.TOO_MANY_POINTS) ? 'rect' :
        subTypes.hasMarkers(trace) ? 'rect' : 'round';

    // fill gaps
    if(hasNaN && trace.connectgaps) {
        var lastX = linePositions[0];
        var lastY = linePositions[1];

        for(i = 0; i < linePositions.length; i += 2) {
            if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) {
                linePositions[i] = lastX;
                linePositions[i + 1] = lastY;
            }
            else {
                lastX = linePositions[i];
                lastY = linePositions[i + 1];
            }
        }
    }

    return {
        join: join,
        positions: linePositions
    };
}

function convertErrorBarPositions(gd, trace, positions) {
    var calcFromTrace = Registry.getComponentMethod('errorbars', 'calcFromTrace');
    var vals = calcFromTrace(trace, gd._fullLayout);
    var count = positions.length / 2;
    var out = {};

    function put(axLetter) {
        var errors = new Float64Array(4 * count);
        var ax = AxisIDs.getFromId(gd, trace[axLetter + 'axis']);
        var pOffset = {x: 0, y: 1}[axLetter];
        var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter];

        for(var i = 0, p = 0; i < count; i++, p += 4) {
            errors[p + eOffset[0]] = positions[i * 2 + pOffset] - ax.d2l(vals[i][axLetter + 's']) || 0;
            errors[p + eOffset[1]] = ax.d2l(vals[i][axLetter + 'h']) - positions[i * 2 + pOffset] || 0;
            errors[p + eOffset[2]] = 0;
            errors[p + eOffset[3]] = 0;
        }

        return errors;
    }

    if(trace.error_x && trace.error_x.visible) {
        out.x = {
            positions: positions,
            errors: put('x')
        };
    }
    if(trace.error_y && trace.error_y.visible) {
        out.y = {
            positions: positions,
            errors: put('y')
        };
    }

    return out;
}

module.exports = {
    convertStyle: convertStyle,
    convertMarkerStyle: convertMarkerStyle,
    convertMarkerSelection: convertMarkerSelection,
    convertLinePositions: convertLinePositions,
    convertErrorBarPositions: convertErrorBarPositions
};
<commit_msg>:hocho: obsolete comment<commit_after>/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var svgSdf = require('svg-path-sdf');
var rgba = require('color-normalize');

var Registry = require('../../registry');
var Lib = require('../../lib');
var Drawing = require('../../components/drawing');
var AxisIDs = require('../../plots/cartesian/axis_ids');

var formatColor = require('../../lib/gl_format_color');
var subTypes = require('../scatter/subtypes');
var makeBubbleSizeFn = require('../scatter/make_bubble_size_func');

var constants = require('./constants');
var DESELECTDIM = require('../../constants/interactions').DESELECTDIM;

function convertStyle(gd, trace) {
    var i;

    var opts = {
        marker: null,
        line: null,
        fill: null,
        errorX: null,
        errorY: null,
        selected: null,
        unselected: null
    };

    if(trace.visible !== true) return opts;

    if(subTypes.hasMarkers(trace)) {
        opts.marker = convertMarkerStyle(trace);
        opts.selected = convertMarkerSelection(trace, trace.selected);
        opts.unselected = convertMarkerSelection(trace, trace.unselected);

        if(!trace.unselected && Array.isArray(trace.marker.opacity)) {
            var mo = trace.marker.opacity;
            opts.unselected.opacity = new Array(mo.length);
            for(i = 0; i < mo.length; i++) {
                opts.unselected.opacity[i] = DESELECTDIM * mo[i];
            }
        }
    }

    if(subTypes.hasLines(trace)) {
        opts.line = {
            overlay: true,
            thickness: trace.line.width,
            color: trace.line.color,
            opacity: trace.opacity
        };

        var dashes = (constants.DASHES[trace.line.dash] || [1]).slice();
        for(i = 0; i < dashes.length; ++i) {
            dashes[i] *= trace.line.width;
        }
        opts.line.dashes = dashes;
    }

    if(trace.error_x && trace.error_x.visible) {
        opts.errorX = convertErrorBarStyle(trace, trace.error_x);
    }

    if(trace.error_y && trace.error_y.visible) {
        opts.errorY = convertErrorBarStyle(trace, trace.error_y);
    }

    if(!!trace.fill && trace.fill !== 'none') {
        opts.fill = {
            closed: true,
            fill: trace.fillcolor,
            thickness: 0
        };
    }

    return opts;
}

function convertMarkerStyle(trace) {
    var count = trace._length || trace._commonLength;
    var optsIn = trace.marker;
    var optsOut = {};
    var i;

    var multiSymbol = Array.isArray(optsIn.symbol);
    var multiColor = Lib.isArrayOrTypedArray(optsIn.color);
    var multiLineColor = Lib.isArrayOrTypedArray(optsIn.line.color);
    var multiOpacity = Lib.isArrayOrTypedArray(optsIn.opacity);
    var multiSize = Lib.isArrayOrTypedArray(optsIn.size);
    var multiLineWidth = Lib.isArrayOrTypedArray(optsIn.line.width);

    var isOpen;
    if(!multiSymbol) isOpen = constants.OPEN_RE.test(optsIn.symbol);

    // prepare colors
    if(multiSymbol || multiColor || multiLineColor || multiOpacity) {
        optsOut.colors = new Array(count);
        optsOut.borderColors = new Array(count);

        var colors = formatColor(optsIn, optsIn.opacity, count);
        var borderColors = formatColor(optsIn.line, optsIn.opacity, count);

        if(!Array.isArray(borderColors[0])) {
            var borderColor = borderColors;
            borderColors = Array(count);
            for(i = 0; i < count; i++) {
                borderColors[i] = borderColor;
            }
        }
        if(!Array.isArray(colors[0])) {
            var color = colors;
            colors = Array(count);
            for(i = 0; i < count; i++) {
                colors[i] = color;
            }
        }

        optsOut.colors = colors;
        optsOut.borderColors = borderColors;

        for(i = 0; i < count; i++) {
            if(multiSymbol) {
                var symbol = optsIn.symbol[i];
                isOpen = constants.OPEN_RE.test(symbol);
            }
            if(isOpen) {
                borderColors[i] = colors[i].slice();
                colors[i] = colors[i].slice();
                colors[i][3] = 0;
            }
        }

        optsOut.opacity = trace.opacity;
    } else {
        if(isOpen) {
            optsOut.color = rgba(optsIn.color, 'uint8');
            optsOut.color[3] = 0;
            optsOut.borderColor = rgba(optsIn.color, 'uint8');
        } else {
            optsOut.color = rgba(optsIn.color, 'uint8');
            optsOut.borderColor = rgba(optsIn.line.color, 'uint8');
        }

        optsOut.opacity = trace.opacity * optsIn.opacity;
    }

    // prepare symbols
    if(multiSymbol) {
        optsOut.markers = new Array(count);
        for(i = 0; i < count; i++) {
            optsOut.markers[i] = getSymbolSdf(optsIn.symbol[i]);
        }
    } else {
        optsOut.marker = getSymbolSdf(optsIn.symbol);
    }

    // prepare sizes
    var markerSizeFunc = makeBubbleSizeFn(trace);
    var s;

    if(multiSize || multiLineWidth) {
        var sizes = optsOut.sizes = new Array(count);
        var borderSizes = optsOut.borderSizes = new Array(count);
        var sizeTotal = 0;
        var sizeAvg;

        if(multiSize) {
            for(i = 0; i < count; i++) {
                sizes[i] = markerSizeFunc(optsIn.size[i]);
                sizeTotal += sizes[i];
            }
            sizeAvg = sizeTotal / count;
        } else {
            s = markerSizeFunc(optsIn.size);
            for(i = 0; i < count; i++) {
                sizes[i] = s;
            }
        }

        // See  https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798
        if(multiLineWidth) {
            for(i = 0; i < count; i++) {
                borderSizes[i] = markerSizeFunc(optsIn.line.width[i]);
            }
        } else {
            s = markerSizeFunc(optsIn.line.width);
            for(i = 0; i < count; i++) {
                borderSizes[i] = s;
            }
        }

        optsOut.sizeAvg = sizeAvg;
    } else {
        optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10);
        optsOut.borderSizes = markerSizeFunc(optsIn.line.width);
    }

    return optsOut;
}

function convertMarkerSelection(trace, target) {
    var optsIn = trace.marker;
    var optsOut = {};

    if(!target) return optsOut;

    if(target.marker && target.marker.symbol) {
        optsOut = convertMarkerStyle(Lib.extendFlat({}, optsIn, target.marker));
    } else if(target.marker) {
        if(target.marker.size) optsOut.sizes = target.marker.size;
        if(target.marker.color) optsOut.colors = target.marker.color;
        if(target.marker.opacity !== undefined) optsOut.opacity = target.marker.opacity;
    }

    return optsOut;
}

function convertErrorBarStyle(trace, target) {
    var optsOut = {
        capSize: target.width * 2,
        lineWidth: target.thickness,
        color: target.color
    };

    if(target.copy_ystyle) {
        optsOut = trace.error_y;
    }

    return optsOut;
}

var SYMBOL_SDF_SIZE = constants.SYMBOL_SDF_SIZE;
var SYMBOL_SIZE = constants.SYMBOL_SIZE;
var SYMBOL_STROKE = constants.SYMBOL_STROKE;
var SYMBOL_SDF = {};
var SYMBOL_SVG_CIRCLE = Drawing.symbolFuncs[0](SYMBOL_SIZE * 0.05);

function getSymbolSdf(symbol) {
    if(symbol === 'circle') return null;

    var symbolPath, symbolSdf;
    var symbolNumber = Drawing.symbolNumber(symbol);
    var symbolFunc = Drawing.symbolFuncs[symbolNumber % 100];
    var symbolNoDot = !!Drawing.symbolNoDot[symbolNumber % 100];
    var symbolNoFill = !!Drawing.symbolNoFill[symbolNumber % 100];

    var isDot = constants.DOT_RE.test(symbol);

    // get symbol sdf from cache or generate it
    if(SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol];

    if(isDot && !symbolNoDot) {
        symbolPath = symbolFunc(SYMBOL_SIZE * 1.1) + SYMBOL_SVG_CIRCLE;
    }
    else {
        symbolPath = symbolFunc(SYMBOL_SIZE);
    }

    symbolSdf = svgSdf(symbolPath, {
        w: SYMBOL_SDF_SIZE,
        h: SYMBOL_SDF_SIZE,
        viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE],
        stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE
    });
    SYMBOL_SDF[symbol] = symbolSdf;

    return symbolSdf || null;
}

function convertLinePositions(gd, trace, positions) {
    var count = positions.length / 2;
    var linePositions;
    var i;

    if(subTypes.hasLines(trace) && count) {
        if(trace.line.shape === 'hv') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                }
                else {
                    linePositions.push(positions[i * 2]);
                    linePositions.push(positions[i * 2 + 1]);
                    linePositions.push(positions[i * 2 + 2]);
                    linePositions.push(positions[i * 2 + 1]);
                }
            }
            linePositions.push(positions[positions.length - 2]);
            linePositions.push(positions[positions.length - 1]);
        } else if(trace.line.shape === 'vh') {
            linePositions = [];
            for(i = 0; i < count - 1; i++) {
                if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                    linePositions.push(NaN);
                }
                else {
                    linePositions.push(positions[i * 2]);
                    linePositions.push(positions[i * 2 + 1]);
                    linePositions.push(positions[i * 2]);
                    linePositions.push(positions[i * 2 + 3]);
                }
            }
            linePositions.push(positions[positions.length - 2]);
            linePositions.push(positions[positions.length - 1]);
        } else {
            linePositions = positions;
        }
    }

    // If we have data with gaps, we ought to use rect joins
    // FIXME: get rid of this
    var hasNaN = false;
    for(i = 0; i < linePositions.length; i++) {
        if(isNaN(linePositions[i])) {
            hasNaN = true;
            break;
        }
    }

    var join = (hasNaN || linePositions.length > constants.TOO_MANY_POINTS) ? 'rect' :
        subTypes.hasMarkers(trace) ? 'rect' : 'round';

    // fill gaps
    if(hasNaN && trace.connectgaps) {
        var lastX = linePositions[0];
        var lastY = linePositions[1];

        for(i = 0; i < linePositions.length; i += 2) {
            if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) {
                linePositions[i] = lastX;
                linePositions[i + 1] = lastY;
            }
            else {
                lastX = linePositions[i];
                lastY = linePositions[i + 1];
            }
        }
    }

    return {
        join: join,
        positions: linePositions
    };
}

function convertErrorBarPositions(gd, trace, positions) {
    var calcFromTrace = Registry.getComponentMethod('errorbars', 'calcFromTrace');
    var vals = calcFromTrace(trace, gd._fullLayout);
    var count = positions.length / 2;
    var out = {};

    function put(axLetter) {
        var errors = new Float64Array(4 * count);
        var ax = AxisIDs.getFromId(gd, trace[axLetter + 'axis']);
        var pOffset = {x: 0, y: 1}[axLetter];
        var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter];

        for(var i = 0, p = 0; i < count; i++, p += 4) {
            errors[p + eOffset[0]] = positions[i * 2 + pOffset] - ax.d2l(vals[i][axLetter + 's']) || 0;
            errors[p + eOffset[1]] = ax.d2l(vals[i][axLetter + 'h']) - positions[i * 2 + pOffset] || 0;
            errors[p + eOffset[2]] = 0;
            errors[p + eOffset[3]] = 0;
        }

        return errors;
    }

    if(trace.error_x && trace.error_x.visible) {
        out.x = {
            positions: positions,
            errors: put('x')
        };
    }
    if(trace.error_y && trace.error_y.visible) {
        out.y = {
            positions: positions,
            errors: put('y')
        };
    }

    return out;
}

module.exports = {
    convertStyle: convertStyle,
    convertMarkerStyle: convertMarkerStyle,
    convertMarkerSelection: convertMarkerSelection,
    convertLinePositions: convertLinePositions,
    convertErrorBarPositions: convertErrorBarPositions
};
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------- \\
// File: Tap.js                                                               \\
// Module: Touch                                                              \\
// Requires: Gesture.js                                                       \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2013 FastMail Pty Ltd. All rights reserved.                \\
// -------------------------------------------------------------------------- \\

/*global document */

"use strict";

( function ( NS ) {

/*  We can't just call preventDefault on touch(start|move), as this would
    prevent scrolling and also prevent links we want to act as normal from
    working. So we use this hack instead to capture the subsequent click and
    remove it from the app's existence.
*/
var MouseEventRemover = NS.Class({
    init: function ( target, defaultPrevented ) {
        this.target = target;
        this.stop = defaultPrevented;
        NS.ViewEventsController.addEventTarget( this, 30 );
    },
    fire: function ( type, event ) {
        var isClick = ( type === 'click' ) && !event.originalType,
            isMouse = isClick || /^mouse/.test( type );
        if ( isMouse && ( this.stop || event.target !== this.target ) ) {
            event.preventDefault();
        }
        if ( type === 'touchstart' || type === 'MSPointerStart' ) {
            NS.ViewEventsController.removeEventTarget( this );
        }
        return isMouse;
    }
});

var TapEvent = function ( type, target, preventDefault ) {
    this.isEvent = true;
    this.type = type;
    this.originalType = 'tap';
    this.target = target;
    this.preventDefault = preventDefault;
};

var TrackedTouch = function ( x, y, time, target ) {
    this.x = x;
    this.y = y;
    this.time = time;
    while ( target && !/^(?:A|BUTTON|INPUT)$/.test( target.nodeName ) ) {
        target = target.parentNode;
    }
    this.target = target;
    if ( target ) {
        NS.Element.addClass( target, 'tap-active' );
    }
};

TrackedTouch.prototype.done  = function () {
    var target = this.target;
    if ( target ) {
        NS.Element.removeClass( target, 'tap-active' );
    }
};

/*  A tap is defined as a touch which:

    * Lasts less than 200ms.
    * Moves less than 10px from the initial touch point.

    There may be other touches occurring at the same time (e.g. you could be
    holding one button and tap another; the tap gesture will still be
    recognised).
*/
NS.Tap = new NS.Gesture({

    _tracking: {},

    cancel: function () {
        var tracking = this._tracking,
            id;
        for ( id in tracking ) {
            tracking[ id ].done();
        }
        this._tracking = {};
    },

    start: function ( event ) {
        var touches = event.changedTouches || [ event ],
            tracking = this._tracking,
            now = Date.now(),
            i, l, touch, id;
        for ( i = 0, l = touches.length; i < l; i += 1 ) {
            touch = touches[i];
            id = touch.identifier || touch.pointerId;
            if ( !tracking[ id ] ) {
                tracking[ id ] = new TrackedTouch(
                    touch.screenX, touch.screenY, now, touch.target );
            }
        }
    },

    move: function ( event ) {
        var touches = event.changedTouches || [ event ],
            tracking = this._tracking,
            i, l, touch, id, trackedTouch, deltaX, deltaY;
        for ( i = 0, l = touches.length; i < l; i += 1 ) {
            touch = touches[i];
            id = touch.identifier || touch.pointerId;
            trackedTouch = tracking[ id ];
            if ( trackedTouch ) {
                deltaX = touch.screenX - trackedTouch.x;
                deltaY = touch.screenY - trackedTouch.y;
                if ( deltaX * deltaX + deltaY * deltaY > 100 ) {
                    trackedTouch.done();
                    delete tracking[ id ];
                }
            }
        }
    },

    end: function ( event ) {
        var touches = event.changedTouches || [ event ],
            tracking = this._tracking,
            now = Date.now(),
            i, l, touch, id, trackedTouch, defaultPrevented, target, nodeName,
            ViewEventsController = NS.ViewEventsController,
            preventDefault = function () {
                defaultPrevented = true;
            };
        for ( i = 0, l = touches.length; i < l; i += 1 ) {
            touch = touches[i];
            id = touch.identifier || touch.pointerId;
            trackedTouch = tracking[ id ];
            if ( trackedTouch ) {
                if ( now - trackedTouch.time < 200 ) {
                    defaultPrevented = false;
                    target = touch.target;
                    ViewEventsController.handleEvent(
                        new TapEvent( 'tap', target, preventDefault )
                    );
                    ViewEventsController.handleEvent(
                        new TapEvent( 'click', target, preventDefault )
                    );
                    // The tap could trigger a UI change. When the click event
                    // is fired 300ms later, if there is now an input under the
                    // area the touch took place, in iOS the keyboard will
                    // appear, even though the preventDefault on the click event
                    // stops it actually being focussed. Calling preventDefault
                    // on the touchend event stops this happening, however we
                    // must not do this if the user actually taps an input!
                    nodeName = target.nodeName;
                    if ( nodeName !== 'INPUT' && nodeName !== 'TEXTAREA' &&
                            nodeName !== 'SELECT' ) {
                        event.preventDefault();
                    }
                    new MouseEventRemover( target, defaultPrevented );
                }
                trackedTouch.done();
                delete tracking[ id ];
            }
        }
    }
});

}( this.O ) );
<commit_msg>Make <label>s a valid target for touch-active class.<commit_after>// -------------------------------------------------------------------------- \\
// File: Tap.js                                                               \\
// Module: Touch                                                              \\
// Requires: Gesture.js                                                       \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2013 FastMail Pty Ltd. All rights reserved.                \\
// -------------------------------------------------------------------------- \\

/*global document */

"use strict";

( function ( NS ) {

/*  We can't just call preventDefault on touch(start|move), as this would
    prevent scrolling and also prevent links we want to act as normal from
    working. So we use this hack instead to capture the subsequent click and
    remove it from the app's existence.
*/
var MouseEventRemover = NS.Class({
    init: function ( target, defaultPrevented ) {
        this.target = target;
        this.stop = defaultPrevented;
        NS.ViewEventsController.addEventTarget( this, 30 );
    },
    fire: function ( type, event ) {
        var isClick = ( type === 'click' ) && !event.originalType,
            isMouse = isClick || /^mouse/.test( type );
        if ( isMouse && ( this.stop || event.target !== this.target ) ) {
            event.preventDefault();
        }
        if ( type === 'touchstart' || type === 'MSPointerStart' ) {
            NS.ViewEventsController.removeEventTarget( this );
        }
        return isMouse;
    }
});

var TapEvent = function ( type, target, preventDefault ) {
    this.isEvent = true;
    this.type = type;
    this.originalType = 'tap';
    this.target = target;
    this.preventDefault = preventDefault;
};

var TrackedTouch = function ( x, y, time, target ) {
    this.x = x;
    this.y = y;
    this.time = time;
    while ( target && !/^(?:A|BUTTON|INPUT|LABEL)$/.test( target.nodeName ) ) {
        target = target.parentNode;
    }
    this.target = target;
    if ( target ) {
        NS.Element.addClass( target, 'tap-active' );
    }
};

TrackedTouch.prototype.done  = function () {
    var target = this.target;
    if ( target ) {
        NS.Element.removeClass( target, 'tap-active' );
    }
};

/*  A tap is defined as a touch which:

    * Lasts less than 200ms.
    * Moves less than 10px from the initial touch point.

    There may be other touches occurring at the same time (e.g. you could be
    holding one button and tap another; the tap gesture will still be
    recognised).
*/
NS.Tap = new NS.Gesture({

    _tracking: {},

    cancel: function () {
        var tracking = this._tracking,
            id;
        for ( id in tracking ) {
            tracking[ id ].done();
        }
        this._tracking = {};
    },

    start: function ( event ) {
        var touches = event.changedTouches || [ event ],
            tracking = this._tracking,
            now = Date.now(),
            i, l, touch, id;
        for ( i = 0, l = touches.length; i < l; i += 1 ) {
            touch = touches[i];
            id = touch.identifier || touch.pointerId;
            if ( !tracking[ id ] ) {
                tracking[ id ] = new TrackedTouch(
                    touch.screenX, touch.screenY, now, touch.target );
            }
        }
    },

    move: function ( event ) {
        var touches = event.changedTouches || [ event ],
            tracking = this._tracking,
            i, l, touch, id, trackedTouch, deltaX, deltaY;
        for ( i = 0, l = touches.length; i < l; i += 1 ) {
            touch = touches[i];
            id = touch.identifier || touch.pointerId;
            trackedTouch = tracking[ id ];
            if ( trackedTouch ) {
                deltaX = touch.screenX - trackedTouch.x;
                deltaY = touch.screenY - trackedTouch.y;
                if ( deltaX * deltaX + deltaY * deltaY > 100 ) {
                    trackedTouch.done();
                    delete tracking[ id ];
                }
            }
        }
    },

    end: function ( event ) {
        var touches = event.changedTouches || [ event ],
            tracking = this._tracking,
            now = Date.now(),
            i, l, touch, id, trackedTouch, defaultPrevented, target, nodeName,
            ViewEventsController = NS.ViewEventsController,
            preventDefault = function () {
                defaultPrevented = true;
            };
        for ( i = 0, l = touches.length; i < l; i += 1 ) {
            touch = touches[i];
            id = touch.identifier || touch.pointerId;
            trackedTouch = tracking[ id ];
            if ( trackedTouch ) {
                if ( now - trackedTouch.time < 200 ) {
                    defaultPrevented = false;
                    target = touch.target;
                    ViewEventsController.handleEvent(
                        new TapEvent( 'tap', target, preventDefault )
                    );
                    ViewEventsController.handleEvent(
                        new TapEvent( 'click', target, preventDefault )
                    );
                    // The tap could trigger a UI change. When the click event
                    // is fired 300ms later, if there is now an input under the
                    // area the touch took place, in iOS the keyboard will
                    // appear, even though the preventDefault on the click event
                    // stops it actually being focussed. Calling preventDefault
                    // on the touchend event stops this happening, however we
                    // must not do this if the user actually taps an input!
                    nodeName = target.nodeName;
                    if ( nodeName !== 'INPUT' && nodeName !== 'TEXTAREA' &&
                            nodeName !== 'SELECT' ) {
                        event.preventDefault();
                    }
                    new MouseEventRemover( target, defaultPrevented );
                }
                trackedTouch.done();
                delete tracking[ id ];
            }
        }
    }
});

}( this.O ) );
<|endoftext|>


<commit_before>module.exports = function (params, lfm) {
    'use strict';
    var async = require('async')
        , fs = require('fs')
        , path = require('path');

    var page
        , pageFile = path.join(__dirname, "/../.lastpage");

    function _t(f, t) {
        return setTimeout(f, t);
    }

    var pageFromFile;
    try {
        pageFromFile = fs.readFileSync(pageFile);
    } catch (e) {
        fs.writeFileSync(pageFile, params.page || 1);
    }
    page = params.page || pageFromFile || 1;
    try {
        async.forever(
            function (next) {
                lfm.library.getArtists({
                    'user': params.user || 'TaggingMachine',
                    'page': page
                }, function (err, topArtists) {
                    if (err)
                        next(err, null);
                    else {
                        async.every(topArtists.artist, function (artist, callback) {
                            lfm.library.addArtist(artist.name, function (err) {
                                if (err) {
                                    console.log(artist.name, err);
                                }
                                else if (params.log)
                                    console.log(artist.name, 'was successfully added to library');
                                _t(function () {
                                    callback(err)
                                }, 300);
                            });
                        }, function (result) {
                            page++;
                            params.log && console.log("\n\n\tWe are on page " + page + " now.\n\n");
                            _t(function () {
                                next(err, null)
                            }, 450 + Math.floor(Math.random() * 100) + (Math.random() > .9 ? 1500 : 0));
                        });
                    }
                });
            },
            function (err) {
                if (err) {
                    return console.log('We\'re in trouble', err);
                }
            }
        );
    } catch (e) {
        savePage();
        return console.log("ended abnormally, saving page to file. to prevent program from loading last page, just specify --page to 1")
    }

    process.on('exit', function (code) {
        savePage();
        console.log("to prevent program from loading last page, just specify --page to 1")
    });

    function savePage() {
        try {
            fs.writeFileSync(pageFile, page, null);
        } catch (e) {
            return console.log("page not saved, neh");
        }
        console.log("page saved");
    }
};<commit_msg>Delay multiplier for addToLibrary method<commit_after>module.exports = function (params, lfm) {
    'use strict';
    var delayMultiplier = parseFloat(params.delayMultiplier) || 1.0;
    var async = require('async')
        , fs = require('fs')
        , path = require('path');

    var page
        , pageFile = path.join(__dirname, "/../.lastpage");

    function _t(f, t) {
        return setTimeout(f, t);
    }

    var pageFromFile;
    try {
        pageFromFile = fs.readFileSync(pageFile);
    } catch (e) {
        fs.writeFileSync(pageFile, params.page || 1);
    }
    page = params.page || pageFromFile || 1;
    try {
        async.forever(
            function (next) {
                lfm.library.getArtists({
                    'user': params.user || 'TaggingMachine',
                    'page': page
                }, function (err, topArtists) {
                    if (err)
                        next(err, null);
                    else {
                        async.every(topArtists.artist, function (artist, callback) {
                            lfm.library.addArtist(artist.name, function (err) {
                                if (err) {
                                    console.log(artist.name, err);
                                }
                                else if (params.log)
                                    console.log(artist.name, 'was successfully added to library');
                                _t(function () {
                                    callback(err)
                                }, 300*delayMultiplier);
                            });
                        }, function (result) {
                            page++;
                            params.log && console.log("\n\n\tWe are on page " + page + " now.\n\n");
                            _t(function () {
                                next(err, null)
                            }, 450*delayMultiplier + Math.floor(Math.random() * 100) + (Math.random() > .9 ? 1500 : 0));
                        });
                    }
                });
            },
            function (err) {
                if (err) {
                    return console.log('We\'re in trouble', err);
                }
            }
        );
    } catch (e) {
        savePage();
        return console.log("ended abnormally, saving page to file. to prevent program from loading last page, just specify --page to 1")
    }

    process.on('exit', function (code) {
        savePage();
        console.log("to prevent program from loading last page, just specify --page to 1")
    });

    function savePage() {
        try {
            fs.writeFileSync(pageFile, page, null);
        } catch (e) {
            return console.log("page not saved, neh");
        }
        console.log("page saved");
    }
};<|endoftext|>


<commit_before>/* @flow */

import type { Insertable } from "./types";

import { toArray } from "../utils";

function prependString(element: Element, insertable: string): void {
  element.insertAdjacentHTML("afterbegin", insertable);
}

function prependNode(element: Element, insertable: Node): void {
  element.insertBefore(insertable, element.firstChild);
}

function prependNodeList(element: Element, insertable: NodeList<*>): void {
  toArray(insertable).reverse().forEach(node => {
    prependNode(element, node);
  });
}

export default function prepend(
  element: Element,
  ...insertables: Array<Insertable>
): void {
  insertables.reverse().forEach(insertable => {
    if (typeof insertable === "string") {
      prependString(element, insertable);
    } else if (insertable instanceof Node) {
      prependNode(element, insertable);
    } else {
      prependNodeList(element, insertable);
    }
  });
}
<commit_msg>Normalize element after prepending content<commit_after>/* @flow */

import type { Insertable } from "./types";

import { toArray } from "../utils";

function prependString(element: Element, insertable: string): void {
  element.insertAdjacentHTML("afterbegin", insertable);
}

function prependNode(element: Element, insertable: Node): void {
  element.insertBefore(insertable, element.firstChild);
}

function prependNodeList(element: Element, insertable: NodeList<*>): void {
  toArray(insertable).reverse().forEach(node => {
    prependNode(element, node);
  });
}

export default function prepend(
  element: Element,
  ...insertables: Array<Insertable>
): void {
  insertables.reverse().forEach(insertable => {
    if (typeof insertable === "string") {
      prependString(element, insertable);
    } else if (insertable instanceof Node) {
      prependNode(element, insertable);
    } else {
      prependNodeList(element, insertable);
    }
  });

  element.normalize();
}
<|endoftext|>


<commit_before>/**
 * GITHUB PAGES
 * Deploy generated pages to Github
 */

/**
 * CONFIG
 */
var gulp = require('gulp');
var ghPages = require('gulp-gh-pages');

/**
 * CONFIG
 */
var jekyll = require('../gulp-config').jekyll;

/**
 * GITHUB PAGES
 */
gulp.task('gh-pages', function() {
  return gulp.src(jekyll.deploy)
    .pipe(ghPages({
      branch: 'master'
    }));
});
<commit_msg>push gh-pages to ssh<commit_after>/**
 * GITHUB PAGES
 * Deploy generated pages to Github
 */

/**
 * CONFIG
 */
var gulp = require('gulp');
var ghPages = require('gulp-gh-pages');

/**
 * CONFIG
 */
var jekyll = require('../gulp-config').jekyll;

/**
 * GITHUB PAGES
 */
gulp.task('gh-pages', function() {
  return gulp.src(jekyll.deploy)
    .pipe(ghPages({
      branch: 'master',
      remoteUrl: 'git@github.com:IanTeda/ianteda.github.io.git'
    }));
});
<|endoftext|>