<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/eventmanager", "./toggler", "./logo-spinner", "./context-button", "./header", "./unload-dialog" ],
        function( EventManagerWrapper, Toggler, LogoSpinner, ContextButton, Header, LangUtils, EDITOR_AREA_LAYOUT, UnloadDialog ){

  var TRANSITION_DURATION = 500,
      BUTTER_CSS_FILE = "{css}/butter.ui.css";

  function Area( id, element ){
    var _element,
        _components = [],
        _this = this;

    EventManagerWrapper( _this );

    this.element = _element = element || document.createElement( "div" );
    _element.id = id;
    this.items = {};

    this.addComponent = function( element, options ){
      var component = new Component( element, options );
      _components.push( component );
      _element.appendChild( component.element );
    };

    this.setContentState = function( state ){
      for( var i=0, l=_components.length; i<l; ++i ){
        _components[ i ].setState( state );
      }
    };
  }

  function Component( element, options ){
    options = options || {};
    var _onTransitionIn = options.transitionIn || function(){},
        _onTransitionInComplete = options.transitionInComplete || function(){},
        _onTransitionOut = options.transitionOut || function(){},
        _onTransitionOutComplete = options.transitionOutComplete || function(){},
        _validStates = options.states || [],
        _enabled = false;

    this.element = element;

    this.setState = function( state ){
      if( ( !_validStates || _validStates.indexOf( state ) > -1 ) && !_enabled ){
        _enabled = true;
        _onTransitionIn();
        setTimeout( _onTransitionInComplete, TRANSITION_DURATION );
      }
      else if( _enabled ){
        _onTransitionOut();
        setTimeout( _onTransitionOutComplete, TRANSITION_DURATION );
        _enabled = false;
      }
    };
  }

  function loadIcons( icons, resourcesDir ){
    var icon, img, div;

    for( icon in icons ){
      if( icons.hasOwnProperty( icon ) ){
        img = new Image();
        img.id = icon + "-icon";
        img.src = resourcesDir + icons[ icon ];

        // We can't use "display: none", since that makes it
        // invisible, and thus not load.  Opera also requires
        // the image be in the DOM before it will load.
        div = document.createElement( "div" );
        div.setAttribute( "data-butter-exclude", "true" );
        div.className = "butter-image-preload";

        div.appendChild( img );
        document.body.appendChild( div );
      }
    }
  }

  var __unwantedKeyPressElements = [
    "TEXTAREA",
    "INPUT",
    "VIDEO",
    "AUDIO"
  ];

  var NUDGE_INCREMENT_SMALL = 0.25,
      NUDGE_INCREMENT_LARGE = 1;

  function UI( butter ){

    var _areas = {},
        _contentState = [],
        _state = true,
        _logoSpinner,
        uiConfig = butter.config,
        _this = this;

    EventManagerWrapper( _this );
    UnloadDialog( butter );

    // Expose Area to external bodies through `butter.ui`
    // Modules should be creating their own Areas when possible
    _this.Area = Area;

    _areas.main = new Area( "butter-tray" );

    this.contentStateLocked = false;

    var _element = _areas.main.element,
        _toggler = new Toggler( function ( e ) {
          butter.ui.visible = !butter.ui.visible;
          _toggler.state = butter.ui.visible;
        }, "Show/Hide Timeline" );

    _element.setAttribute( "data-butter-exclude", "true" );
    _element.className = "butter-tray";

    _element.appendChild( _toggler.element );

    _areas.work = new Area( "work" );
    _areas.statusbar = new Area( "status-bar" );
    _areas.tools = new Area( "tools" );

    var logoContainer = document.createElement( "div" );
    logoContainer.id = "butter-loading-container";
    _logoSpinner = LogoSpinner( logoContainer );
    _element.appendChild( logoContainer );

    _element.appendChild( _areas.statusbar.element );
    _element.appendChild( _areas.work.element );
    _element.appendChild( _areas.tools.element );

    if( uiConfig.value( "ui" ).enabled !== false ){
      document.body.classList.add( "butter-header-spacing" );
      document.body.classList.add( "butter-tray-spacing" );
      document.body.appendChild( _element );
      butter.listen( "mediaadded", function( e ){
        e.data.createView();
      });
    }

    this.load = function( onReady ){
      if( uiConfig.value( "ui" ).enabled !== false ){
        butter.loader.load(
          [
            {
              type: "css",
              url: BUTTER_CSS_FILE
            }
          ],
          function(){
            // icon preloading needs css to be loaded first
            loadIcons( uiConfig.value( "icons" ), uiConfig.value( "dirs" ).resources || "" );
            onReady();
          }
        );
      }
      else{
        onReady();
      }
    };

    this.registerStateToggleFunctions = function( state, events ){
      _this.listen( "contentstatechanged", function( e ){
        if( e.data.oldState === state ){
          events.transitionOut( e );
        }
        if( e.data.newState === state ){
          events.transitionIn( e );
        }
      });
    };

    this.pushContentState = function( state ){
      if( _this.contentStateLocked ){
        return;
      }
      var oldState = _this.contentState;
      _contentState.push( state );
      _element.setAttribute( "data-butter-content-state", _this.contentState );
      for( var a in _areas ){
        if( _areas.hasOwnProperty( a ) ){
          _areas[ a ].setContentState( state );
        }
      }
      _this.dispatch( "contentstatechanged", {
        oldState: oldState,
        newState: _this.contentState
      });
    };

    this.popContentState = function(){
      if( _this.contentStateLocked ){
        return;
      }
      var oldState = _contentState.pop(),
          newState = _this.contentState;
      _element.setAttribute( "data-butter-content-state", newState );
      for( var a in _areas ){
        if( _areas.hasOwnProperty( a ) ){
          _areas[ a ].setContentState( newState );
        }
      }
      _this.dispatch( "contentstatechanged", {
        oldState: oldState,
        newState: newState
      });
      return oldState;
    };

    this.setContentState = function( newState ){
      var oldState = _contentState.pop();
      _contentState = [ newState ];
      _element.setAttribute( "data-butter-content-state", newState );
      for( var a in _areas ){
        if( _areas.hasOwnProperty( a ) ){
          _areas[ a ].setContentState( newState );
        }
      }
      _this.dispatch( "contentstatechanged", {
        oldState: oldState,
        newState: newState
      });
      return oldState;
    };

    Object.defineProperties( this, {
      contentState: {
        configurable: false,
        enumerable: true,
        get: function(){
          if( _contentState.length > 0 ){
            return _contentState[ _contentState.length - 1 ];
          }
          return null;
        }
      },
      element: {
        configurable: false,
        enumerable: true,
        get: function(){
          return _element;
        }
      },
      areas: {
        configurable: false,
        enumerable: true,
        get: function(){
          return _areas;
        }
      },
      visible: {
        enumerable: true,
        get: function(){
          return _state;
        },
        set: function( val ){
          if( _state !== val ){
            _state = val;
            if( _state ){
              _element.classList.remove( "minimized" );
              _this.dispatch( "uivisibilitychanged", true );
            }
            else {
              _element.classList.add( "minimized" );
              _this.dispatch( "uivisibilitychanged", false );
            } //if
          } //if
        }
      }
    });

    var orderedTrackEvents = butter.orderedTrackEvents = [],
        sortTrackEvents = function( a, b ) {
          return a.popcornOptions.start > b .popcornOptions.start;
        };

    butter.listen( "trackeventadded", function( e ) {
      orderedTrackEvents.push( e.data );
      orderedTrackEvents.sort( sortTrackEvents );
    }); // listen

    butter.listen( "trackeventremoved", function( e ) {
      var index = orderedTrackEvents.indexOf( e.data );
      if( index > -1 ){
        orderedTrackEvents.splice( index, 1 );
      } // if
    }); // listen

    butter.listen( "trackeventupdated", function( e ) {
      orderedTrackEvents.sort( sortTrackEvents );
    }); // listen

    var orderedTracks = butter.orderedTracks = [],
        sortTracks = function( a, b ) {
          return a.order > b.order;
        };

    butter.listen( "trackadded", function( e ) {
      e.data.listen( "trackorderchanged", function( e ) {
        orderedTracks.sort( sortTracks );
      }); // listen
      orderedTracks.push( e.data );
      orderedTracks.sort( sortTracks );
    }); // listen

    butter.listen( "trackremoved", function( e ) {
      var index = orderedTracks.indexOf( e.data );
      if( index > -1 ){
        orderedTracks.splice( index, 1 );
      } // if
    }); // listen

    var processKey = {
      32: function( e ) { // space key
        e.preventDefault();

        if( butter.currentMedia.ended ){
          butter.currentMedia.paused = false;
        }
        else{
          butter.currentMedia.paused = !butter.currentMedia.paused;
        }
      }, // space key
      37: function( e ) { // left key
        var inc = e.shiftKey ? NUDGE_INCREMENT_LARGE : NUDGE_INCREMENT_SMALL;
        if( butter.selectedEvents.length ) {
          e.preventDefault();
          for( var i = 0, seLength = butter.selectedEvents.length; i < seLength; i++ ) {
            butter.selectedEvents[ i ].moveFrameLeft( inc, e.ctrlKey || e.metaKey );
          } // for
        } else {
          butter.currentTime -= inc;
        } // if
      }, // left key
      38: function( e ) { // up key
        var track,
            trackEvent,
            nextTrack;

        if ( butter.selectedEvents.length ) {
          e.preventDefault();
        }

        for( var i = 0, seLength = butter.selectedEvents.length; i < seLength; i++ ) {
          trackEvent = butter.selectedEvents[ i ];
          track = trackEvent.track;
          nextTrack = orderedTracks[ orderedTracks.indexOf( track ) - 1 ];
          if( nextTrack ) {
            track.removeTrackEvent( trackEvent );
            nextTrack.addTrackEvent( trackEvent );
          } // if
        } // for
      }, // up key
      39: function( e ) { // right key
        e.preventDefault();
        var inc = e.shiftKey ? NUDGE_INCREMENT_LARGE : NUDGE_INCREMENT_SMALL;
        if( butter.selectedEvents.length ) {
          for( var i = 0, seLength = butter.selectedEvents.length; i < seLength; i++ ) {
            butter.selectedEvents[ i ].moveFrameRight( inc, e.ctrlKey || e.metaKey );
          } // for
        } else {
          butter.currentTime += inc;
        } // if
      }, // right key
      40: function( e ) { // down key
        var track,
            trackEvent,
            nextTrack;

        if ( butter.selectedEvents.length ) {
          e.preventDefault();
        }

        for( var i = 0, seLength = butter.selectedEvents.length; i < seLength; i++ ) {
          trackEvent = butter.selectedEvents[ i ];
          track = trackEvent.track;
          nextTrack = orderedTracks[ orderedTracks.indexOf( track ) + 1 ];
          if( nextTrack ) {
            track.removeTrackEvent( trackEvent );
            nextTrack.addTrackEvent( trackEvent );
          } // if
        } // for
      }, // down key
      27: function( e ) { // esc key
        for( var i = 0; i < butter.selectedEvents.length; i++ ) {
          butter.selectedEvents[ i ].selected = false;
        } // for
        butter.selectedEvents = [];
      }, // esc key
      8: function( e ) { // del key
        if( butter.selectedEvents.length ) {
          e.preventDefault();
          for( var i = 0; i < butter.selectedEvents.length; i++ ) {
            butter.selectedEvents[ i ].track.removeTrackEvent( butter.selectedEvents[ i ] );
          } // for
          butter.selectedEvents = [];
        } // if
      }, // del key
      9: function( e ) { // tab key
        if( orderedTrackEvents.length && butter.selectedEvents.length <= 1 ){
          e.preventDefault();
          var index = 0,
              direction = e.shiftKey ? -1 : 1;
          if( orderedTrackEvents.indexOf( butter.selectedEvents[ 0 ] ) > -1 ){
            index = orderedTrackEvents.indexOf( butter.selectedEvents[ 0 ] );
            if( orderedTrackEvents[ index+direction ] ){
              index+=direction;
            } else if( !e.shiftKey ){
              index = 0;
            } else {
              index = orderedTrackEvents.length - 1;
            } // if
          } // if
          for( var i = 0; i < butter.selectedEvents.length; i++ ) {
            butter.selectedEvents[ i ].selected = false;
          } // for
          butter.selectedEvents = [];
          orderedTrackEvents[ index ].selected = true;
          butter.selectedEvents.push( orderedTrackEvents[ index ] );
        } // if
      } // tab key
    };

    window.addEventListener( "keydown", function( e ){
      var key = e.which || e.keyCode;
      // this allows backspace and del to do the same thing on windows and mac keyboards
      key = key === 46 ? 8 : key;
      if( processKey[ key ] && __unwantedKeyPressElements.indexOf( e.target.nodeName ) === -1 ){
        processKey[ key ]( e );
      } // if
    }, false );

    this.TRANSITION_DURATION = TRANSITION_DURATION;

    _toggler.visible = false;
    _this.visible = false;

    this.loadIndicator = {
      start: function(){
        _logoSpinner.start();
        logoContainer.style.display = "block";
      },
      stop: function(){
        _logoSpinner.stop(function(){
          logoContainer.style.display = "none";
        });
      }
    };

    _this.loadIndicator.start();

    butter.listen( "ready", function(){
      _this.loadIndicator.stop();
      _this.visible = true;
      _toggler.visible = true;
      ContextButton( butter );
      if( uiConfig.value( "ui" ).enabled !== false ){
        Header( butter, uiConfig );
      }
    });

    _this.dialogDir = butter.config.value( "dirs" ).dialogs || "";

  } //UI

  UI.__moduleName = "ui";

  return UI;

});
<commit_msg>[t1174] some merge/rebase confusion resolved<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/eventmanager", "./toggler", "./logo-spinner", "./context-button", "./header", "./unload-dialog" ],
        function( EventManagerWrapper, Toggler, LogoSpinner, ContextButton, Header, UnloadDialog ){

  var TRANSITION_DURATION = 500,
      BUTTER_CSS_FILE = "{css}/butter.ui.css";

  function Area( id, element ){
    var _element,
        _components = [],
        _this = this;

    EventManagerWrapper( _this );

    this.element = _element = element || document.createElement( "div" );
    _element.id = id;
    this.items = {};

    this.addComponent = function( element, options ){
      var component = new Component( element, options );
      _components.push( component );
      _element.appendChild( component.element );
    };

    this.setContentState = function( state ){
      for( var i=0, l=_components.length; i<l; ++i ){
        _components[ i ].setState( state );
      }
    };
  }

  function Component( element, options ){
    options = options || {};
    var _onTransitionIn = options.transitionIn || function(){},
        _onTransitionInComplete = options.transitionInComplete || function(){},
        _onTransitionOut = options.transitionOut || function(){},
        _onTransitionOutComplete = options.transitionOutComplete || function(){},
        _validStates = options.states || [],
        _enabled = false;

    this.element = element;

    this.setState = function( state ){
      if( ( !_validStates || _validStates.indexOf( state ) > -1 ) && !_enabled ){
        _enabled = true;
        _onTransitionIn();
        setTimeout( _onTransitionInComplete, TRANSITION_DURATION );
      }
      else if( _enabled ){
        _onTransitionOut();
        setTimeout( _onTransitionOutComplete, TRANSITION_DURATION );
        _enabled = false;
      }
    };
  }

  function loadIcons( icons, resourcesDir ){
    var icon, img, div;

    for( icon in icons ){
      if( icons.hasOwnProperty( icon ) ){
        img = new Image();
        img.id = icon + "-icon";
        img.src = resourcesDir + icons[ icon ];

        // We can't use "display: none", since that makes it
        // invisible, and thus not load.  Opera also requires
        // the image be in the DOM before it will load.
        div = document.createElement( "div" );
        div.setAttribute( "data-butter-exclude", "true" );
        div.className = "butter-image-preload";

        div.appendChild( img );
        document.body.appendChild( div );
      }
    }
  }

  var __unwantedKeyPressElements = [
    "TEXTAREA",
    "INPUT",
    "VIDEO",
    "AUDIO"
  ];

  var NUDGE_INCREMENT_SMALL = 0.25,
      NUDGE_INCREMENT_LARGE = 1;

  function UI( butter ){

    var _areas = {},
        _contentState = [],
        _state = true,
        _logoSpinner,
        uiConfig = butter.config,
        _this = this;

    EventManagerWrapper( _this );
    UnloadDialog( butter );

    // Expose Area to external bodies through `butter.ui`
    // Modules should be creating their own Areas when possible
    _this.Area = Area;

    _areas.main = new Area( "butter-tray" );

    this.contentStateLocked = false;

    var _element = _areas.main.element,
        _toggler = new Toggler( function ( e ) {
          butter.ui.visible = !butter.ui.visible;
          _toggler.state = butter.ui.visible;
        }, "Show/Hide Timeline" );

    _element.setAttribute( "data-butter-exclude", "true" );
    _element.className = "butter-tray";

    _element.appendChild( _toggler.element );

    _areas.work = new Area( "work" );
    _areas.statusbar = new Area( "status-bar" );
    _areas.tools = new Area( "tools" );

    var logoContainer = document.createElement( "div" );
    logoContainer.id = "butter-loading-container";
    _logoSpinner = LogoSpinner( logoContainer );
    _element.appendChild( logoContainer );

    _element.appendChild( _areas.statusbar.element );
    _element.appendChild( _areas.work.element );
    _element.appendChild( _areas.tools.element );

    if( uiConfig.value( "ui" ).enabled !== false ){
      document.body.classList.add( "butter-header-spacing" );
      document.body.classList.add( "butter-tray-spacing" );
      document.body.appendChild( _element );
      butter.listen( "mediaadded", function( e ){
        e.data.createView();
      });
    }

    this.load = function( onReady ){
      if( uiConfig.value( "ui" ).enabled !== false ){
        butter.loader.load(
          [
            {
              type: "css",
              url: BUTTER_CSS_FILE
            }
          ],
          function(){
            // icon preloading needs css to be loaded first
            loadIcons( uiConfig.value( "icons" ), uiConfig.value( "dirs" ).resources || "" );
            onReady();
          }
        );
      }
      else{
        onReady();
      }
    };

    this.registerStateToggleFunctions = function( state, events ){
      _this.listen( "contentstatechanged", function( e ){
        if( e.data.oldState === state ){
          events.transitionOut( e );
        }
        if( e.data.newState === state ){
          events.transitionIn( e );
        }
      });
    };

    this.pushContentState = function( state ){
      if( _this.contentStateLocked ){
        return;
      }
      var oldState = _this.contentState;
      _contentState.push( state );
      _element.setAttribute( "data-butter-content-state", _this.contentState );
      for( var a in _areas ){
        if( _areas.hasOwnProperty( a ) ){
          _areas[ a ].setContentState( state );
        }
      }
      _this.dispatch( "contentstatechanged", {
        oldState: oldState,
        newState: _this.contentState
      });
    };

    this.popContentState = function(){
      if( _this.contentStateLocked ){
        return;
      }
      var oldState = _contentState.pop(),
          newState = _this.contentState;
      _element.setAttribute( "data-butter-content-state", newState );
      for( var a in _areas ){
        if( _areas.hasOwnProperty( a ) ){
          _areas[ a ].setContentState( newState );
        }
      }
      _this.dispatch( "contentstatechanged", {
        oldState: oldState,
        newState: newState
      });
      return oldState;
    };

    this.setContentState = function( newState ){
      var oldState = _contentState.pop();
      _contentState = [ newState ];
      _element.setAttribute( "data-butter-content-state", newState );
      for( var a in _areas ){
        if( _areas.hasOwnProperty( a ) ){
          _areas[ a ].setContentState( newState );
        }
      }
      _this.dispatch( "contentstatechanged", {
        oldState: oldState,
        newState: newState
      });
      return oldState;
    };

    Object.defineProperties( this, {
      contentState: {
        configurable: false,
        enumerable: true,
        get: function(){
          if( _contentState.length > 0 ){
            return _contentState[ _contentState.length - 1 ];
          }
          return null;
        }
      },
      element: {
        configurable: false,
        enumerable: true,
        get: function(){
          return _element;
        }
      },
      areas: {
        configurable: false,
        enumerable: true,
        get: function(){
          return _areas;
        }
      },
      visible: {
        enumerable: true,
        get: function(){
          return _state;
        },
        set: function( val ){
          if( _state !== val ){
            _state = val;
            if( _state ){
              _element.classList.remove( "minimized" );
              _this.dispatch( "uivisibilitychanged", true );
            }
            else {
              _element.classList.add( "minimized" );
              _this.dispatch( "uivisibilitychanged", false );
            } //if
          } //if
        }
      }
    });

    var orderedTrackEvents = butter.orderedTrackEvents = [],
        sortTrackEvents = function( a, b ) {
          return a.popcornOptions.start > b .popcornOptions.start;
        };

    butter.listen( "trackeventadded", function( e ) {
      orderedTrackEvents.push( e.data );
      orderedTrackEvents.sort( sortTrackEvents );
    }); // listen

    butter.listen( "trackeventremoved", function( e ) {
      var index = orderedTrackEvents.indexOf( e.data );
      if( index > -1 ){
        orderedTrackEvents.splice( index, 1 );
      } // if
    }); // listen

    butter.listen( "trackeventupdated", function( e ) {
      orderedTrackEvents.sort( sortTrackEvents );
    }); // listen

    var orderedTracks = butter.orderedTracks = [],
        sortTracks = function( a, b ) {
          return a.order > b.order;
        };

    butter.listen( "trackadded", function( e ) {
      e.data.listen( "trackorderchanged", function( e ) {
        orderedTracks.sort( sortTracks );
      }); // listen
      orderedTracks.push( e.data );
      orderedTracks.sort( sortTracks );
    }); // listen

    butter.listen( "trackremoved", function( e ) {
      var index = orderedTracks.indexOf( e.data );
      if( index > -1 ){
        orderedTracks.splice( index, 1 );
      } // if
    }); // listen

    var processKey = {
      32: function( e ) { // space key
        e.preventDefault();

        if( butter.currentMedia.ended ){
          butter.currentMedia.paused = false;
        }
        else{
          butter.currentMedia.paused = !butter.currentMedia.paused;
        }
      }, // space key
      37: function( e ) { // left key
        var inc = e.shiftKey ? NUDGE_INCREMENT_LARGE : NUDGE_INCREMENT_SMALL;
        if( butter.selectedEvents.length ) {
          e.preventDefault();
          for( var i = 0, seLength = butter.selectedEvents.length; i < seLength; i++ ) {
            butter.selectedEvents[ i ].moveFrameLeft( inc, e.ctrlKey || e.metaKey );
          } // for
        } else {
          butter.currentTime -= inc;
        } // if
      }, // left key
      38: function( e ) { // up key
        var track,
            trackEvent,
            nextTrack;

        if ( butter.selectedEvents.length ) {
          e.preventDefault();
        }

        for( var i = 0, seLength = butter.selectedEvents.length; i < seLength; i++ ) {
          trackEvent = butter.selectedEvents[ i ];
          track = trackEvent.track;
          nextTrack = orderedTracks[ orderedTracks.indexOf( track ) - 1 ];
          if( nextTrack ) {
            track.removeTrackEvent( trackEvent );
            nextTrack.addTrackEvent( trackEvent );
          } // if
        } // for
      }, // up key
      39: function( e ) { // right key
        e.preventDefault();
        var inc = e.shiftKey ? NUDGE_INCREMENT_LARGE : NUDGE_INCREMENT_SMALL;
        if( butter.selectedEvents.length ) {
          for( var i = 0, seLength = butter.selectedEvents.length; i < seLength; i++ ) {
            butter.selectedEvents[ i ].moveFrameRight( inc, e.ctrlKey || e.metaKey );
          } // for
        } else {
          butter.currentTime += inc;
        } // if
      }, // right key
      40: function( e ) { // down key
        var track,
            trackEvent,
            nextTrack;

        if ( butter.selectedEvents.length ) {
          e.preventDefault();
        }

        for( var i = 0, seLength = butter.selectedEvents.length; i < seLength; i++ ) {
          trackEvent = butter.selectedEvents[ i ];
          track = trackEvent.track;
          nextTrack = orderedTracks[ orderedTracks.indexOf( track ) + 1 ];
          if( nextTrack ) {
            track.removeTrackEvent( trackEvent );
            nextTrack.addTrackEvent( trackEvent );
          } // if
        } // for
      }, // down key
      27: function( e ) { // esc key
        for( var i = 0; i < butter.selectedEvents.length; i++ ) {
          butter.selectedEvents[ i ].selected = false;
        } // for
        butter.selectedEvents = [];
      }, // esc key
      8: function( e ) { // del key
        if( butter.selectedEvents.length ) {
          e.preventDefault();
          for( var i = 0; i < butter.selectedEvents.length; i++ ) {
            butter.selectedEvents[ i ].track.removeTrackEvent( butter.selectedEvents[ i ] );
          } // for
          butter.selectedEvents = [];
        } // if
      }, // del key
      9: function( e ) { // tab key
        if( orderedTrackEvents.length && butter.selectedEvents.length <= 1 ){
          e.preventDefault();
          var index = 0,
              direction = e.shiftKey ? -1 : 1;
          if( orderedTrackEvents.indexOf( butter.selectedEvents[ 0 ] ) > -1 ){
            index = orderedTrackEvents.indexOf( butter.selectedEvents[ 0 ] );
            if( orderedTrackEvents[ index+direction ] ){
              index+=direction;
            } else if( !e.shiftKey ){
              index = 0;
            } else {
              index = orderedTrackEvents.length - 1;
            } // if
          } // if
          for( var i = 0; i < butter.selectedEvents.length; i++ ) {
            butter.selectedEvents[ i ].selected = false;
          } // for
          butter.selectedEvents = [];
          orderedTrackEvents[ index ].selected = true;
          butter.selectedEvents.push( orderedTrackEvents[ index ] );
        } // if
      } // tab key
    };

    window.addEventListener( "keydown", function( e ){
      var key = e.which || e.keyCode;
      // this allows backspace and del to do the same thing on windows and mac keyboards
      key = key === 46 ? 8 : key;
      if( processKey[ key ] && __unwantedKeyPressElements.indexOf( e.target.nodeName ) === -1 ){
        processKey[ key ]( e );
      } // if
    }, false );

    this.TRANSITION_DURATION = TRANSITION_DURATION;

    _toggler.visible = false;
    _this.visible = false;

    this.loadIndicator = {
      start: function(){
        _logoSpinner.start();
        logoContainer.style.display = "block";
      },
      stop: function(){
        _logoSpinner.stop(function(){
          logoContainer.style.display = "none";
        });
      }
    };

    _this.loadIndicator.start();

    butter.listen( "ready", function(){
      _this.loadIndicator.stop();
      _this.visible = true;
      _toggler.visible = true;
      ContextButton( butter );
      if( uiConfig.value( "ui" ).enabled !== false ){
        Header( butter, uiConfig );
      }
    });

    _this.dialogDir = butter.config.value( "dirs" ).dialogs || "";

  } //UI

  UI.__moduleName = "ui";

  return UI;

});
<|endoftext|>


<commit_before>var util = require('util'),
    events = require('events'),
    rewriter = require('./jsonrewriter');

/**
 * Class listening to Ripple network state and updating models.
 *
 * This class handles all incoming events by the network and updates
 * the appropriate local models.
 */
var Model = function ()
{
  events.EventEmitter.call(this);
};
util.inherits(Model, events.EventEmitter);

Model.prototype.init = function ()
{
  var $scope = this.app.$scope;

  $scope.balance = "0";

  $scope.currencies_all = require('../data/currencies');
  $scope.currencies = $scope.currencies_all.slice(1);
};

Model.prototype.setApp = function (app)
{
  this.app = app;
};

/**
 * Setup listeners for identity state.
 *
 * Causes the initialization of account model data.
 */
Model.prototype.listenId = function (id)
{
  id.on('accountload', this.handleAccountLoad.bind(this));
};

Model.prototype.handleAccountLoad = function (e)
{
  var remote = this.app.net.remote;
  remote.request_ripple_lines_get(e.account)
    .on('success', this.handleRippleLines.bind(this)).request();
  remote.request_wallet_accounts(e.secret)
    .on('success', this.handleAccounts.bind(this)).request();

  remote.on('net_account', this.handleAccountEvent.bind(this));

  var $scope = this.app.$scope;
  $scope.address = e.account;
};

Model.prototype.handleRippleLines = function (data)
{
  var $scope = this.app.$scope;
  $scope.$apply(function ()
  {
    $scope.lines={};
    for(var n=0; n<data.lines.length; n++)
    {
      $scope.lines[data.lines[n].account+data.lines[n].currency] = data.lines[n];
    }
    console.log('Lines updated:', $scope.lines);
  });
};

Model.prototype.handleAccounts = function (data)
{
  var self = this;
  var remote = this.app.net.remote;
  var $scope = this.app.$scope;
  $scope.$apply(function () {
    $scope.balance = data.accounts[0].Balance;

    remote.request_account_tx(data.accounts[0].Account, "0", "999999")
      .on('success', self.handleAccountTx.bind(self, data.accounts[0].Account)).request();
  });
};

Model.prototype.handleAccountTx = function (account, data)
{
  var self = this;

  var $scope = this.app.$scope;
  $scope.$apply(function () {
    $scope.history = [];
    if (data.transactions) {
      var transactions = data.transactions.forEach(function (e) {
        self._processTxn(e.tx, e.meta);
      });
    }
  });
};

Model.prototype.handleAccountEvent = function (e)
{
  this._processTxn(e.transaction, e.meta);
  var $scope = this.app.$scope;
  $scope.$digest();
};

/**
 * Process a transaction and add it to the history table.
 */
Model.prototype._processTxn = function (tx, meta)
{
  var $scope = this.app.$scope;

  var account = this.app.id.account;

  var historyEntry = rewriter.processTxn(tx, meta, account);

  $scope.history.unshift(historyEntry);

  if(tx.TransactionType === "TrustSet" ) this._updateLines(meta,account);
};

/*
account: "rHMq44aXmd9wEYHK84VyiZyx8SP6VbpzNV"
balance: "0"
currency: "USD"
limit: "2000"
limit_peer: "0"
quality_in: 0
quality_out: 0
 */
Model.prototype._updateLines= function(meta,account)
{
  var $scope = this.app.$scope;

  var nodes = rewriter.filterAnodes(meta.AffectedNodes, "RippleState");
  for (var i=0, l=nodes.length; i<l; i++) {
    var fields = rewriter.getAnodeResult(nodes[i]),
        index = peer_account+currency,
        currency = fields.Balance.currency,
        peer_account;

    if (!$scope.lines[index]) $scope.lines[index] = {};

    if (fields.HighLimit.issuer===account) {
      peer_account = fields.LowLimit.issuer;
      $scope.lines[index].limit = fields.HighLimit.value;
      $scope.lines[index].limit_peer = fields.LowLimit.value;
    } else if (fields.LowLimit.issuer===account) {
      peer_account = fields.HighLimit.issuer;
      $scope.lines[index].limit = fields.LowLimit.value;
      $scope.lines[index].limit_peer = fields.HighLimit.value;
    }
    $scope.lines[index].balance = fields.Balance.value;
  }
}

exports.Model = Model;
<commit_msg>Fix wrong index.<commit_after>var util = require('util'),
    events = require('events'),
    rewriter = require('./jsonrewriter');

/**
 * Class listening to Ripple network state and updating models.
 *
 * This class handles all incoming events by the network and updates
 * the appropriate local models.
 */
var Model = function ()
{
  events.EventEmitter.call(this);
};
util.inherits(Model, events.EventEmitter);

Model.prototype.init = function ()
{
  var $scope = this.app.$scope;

  $scope.balance = "0";

  $scope.currencies_all = require('../data/currencies');
  $scope.currencies = $scope.currencies_all.slice(1);
};

Model.prototype.setApp = function (app)
{
  this.app = app;
};

/**
 * Setup listeners for identity state.
 *
 * Causes the initialization of account model data.
 */
Model.prototype.listenId = function (id)
{
  id.on('accountload', this.handleAccountLoad.bind(this));
};

Model.prototype.handleAccountLoad = function (e)
{
  var remote = this.app.net.remote;
  remote.request_ripple_lines_get(e.account)
    .on('success', this.handleRippleLines.bind(this)).request();
  remote.request_wallet_accounts(e.secret)
    .on('success', this.handleAccounts.bind(this)).request();

  remote.on('net_account', this.handleAccountEvent.bind(this));

  var $scope = this.app.$scope;
  $scope.address = e.account;
};

Model.prototype.handleRippleLines = function (data)
{
  var $scope = this.app.$scope;
  $scope.$apply(function ()
  {
    $scope.lines={};
    for(var n=0; n<data.lines.length; n++)
    {
      $scope.lines[data.lines[n].account+data.lines[n].currency] = data.lines[n];
    }
    console.log('Lines updated:', $scope.lines);
  });
};

Model.prototype.handleAccounts = function (data)
{
  var self = this;
  var remote = this.app.net.remote;
  var $scope = this.app.$scope;
  $scope.$apply(function () {
    $scope.balance = data.accounts[0].Balance;

    remote.request_account_tx(data.accounts[0].Account, "0", "999999")
      .on('success', self.handleAccountTx.bind(self, data.accounts[0].Account)).request();
  });
};

Model.prototype.handleAccountTx = function (account, data)
{
  var self = this;

  var $scope = this.app.$scope;
  $scope.$apply(function () {
    $scope.history = [];
    if (data.transactions) {
      var transactions = data.transactions.forEach(function (e) {
        self._processTxn(e.tx, e.meta);
      });
    }
  });
};

Model.prototype.handleAccountEvent = function (e)
{
  this._processTxn(e.transaction, e.meta);
  var $scope = this.app.$scope;
  $scope.$digest();
};

/**
 * Process a transaction and add it to the history table.
 */
Model.prototype._processTxn = function (tx, meta)
{
  var $scope = this.app.$scope;

  var account = this.app.id.account;

  var historyEntry = rewriter.processTxn(tx, meta, account);

  $scope.history.unshift(historyEntry);

  if(tx.TransactionType === "TrustSet" ) this._updateLines(meta,account);
};

/*
account: "rHMq44aXmd9wEYHK84VyiZyx8SP6VbpzNV"
balance: "0"
currency: "USD"
limit: "2000"
limit_peer: "0"
quality_in: 0
quality_out: 0
 */
Model.prototype._updateLines= function(meta,account)
{
  var $scope = this.app.$scope;

  var nodes = rewriter.filterAnodes(meta.AffectedNodes, "RippleState");
  for (var i=0, l=nodes.length; i<l; i++) {
    var fields = rewriter.getAnodeResult(nodes[i]),
        currency = fields.Balance.currency,
        peer_account, index;

    var line = {};

    if (fields.HighLimit.issuer===account) {
      peer_account = fields.LowLimit.issuer;
      line.limit = fields.HighLimit.value;
      line.limit_peer = fields.LowLimit.value;
    } else if (fields.LowLimit.issuer===account) {
      peer_account = fields.HighLimit.issuer;
      line.limit = fields.LowLimit.value;
      line.limit_peer = fields.HighLimit.value;
    }
    line.balance = fields.Balance.value;

    index = peer_account+currency;

    $scope.lines[index] = $.extend($scope.lines[index], line);
  }
}

exports.Model = Model;
<|endoftext|>


<commit_before>/**
 * ui.i18n Created by Tim Sweet on 2/1/14.
 * https://github.com/timothyswt
 * MIT License
 */

/**
 * @ngdoc overview
 * @name ui.grid.i18n
 * @description
 *
 *  # ui.grid.i18n
 * This module provides i18n functions to ui.grid and any application that wants to use it

 *
 *

 */

(function () {
  var DIRECTIVE_ALIASES = ['uiT', 'uiTranslate'];
  var FILTER_ALIASES = ['t', 'uiTranslate'];

  var module = angular.module('ui.grid.i18n');

  /**
   *  @ngdoc object
   *  @name ui.grid.i18n.constant:i18nConstants
   *
   *  @description constants available in i18n module
   */
  module.constant('i18nConstants', {
    MISSING: '[MISSING]',
    UPDATE_EVENT: '$uiI18n',

    LOCALE_DIRECTIVE_ALIAS: 'uiI18n',
    // default to english
    DEFAULT_LANG: 'en'
  });

//    module.config(['$provide', function($provide) {
//        $provide.decorator('i18nService', ['$delegate', function($delegate) {}])}]);

  /**
   *  @ngdoc service
   *  @name ui.grid.i18n.service:i18nService
   *
   *  @description Services for i18n
   */
  module.service('i18nService', ['$log', 'i18nConstants', '$rootScope',
    function ($log, i18nConstants, $rootScope) {

      var langCache = {
        _langs: {},
        current: null,
        get: function (lang) {
          return this._langs[lang.toLowerCase()];
        },
        add: function (lang, strings) {
          var lower = lang.toLowerCase();
          if (!this._langs[lower]) {
            this._langs[lower] = {};
          }
          angular.extend(this._langs[lower], strings);
        },
        getAllLangs: function () {
          var langs = [];
          if (!this._langs) {
            return langs;
          }

          for (var key in this._langs) {
            langs.push(key);
          }

          return langs;
        },
        setCurrent: function (lang) {
          this.current = lang.toLowerCase();
        },
        getCurrentLang: function () {
          return this.current;
        }
      };

      var service = {

        /**
         * @ngdoc service
         * @name add
         * @methodOf ui.grid.i18n.service:i18nService
         * @description  Adds the languages and strings to the cache. Decorate this service to
         * add more translation strings
         * @param {string} lang language to add
         * @param {object} stringMaps of strings to add grouped by property names
         * @example
         *

         *      i18nService.add('en', {
         *         aggregate: {
         *                 label1: 'items',
         *                 label2: 'some more items'
         *                 }
         *         },
         *         groupPanel: {
         *              description: 'Drag a column header here and drop it to group by that column.'
         *           }
         *      }
         *

         */
        add: function (langs, stringMaps) {
          if (typeof(langs) === 'object') {
            angular.forEach(langs, function (lang) {
              if (lang) {
                langCache.add(lang, stringMaps);
              }
            });
          } else {
            langCache.add(langs, stringMaps);
          }
        },

        /**
         * @ngdoc service
         * @name getAllLangs
         * @methodOf ui.grid.i18n.service:i18nService
         * @description  return all currently loaded languages
         * @returns {array} string
         */
        getAllLangs: function () {
          return langCache.getAllLangs();
        },

        /**
         * @ngdoc service
         * @name get
         * @methodOf ui.grid.i18n.service:i18nService
         * @description  return all currently loaded languages
         * @param {string} lang to return.  If not specified, returns current language
         * @returns {object} the translation string maps for the language
         */
        get: function (lang) {
          var language = lang ? lang : service.getCurrentLang();
          return langCache.get(language);
        },

        /**
         * @ngdoc service
         * @name getSafeText
         * @methodOf ui.grid.i18n.service:i18nService
         * @description  returns the text specified in the path or a Missing text if text is not found
         * @param {String} path property path to use for retrieving text from string map
         * @param {String} [lang] to return.  If not specified, returns current language
         * @returns {object} the translation for the path
         * @example
         *

         * i18nService.getSafeText('sort.ascending')
         *

         */
        getSafeText: function (path, lang) {
          var language = lang || service.getCurrentLang();
          var trans = langCache.get(language);

          if (!trans) {
            return i18nConstants.MISSING;
          }

          var paths = path.split('.');
          var current = trans;

          for (var i = 0; i < paths.length; ++i) {
            if (current[paths[i]] === undefined || current[paths[i]] === null) {
              return i18nConstants.MISSING;
            } else {
              current = current[paths[i]];
            }
          }

          return current;

        },

        /**
         * @ngdoc service
         * @name setCurrentLang
         * @methodOf ui.grid.i18n.service:i18nService
         * @description sets the current language to use in the application
         * $broadcasts the i18nConstants.UPDATE_EVENT on the $rootScope
         * @param {string} lang to set
         * @example
         *

         * i18nService.setCurrentLang('fr');
         *

         */

        setCurrentLang: function (lang) {
          if (lang) {
            langCache.setCurrent(lang);
            $rootScope.$broadcast(i18nConstants.UPDATE_EVENT);
          }
        },

        /**
         * @ngdoc service
         * @name getCurrentLang
         * @methodOf ui.grid.i18n.service:i18nService
         * @description returns the current language used in the application
         */
        getCurrentLang: function () {
          var lang = langCache.getCurrentLang();
          if (!lang) {
            lang = i18nConstants.DEFAULT_LANG;
            langCache.setCurrent(lang);
          }
          return lang;
        }

      };

      return service;

    }]);

  var localeDirective = function (i18nService, i18nConstants) {
    return {
      compile: function () {
        return {
          pre: function ($scope, $elm, $attrs) {
            var alias = i18nConstants.LOCALE_DIRECTIVE_ALIAS;
            // check for watchable property
            var lang = $scope.$eval($attrs[alias]);
            if (lang) {
              $scope.$watch($attrs[alias], function () {
                i18nService.setCurrentLang(lang);
              });
            } else if ($attrs.$$observers) {
              $attrs.$observe(alias, function () {
                i18nService.setCurrentLang($attrs[alias] || i18nConstants.DEFAULT_LANG);
              });
            }
          }
        };
      }
    };
  };

  module.directive('uiI18n', ['i18nService', 'i18nConstants', localeDirective]);

  // directive syntax
  var uitDirective = function ($parse, i18nService, i18nConstants) {
    return {
      restrict: 'EA',
      compile: function () {
        return {
          pre: function ($scope, $elm, $attrs) {
            var alias1 = DIRECTIVE_ALIASES[0],
              alias2 = DIRECTIVE_ALIASES[1];
            var token = $attrs[alias1] || $attrs[alias2] || $elm.html();
            var missing = i18nConstants.MISSING + token;
            var observer;
            if ($attrs.$$observers) {
              var prop = $attrs[alias1] ? alias1 : alias2;
              observer = $attrs.$observe(prop, function (result) {
                if (result) {
                  $elm.html($parse(result)(i18nService.getCurrentLang()) || missing);
                }
              });
            }
            var getter = $parse(token);
            var listener = $scope.$on(i18nConstants.UPDATE_EVENT, function (evt) {
              if (observer) {
                observer($attrs[alias1] || $attrs[alias2]);
              } else {
                // set text based on i18n current language
                $elm.html(getter(i18nService.get()) || missing);
              }
            });
            $scope.$on('$destroy', listener);

            $elm.html(getter(i18nService.get()) || missing);
          }
        };
      }
    };
  };

  angular.forEach( DIRECTIVE_ALIASES, function ( alias ) {
    module.directive( alias, ['$parse', 'i18nService', 'i18nConstants', uitDirective] );
  } );

  // optional filter syntax
  var uitFilter = function ($parse, i18nService, i18nConstants) {
    return function (data) {
      var getter = $parse(data);
      // set text based on i18n current language
      return getter(i18nService.get()) || i18nConstants.MISSING + data;
    };
  };

  angular.forEach( FILTER_ALIASES, function ( alias ) {
    module.filter( alias, ['$parse', 'i18nService', 'i18nConstants', uitFilter] );
  } );

})();<commit_msg>feat(ui-i18n.js): Allow replacing/customizing specific existing locale strings when using add.<commit_after>/**
 * ui.i18n Created by Tim Sweet on 2/1/14.
 * https://github.com/timothyswt
 * MIT License
 */

/**
 * @ngdoc overview
 * @name ui.grid.i18n
 * @description
 *
 *  # ui.grid.i18n
 * This module provides i18n functions to ui.grid and any application that wants to use it

 *
 *

 */

(function () {
  var DIRECTIVE_ALIASES = ['uiT', 'uiTranslate'];
  var FILTER_ALIASES = ['t', 'uiTranslate'];

  var module = angular.module('ui.grid.i18n');

  /**
   *  @ngdoc object
   *  @name ui.grid.i18n.constant:i18nConstants
   *
   *  @description constants available in i18n module
   */
  module.constant('i18nConstants', {
    MISSING: '[MISSING]',
    UPDATE_EVENT: '$uiI18n',

    LOCALE_DIRECTIVE_ALIAS: 'uiI18n',
    // default to english
    DEFAULT_LANG: 'en'
  });

//    module.config(['$provide', function($provide) {
//        $provide.decorator('i18nService', ['$delegate', function($delegate) {}])}]);

  /**
   *  @ngdoc service
   *  @name ui.grid.i18n.service:i18nService
   *
   *  @description Services for i18n
   */
  module.service('i18nService', ['$log', 'i18nConstants', '$rootScope',
    function ($log, i18nConstants, $rootScope) {

      var langCache = {
        _langs: {},
        current: null,
        get: function (lang) {
          return this._langs[lang.toLowerCase()];
        },
        add: function (lang, strings) {
          var lower = lang.toLowerCase();
          if (!this._langs[lower]) {
            this._langs[lower] = {};
          }
          angular.merge(this._langs[lower], strings);
        },
        getAllLangs: function () {
          var langs = [];
          if (!this._langs) {
            return langs;
          }

          for (var key in this._langs) {
            langs.push(key);
          }

          return langs;
        },
        setCurrent: function (lang) {
          this.current = lang.toLowerCase();
        },
        getCurrentLang: function () {
          return this.current;
        }
      };

      var service = {

        /**
         * @ngdoc service
         * @name add
         * @methodOf ui.grid.i18n.service:i18nService
         * @description  Adds the languages and strings to the cache. Decorate this service to
         * add more translation strings
         * @param {string} lang language to add
         * @param {object} stringMaps of strings to add grouped by property names
         * @example
         *

         *      i18nService.add('en', {
         *         aggregate: {
         *                 label1: 'items',
         *                 label2: 'some more items'
         *                 }
         *         },
         *         groupPanel: {
         *              description: 'Drag a column header here and drop it to group by that column.'
         *           }
         *      }
         *

         */
        add: function (langs, stringMaps) {
          if (typeof(langs) === 'object') {
            angular.forEach(langs, function (lang) {
              if (lang) {
                langCache.add(lang, stringMaps);
              }
            });
          } else {
            langCache.add(langs, stringMaps);
          }
        },

        /**
         * @ngdoc service
         * @name getAllLangs
         * @methodOf ui.grid.i18n.service:i18nService
         * @description  return all currently loaded languages
         * @returns {array} string
         */
        getAllLangs: function () {
          return langCache.getAllLangs();
        },

        /**
         * @ngdoc service
         * @name get
         * @methodOf ui.grid.i18n.service:i18nService
         * @description  return all currently loaded languages
         * @param {string} lang to return.  If not specified, returns current language
         * @returns {object} the translation string maps for the language
         */
        get: function (lang) {
          var language = lang ? lang : service.getCurrentLang();
          return langCache.get(language);
        },

        /**
         * @ngdoc service
         * @name getSafeText
         * @methodOf ui.grid.i18n.service:i18nService
         * @description  returns the text specified in the path or a Missing text if text is not found
         * @param {String} path property path to use for retrieving text from string map
         * @param {String} [lang] to return.  If not specified, returns current language
         * @returns {object} the translation for the path
         * @example
         *

         * i18nService.getSafeText('sort.ascending')
         *

         */
        getSafeText: function (path, lang) {
          var language = lang || service.getCurrentLang();
          var trans = langCache.get(language);

          if (!trans) {
            return i18nConstants.MISSING;
          }

          var paths = path.split('.');
          var current = trans;

          for (var i = 0; i < paths.length; ++i) {
            if (current[paths[i]] === undefined || current[paths[i]] === null) {
              return i18nConstants.MISSING;
            } else {
              current = current[paths[i]];
            }
          }

          return current;

        },

        /**
         * @ngdoc service
         * @name setCurrentLang
         * @methodOf ui.grid.i18n.service:i18nService
         * @description sets the current language to use in the application
         * $broadcasts the i18nConstants.UPDATE_EVENT on the $rootScope
         * @param {string} lang to set
         * @example
         *

         * i18nService.setCurrentLang('fr');
         *

         */

        setCurrentLang: function (lang) {
          if (lang) {
            langCache.setCurrent(lang);
            $rootScope.$broadcast(i18nConstants.UPDATE_EVENT);
          }
        },

        /**
         * @ngdoc service
         * @name getCurrentLang
         * @methodOf ui.grid.i18n.service:i18nService
         * @description returns the current language used in the application
         */
        getCurrentLang: function () {
          var lang = langCache.getCurrentLang();
          if (!lang) {
            lang = i18nConstants.DEFAULT_LANG;
            langCache.setCurrent(lang);
          }
          return lang;
        }

      };

      return service;

    }]);

  var localeDirective = function (i18nService, i18nConstants) {
    return {
      compile: function () {
        return {
          pre: function ($scope, $elm, $attrs) {
            var alias = i18nConstants.LOCALE_DIRECTIVE_ALIAS;
            // check for watchable property
            var lang = $scope.$eval($attrs[alias]);
            if (lang) {
              $scope.$watch($attrs[alias], function () {
                i18nService.setCurrentLang(lang);
              });
            } else if ($attrs.$$observers) {
              $attrs.$observe(alias, function () {
                i18nService.setCurrentLang($attrs[alias] || i18nConstants.DEFAULT_LANG);
              });
            }
          }
        };
      }
    };
  };

  module.directive('uiI18n', ['i18nService', 'i18nConstants', localeDirective]);

  // directive syntax
  var uitDirective = function ($parse, i18nService, i18nConstants) {
    return {
      restrict: 'EA',
      compile: function () {
        return {
          pre: function ($scope, $elm, $attrs) {
            var alias1 = DIRECTIVE_ALIASES[0],
              alias2 = DIRECTIVE_ALIASES[1];
            var token = $attrs[alias1] || $attrs[alias2] || $elm.html();
            var missing = i18nConstants.MISSING + token;
            var observer;
            if ($attrs.$$observers) {
              var prop = $attrs[alias1] ? alias1 : alias2;
              observer = $attrs.$observe(prop, function (result) {
                if (result) {
                  $elm.html($parse(result)(i18nService.getCurrentLang()) || missing);
                }
              });
            }
            var getter = $parse(token);
            var listener = $scope.$on(i18nConstants.UPDATE_EVENT, function (evt) {
              if (observer) {
                observer($attrs[alias1] || $attrs[alias2]);
              } else {
                // set text based on i18n current language
                $elm.html(getter(i18nService.get()) || missing);
              }
            });
            $scope.$on('$destroy', listener);

            $elm.html(getter(i18nService.get()) || missing);
          }
        };
      }
    };
  };

  angular.forEach( DIRECTIVE_ALIASES, function ( alias ) {
    module.directive( alias, ['$parse', 'i18nService', 'i18nConstants', uitDirective] );
  } );

  // optional filter syntax
  var uitFilter = function ($parse, i18nService, i18nConstants) {
    return function (data) {
      var getter = $parse(data);
      // set text based on i18n current language
      return getter(i18nService.get()) || i18nConstants.MISSING + data;
    };
  };

  angular.forEach( FILTER_ALIASES, function ( alias ) {
    module.filter( alias, ['$parse', 'i18nService', 'i18nConstants', uitFilter] );
  } );

})();
<|endoftext|>


<commit_before>/* global qs qsa docReady toggleHidden prettyPrint tippy */

docReady(function () {
  /* single response display - header hover */

  qsa('span.hdr', function (element) {
    var headerName = element.getAttribute('data-name')
    var offset = element.getAttribute('data-offset')
    var tooltip = qs('span.tip', element)
    if (tooltip === null) {
      return
    }
    tippy(element, {
      content: tooltip,
      theme: 'redbot',
      delay: [10, 10],
      interactive: true,
      interactiveBorder: 5,
      placement: 'bottom-end',
      offset: [50, 5],
      maxWidth: 460,
      appendTo: document.body,
      onShow: function (tippyInstance) {
        element.classList.toggle('hilight')
        highlightHeaderRelated(headerName, offset, true)
      },
      onHidden: function (tippyInstance) {
        element.classList.toggle('hilight')
        highlightHeaderRelated(headerName, offset, false)
      }
    })
  })

  function highlightHeaderRelated (headerName, offset, direction) {
    qsa('li.note', function (element) {
      var noteInteresting = false
      var subjects = element.getAttribute('data-subject').split(' ')
      subjects.forEach(subject => {
        if (subject === `header-${headerName}`) {
          noteInteresting = true
        }
        if (subject === `offset-${offset}`) {
          noteInteresting = true
        }
      })
      if (!noteInteresting) {
        element.style.opacity = direction ? 0.3 : 1.0
      }
    })
  }

  /* single response display - note hover */

  qsa('li.note span', function (element) {
    var noteName = element.parentNode.getAttribute('data-name')
    var tooltip = qs('span.tip', element)
    if (tooltip === null) {
      return
    }
    tippy(element, {
      content: tooltip,
      theme: 'redbot',
      delay: [10, 10],
      interactive: true,
      interactiveBorder: 5,
      placement: 'bottom-end',
      offset: [50, 5],
      maxWidth: 460,
      appendTo: document.body,
      onShow: function (tippyInstance) {
        highlightNoteRelated(element, true)
      },
      onHidden: function (tippyInstance) {
        highlightNoteRelated(element, false)
      }
    })
  })

  function highlightNoteRelated (note, direction) {
    var noteSubjects = note.parentNode.getAttribute('data-subject').split(' ')
    noteSubjects.forEach(subject => {
      if (subject.indexOf('offset-') === 0) {
        qsa(`span.hdr[data-offset='${subject.slice(7)}']`, function (element) {
          element.classList.toggle('hilight')
        })
      } else if (subject.indexOf('header-') === 0) {
        qsa(`span.hdr[data-name='${subject.slice(7)}']`, function (element) {
          element.classList.toggle('hilight')
        })
      }
    })
  }

  /* single response display - response body */

  var bodyButton = qs('#body_view')
  var showingBody = false
  if (bodyButton !== null) {
    bodyButton.onclick = function () {
      toggleHidden(qs('#body'))
      toggleHidden(qs('#details'))
      if (!showingBody) {
        qs('#body_view').textContent = 'view notes'
        prettyPrint()
      } else {
        qs('#body_view').textContent = 'view body'
      }
      showingBody = !showingBody
    }
  }

  /* single response display - save */

  var saveButton = qs('#save')
  if (saveButton !== null) {
    saveButton.onclick = function () {
      qs('#save_form').submit()
    }
  }
})
<commit_msg>remove unused noteName<commit_after>/* global qs qsa docReady toggleHidden prettyPrint tippy */

docReady(function () {
  /* single response display - header hover */

  qsa('span.hdr', function (element) {
    var headerName = element.getAttribute('data-name')
    var offset = element.getAttribute('data-offset')
    var tooltip = qs('span.tip', element)
    if (tooltip === null) {
      return
    }
    tippy(element, {
      content: tooltip,
      theme: 'redbot',
      delay: [10, 10],
      interactive: true,
      interactiveBorder: 5,
      placement: 'bottom-end',
      offset: [50, 5],
      maxWidth: 460,
      appendTo: document.body,
      onShow: function (tippyInstance) {
        element.classList.toggle('hilight')
        highlightHeaderRelated(headerName, offset, true)
      },
      onHidden: function (tippyInstance) {
        element.classList.toggle('hilight')
        highlightHeaderRelated(headerName, offset, false)
      }
    })
  })

  function highlightHeaderRelated (headerName, offset, direction) {
    qsa('li.note', function (element) {
      var noteInteresting = false
      var subjects = element.getAttribute('data-subject').split(' ')
      subjects.forEach(subject => {
        if (subject === `header-${headerName}`) {
          noteInteresting = true
        }
        if (subject === `offset-${offset}`) {
          noteInteresting = true
        }
      })
      if (!noteInteresting) {
        element.style.opacity = direction ? 0.3 : 1.0
      }
    })
  }

  /* single response display - note hover */

  qsa('li.note span', function (element) {
    var tooltip = qs('span.tip', element)
    if (tooltip === null) {
      return
    }
    tippy(element, {
      content: tooltip,
      theme: 'redbot',
      delay: [10, 10],
      interactive: true,
      interactiveBorder: 5,
      placement: 'bottom-end',
      offset: [50, 5],
      maxWidth: 460,
      appendTo: document.body,
      onShow: function (tippyInstance) {
        highlightNoteRelated(element, true)
      },
      onHidden: function (tippyInstance) {
        highlightNoteRelated(element, false)
      }
    })
  })

  function highlightNoteRelated (note, direction) {
    var noteSubjects = note.parentNode.getAttribute('data-subject').split(' ')
    noteSubjects.forEach(subject => {
      if (subject.indexOf('offset-') === 0) {
        qsa(`span.hdr[data-offset='${subject.slice(7)}']`, function (element) {
          element.classList.toggle('hilight')
        })
      } else if (subject.indexOf('header-') === 0) {
        qsa(`span.hdr[data-name='${subject.slice(7)}']`, function (element) {
          element.classList.toggle('hilight')
        })
      }
    })
  }

  /* single response display - response body */

  var bodyButton = qs('#body_view')
  var showingBody = false
  if (bodyButton !== null) {
    bodyButton.onclick = function () {
      toggleHidden(qs('#body'))
      toggleHidden(qs('#details'))
      if (!showingBody) {
        qs('#body_view').textContent = 'view notes'
        prettyPrint()
      } else {
        qs('#body_view').textContent = 'view body'
      }
      showingBody = !showingBody
    }
  }

  /* single response display - save */

  var saveButton = qs('#save')
  if (saveButton !== null) {
    saveButton.onclick = function () {
      qs('#save_form').submit()
    }
  }
})
<|endoftext|>


<commit_before>'use strict';

var $ = require('jquery');
var EventEmitter = require('events').EventEmitter;
var klass = require('klass');
var path = require('path');
var Hogan = require('hogan');
var Dao = require('../util/dao.js');
var UrlBuilder = require('../util/url-builder.js');
var Promise = require('bluebird');

module.exports = klass(EventEmitter).extend({
    currentFile: null,
    page: null,
    lastPage: null,
    $currentElement: null,
    initialize: function (selector) {
        this.currentFile = null;
        this.$root = $(selector);
        this.$preload = this.$root.find('.preload');
        this.$currentFileList = this.$root.find('.current-file-list');
        this.$currentFileTitle = this.$root.find('.current-file-title')
        this.initializeTemplates();
        this.bindEvents();
    },
    bindEvents: function () {
        var self = this;
        this.$root.on('click', 'a', function (e) {
            self.emit('click');
        });

        this.$preload.on('click', function (e) {
            e.preventDefault();
            self.preloadThumbs();
        });
    },
    setCurrentFile: function (filename) {
        this.currentFile = filename;
        this.$currentFileTitle.text(path.basename(filename));
    },
    loadPage: function (filename, page) {
        var self = this;
        if (this.currentFile != filename) {
            this.displayLoading();
            Dao.getComicPages(filename, function (err, path, pages) {
                if (err) return self.displayError(err);
                self.setCurrentFile(filename);
                self.updatePages(path, pages);
                self.selectPage(page);
                self.emit('update', self.lastPage, page);
            });
        } else {
            this.selectPage(page);
            this.emit('update', this.lastPage, page);
        }
    },
    displayLoading: function () {
        this.$currentFileTitle.html(this.pageLoadingTemplate.render());
        this.$currentFileList.empty();
    },
    displayError: function (err) {
        // TODO
        this.$currentFileTitle.html(err.message);
    },
    updatePages: function (path, pages) {
        var self = this;
        this.lastPage = pages.length;
        this.$currentFileList.empty();
        this.$currentFileList.scrollTop(0);
        pages.forEach(function (page, index) {
            var data = $.extend({}, page, {index: index + 1, path: path});
            data.fileOffset = ''+data.fileOffset;
            self.$currentFileList.append(self.pageRowTemplate.render(data));
        });
    },
    selectPage: function (page) {
        if (this.$currentElement) {
            this.$currentElement.removeClass('active');
        }
        this.page = +page;
        var $pageElement = this.$currentFileList.find('li').eq(page - 1);
        $pageElement.addClass('active');
        var filename = $pageElement.attr('data-filename');
        this.$currentElement = $pageElement;
        this.loadThumb($pageElement);
        this.emit('page', {path: this.currentFile, filename: filename});
    },
    preloadThumbs: function () {
        var self = this;
        var currentFile = this.curentFile;
        var promise = new Promise(function (resolve, reject) {
            resolve();
        });
        this.$currentFileList.find('li').each(function (index, element) {
            var $element = $(element);
            promise = promise.then(function () {
                if (self.currentFile != currentFile) {
                    return Promise.reject();
                }
                return self.loadThumb($element);
            });
        });
        return promise;
    },
    loadThumb: function ($pageElement) {
        var self = this;
        var $thumb = $pageElement.find('.page-thumb');
        var thumb = $thumb.find('img')[0];
        return new Promise(function (resolve, reject) {
            if ($thumb.hasClass('no-src')) {
                var filename = $pageElement.attr('data-filename');
                thumb.src = UrlBuilder.getImageFilenameUrl(self.currentFile, filename);
                thumb.onload = function () {
                    $thumb.removeClass('no-src');
                    thumb.onerror = null;
                    resolve();
                }
                thumb.onerror = function () {
                    // TODO: handle image errors
                    thumb.onload = null;
                    reject();
                }
            } else {
                resolve();
            }
        });
    },
    nextPage: function () {
        if (this.currentFile && this.page <= this.lastPage - 1) {
            window.location.hash = '#!' + this.currentFile + '::' + (this.page + 1);
        }
    },
    previousPage: function () {
        if (this.currentFile && this.page > 1) {
            window.location.hash = '#!' + this.currentFile + '::' + (this.page - 1);
        }
    },
    initializeTemplates: function () {
        this.pageRowTemplate = Hogan.compile($('#cz-template-page-row').html());
        this.pageLoadingTemplate = Hogan.compile($('#cz-template-page-loading').html());
    }
});
<commit_msg>End preloading when file changes<commit_after>'use strict';

var $ = require('jquery');
var EventEmitter = require('events').EventEmitter;
var klass = require('klass');
var path = require('path');
var Hogan = require('hogan');
var Dao = require('../util/dao.js');
var UrlBuilder = require('../util/url-builder.js');
var Promise = require('bluebird');

module.exports = klass(EventEmitter).extend({
    currentFile: null,
    page: null,
    lastPage: null,
    $currentElement: null,
    initialize: function (selector) {
        this.currentFile = null;
        this.$root = $(selector);
        this.$preload = this.$root.find('.preload');
        this.$currentFileList = this.$root.find('.current-file-list');
        this.$currentFileTitle = this.$root.find('.current-file-title')
        this.initializeTemplates();
        this.bindEvents();
    },
    bindEvents: function () {
        var self = this;
        this.$root.on('click', 'a', function (e) {
            self.emit('click');
        });

        this.$preload.on('click', function (e) {
            e.preventDefault();
            self.preloadThumbs();
        });
    },
    setCurrentFile: function (filename) {
        this.currentFile = filename;
        this.$currentFileTitle.text(path.basename(filename));
    },
    loadPage: function (filename, page) {
        var self = this;
        if (this.currentFile != filename) {
            this.displayLoading();
            Dao.getComicPages(filename, function (err, path, pages) {
                if (err) return self.displayError(err);
                self.setCurrentFile(filename);
                self.updatePages(path, pages);
                self.selectPage(page);
                self.emit('update', self.lastPage, page);
            });
        } else {
            this.selectPage(page);
            this.emit('update', this.lastPage, page);
        }
    },
    displayLoading: function () {
        this.$currentFileTitle.html(this.pageLoadingTemplate.render());
        this.$currentFileList.empty();
    },
    displayError: function (err) {
        // TODO
        this.$currentFileTitle.html(err.message);
    },
    updatePages: function (path, pages) {
        var self = this;
        this.lastPage = pages.length;
        this.$currentFileList.empty();
        this.$currentFileList.scrollTop(0);
        pages.forEach(function (page, index) {
            var data = $.extend({}, page, {index: index + 1, path: path});
            data.fileOffset = ''+data.fileOffset;
            self.$currentFileList.append(self.pageRowTemplate.render(data));
        });
    },
    selectPage: function (page) {
        if (this.$currentElement) {
            this.$currentElement.removeClass('active');
        }
        this.page = +page;
        var $pageElement = this.$currentFileList.find('li').eq(page - 1);
        $pageElement.addClass('active');
        var filename = $pageElement.attr('data-filename');
        this.$currentElement = $pageElement;
        this.loadThumb($pageElement);
        this.emit('page', {path: this.currentFile, filename: filename});
    },
    preloadThumbs: function () {
        var self = this;
        var currentFile = this.curentFile;
        var promise = Promise.resolve();
        this.$currentFileList.find('li').each(function (index, element) {
            var $element = $(element);
            promise = promise.then(function () {
                if (self.currentFile != currentFile) {
                    return Promise.reject();
                }
                return self.loadThumb($element);
            });
        });
        return promise;
    },
    loadThumb: function ($pageElement) {
        var self = this;
        var $thumb = $pageElement.find('.page-thumb');
        var thumb = $thumb.find('img')[0];
        return new Promise(function (resolve, reject) {
            if ($thumb.hasClass('no-src')) {
                var filename = $pageElement.attr('data-filename');
                thumb.src = UrlBuilder.getImageFilenameUrl(self.currentFile, filename);
                thumb.onload = function () {
                    $thumb.removeClass('no-src');
                    thumb.onerror = null;
                    resolve();
                }
                thumb.onerror = function () {
                    // TODO: handle image errors
                    thumb.onload = null;
                    reject();
                }
            } else {
                resolve();
            }
        });
    },
    nextPage: function () {
        if (this.currentFile && this.page <= this.lastPage - 1) {
            window.location.hash = '#!' + this.currentFile + '::' + (this.page + 1);
        }
    },
    previousPage: function () {
        if (this.currentFile && this.page > 1) {
            window.location.hash = '#!' + this.currentFile + '::' + (this.page - 1);
        }
    },
    initializeTemplates: function () {
        this.pageRowTemplate = Hogan.compile($('#cz-template-page-row').html());
        this.pageLoadingTemplate = Hogan.compile($('#cz-template-page-loading').html());
    }
});
<|endoftext|>


<commit_before>// placeholder for all deprecated classes,
// and corresponding alias for backward compatibility

/**
 * @function me.device.getPixelRatio
 * @deprecated since 5.1.0
 * @see me.device.devicePixelRatio
 */
me.device.getPixelRatio = function() {
    console.log("me.device.getPixelRatio() is deprecated, please use me.device.devicePixelRatio");
    return me.device.devicePixelRatio;
};

/**
 * @class me.Font
 * @deprecated since 6.1.0
 * @see me.Text
 */
me.Font = me.Text.extend({
    /** @ignore */
    init: function (font, size, fillStyle, textAlign) {
        var settings = {
            font:font,
            size:size,
            fillStyle:fillStyle,
            textAlign:textAlign
        };
        // super constructor
        this._super(me.Text, "init", [0, 0, settings]);
        // deprecation warning
        console.log("me.Font is deprecated, please use me.Text");
    },

    /** @ignore */
    setFont : function (font, size, fillStyle, textAlign) {
        // apply fillstyle if defined
        if (typeof(fillStyle) !== "undefined") {
            this.fillStyle.copy(fillStyle);
        }
        // h alignement if defined
        if (typeof(textAlign) !== "undefined") {
            this.textAlign = textAlign;
        }
        // super constructor
        return this._super(me.Text, "setFont", [font, size]);
    }
});

/**
 * @ignore
 */
me.BitmapFontData = me.BitmapTextData;

/**
 * @class me.BitmapFont
 * @deprecated since 6.1.0
 * @see me.BitmapText
 */
me.BitmapFont = me.BitmapText.extend({
    /** @ignore */
    init: function (data, fontImage, scale, textAlign, textBaseline) {
        var settings = {
            font: fontImage,
            fontData: data,
            size: scale,
            textAlign: textAlign,
            textBaseline: textBaseline
        };
        // super constructor
        this._super(me.BitmapText, "init", [0, 0, settings]);
        // deprecation warning
        console.log("me.BitmapFont is deprecated, please use me.BitmapText");
    }
});

/**
 * @class me.ScreenObject
 * @deprecated since 6.2.0
 * @see me.Stage
 */
me.ScreenObject = me.Stage.extend({
    /** @ignore */
    init: function (settings) {
        // super constructor
        this._super(me.Stage, "init", settings);
        // deprecation warning
        console.log("me.ScreenObject is deprecated, please use me.Stage");
    }
});

/**
 * @function me.Renderer.drawShape
 * @deprecated since 6.3.0
 * @see me.Renderer.stroke
 */
me.Renderer.prototype.drawShape = function () {
    console.log("drawShape() is deprecated, please use the stroke() or fill() function");
    me.Renderer.prototype.stroke.apply(this, arguments);
};

/**
 * @ignore
 */
me.CanvasRenderer.prototype.Texture = me.Renderer.prototype.Texture;

/**
 * @ignore
 */
me.WebGLRenderer.prototype.Texture = me.Renderer.prototype.Texture;

 /**
  * @function me.video.getPos
  * @deprecated since 7.0.0
  * @see me.device.getElementBounds
  */
me.video.getPos = function() {
    console.log("me.video.getPos() is deprecated, please use me.device.getElementBounds(me.video.renderer.getScreenCanvas());");
    return me.device.getElementBounds(me.video.renderer.getScreenCanvas());
};

/**
 * melonJS base class for exception handling.
 * @class
 * @extends me.Object
 * @memberOf me
 * @constructor
 * @deprecated since 7.0.0
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
 * @param {String} msg Error message.
 */
me.Error = me.Object.extend.bind(Error)({
    /**
     * @ignore
     */
    init : function (msg) {
        this.name = "me.Error";
        this.message = msg;
    }
});

/**
 * @function me.sys.checkVersion
 * @deprecated since 7.1.0
 * @see me.utils.checkVersion
 */
me.sys.checkVersion = function(first, second) {
    console.log("me.sys.checkVersion() is deprecated, please use me.utils.checkVersion()");
    return me.utils.checkVersion(first, second);
};

/**
 * @public
 * @type {Object}
 * @name HASH
 * @memberOf me.game
 * @deprecated since 7.1.0
 * @see me.utils.getUriFragment
 */
Object.defineProperty(me.game, "HASH", {
    /**
     * @ignore
     */
    get : function () {
        console.log("me.game.HASH is deprecated, please use me.utils.getUriFragment()");
        return me.utils.getUriFragment();
    },
    configurable : false
});

/**
 * @function me.video.updateDisplaySize
 * @deprecated since 7.1.0
 * @see me.video.scale
 */
me.video.updateDisplaySize = function(x, y) {
    console.log("me.video.updateDisplaySize() is deprecated, please use me.video.scale()");
    return me.video.scale(x, y);
};

/**
 * @function me.Renderer.scaleCanvas
 * @deprecated since 7.1.0
 * @see me.video.scale
 */
me.Renderer.prototype.scaleCanvas = function (x, y) {
    console.log("scaleCanvas() is deprecated, please use me.video.scale()");
    return me.video.scale(x, y);
};

/**
 * @function me.Entity.distanceToPoint
 * @deprecated since 7.1.0
 * @see me.Renderable.distanceTo
*/
me.Entity.prototype.distanceToPoint = function (v) {
    console.log("distanceToPoint() is deprecated, please use me.Renderable.distanceTo()");
    return this.distanceTo(v);
};

/**
 * @function me.Entity.angleToPoint
 * @deprecated since 7.1.0
 * @see me.Renderable.angleTo
*/
me.Entity.prototype.angleToPoint = function (v) {
    console.log("angleToPoint() is deprecated, please use me.Renderable.angleTo()");
    return this.angleTo(v);
};

/**
 * @public
 * @type {Number}
 * @name gravity
 * @memberOf me.sys
 * @deprecated since 8.0.0
 * @see me.World.gravity
 */
Object.defineProperty(me.sys, "gravity", {
    /**
     * @ignore
     */
    get : function () {
        console.log("me.sys.gravity is deprecated, please use me.game.world.gravity");
        return me.game.world ? me.game.world.gravity.y : undefined;
    },

    /**
     * @ignore
     */
    set : function (value) {
        console.log("me.sys.gravity is deprecated, please use me.game.world.gravity");
        if (me.game.world) me.game.world.gravity.y = value;
    },
    configurable : false
});

/**
 * @ignore
 */
me.WebGLRenderer.Compositor = me.WebGLCompositor;

/**
 * Draw triangle(s)
 * @name drawTriangle
 * @deprecated since 8.0.0
 * @see me.WebGLRenderer.Compositor
 * @memberOf me.WebGLRenderer.Compositor.drawVertices
 * @function
 * @param {me.Vector2d[]} points vertices
 * @param {Number} [len=points.length] amount of points defined in the points array
 * @param {Boolean} [strip=false] Whether the array defines a serie of connected triangles, sharing vertices
 */
me.WebGLRenderer.Compositor.prototype.drawTriangle = function (points, len, strip) {
    var gl = this.gl;
    this.drawVertices(strip === true ? gl.TRIANGLE_STRIP : gl.TRIANGLES, points, len);
    console.log("drawTriangle is deprecated, please use drawVertices");
};

/**
 * Draw a line
 * @name drawLine
 * @deprecated since 8.0.0
 * @memberOf me.WebGLRenderer.Compositor.drawVertices
 * @memberOf me.WebGLRenderer.Compositor
 * @function
 * @param {me.Vector2d[]} points Line vertices
 * @param {Number} [len=points.length] amount of points defined in the points array
 * @param {Boolean} [open=false] Whether the line is open (true) or closed (false)
 */
me.WebGLRenderer.Compositor.prototype.drawLine = function (points, len, open) {
    var gl = this.gl;
    this.drawVertices(open === true ? gl.LINE_STRIP : gl.LINE_LOOP, points, len);
    console.log("drawLine is deprecated, please use drawVertices");
};

/**
 * @public
 * @type {me.Vector2d}
 * @name scale
 * @memberOf me.sys
 * @deprecated since 8.0.0
 * @see me.video.scaleRatio
 */
Object.defineProperty(me.sys, "scale", {
    /**
     * @ignore
     */
    get : function () {
        console.log("me.sys.scale is deprecated, please use me.video.scaleRatio");
        return me.video.scaleRatio;
    },
    configurable : false
});

/**
 * @function me.video.getWrapper
 * @deprecated since 8.0.0
 * @see me.video.getParent
 */
me.video.getWrapper = function() {
    console.log("me.video.getWrapper()is deprecated, please use me.device.getParent();");
    return me.video.getParent();
};
<commit_msg>change all console deprecation message into proper console warnning<commit_after>// placeholder for all deprecated classes,
// and corresponding alias for backward compatibility

/**
 * @function me.device.getPixelRatio
 * @deprecated since 5.1.0
 * @see me.device.devicePixelRatio
 */
me.device.getPixelRatio = function() {
    console.warn("me.device.getPixelRatio() is deprecated, please use me.device.devicePixelRatio");
    return me.device.devicePixelRatio;
};

/**
 * @class me.Font
 * @deprecated since 6.1.0
 * @see me.Text
 */
me.Font = me.Text.extend({
    /** @ignore */
    init: function (font, size, fillStyle, textAlign) {
        var settings = {
            font:font,
            size:size,
            fillStyle:fillStyle,
            textAlign:textAlign
        };
        // super constructor
        this._super(me.Text, "init", [0, 0, settings]);
        // deprecation warning
        console.warn("me.Font is deprecated, please use me.Text");
    },

    /** @ignore */
    setFont : function (font, size, fillStyle, textAlign) {
        // apply fillstyle if defined
        if (typeof(fillStyle) !== "undefined") {
            this.fillStyle.copy(fillStyle);
        }
        // h alignement if defined
        if (typeof(textAlign) !== "undefined") {
            this.textAlign = textAlign;
        }
        // super constructor
        return this._super(me.Text, "setFont", [font, size]);
    }
});

/**
 * @ignore
 */
me.BitmapFontData = me.BitmapTextData;

/**
 * @class me.BitmapFont
 * @deprecated since 6.1.0
 * @see me.BitmapText
 */
me.BitmapFont = me.BitmapText.extend({
    /** @ignore */
    init: function (data, fontImage, scale, textAlign, textBaseline) {
        var settings = {
            font: fontImage,
            fontData: data,
            size: scale,
            textAlign: textAlign,
            textBaseline: textBaseline
        };
        // super constructor
        this._super(me.BitmapText, "init", [0, 0, settings]);
        // deprecation warning
        console.warn("me.BitmapFont is deprecated, please use me.BitmapText");
    }
});

/**
 * @class me.ScreenObject
 * @deprecated since 6.2.0
 * @see me.Stage
 */
me.ScreenObject = me.Stage.extend({
    /** @ignore */
    init: function (settings) {
        // super constructor
        this._super(me.Stage, "init", settings);
        // deprecation warning
        console.warn("me.ScreenObject is deprecated, please use me.Stage");
    }
});

/**
 * @function me.Renderer.drawShape
 * @deprecated since 6.3.0
 * @see me.Renderer.stroke
 */
me.Renderer.prototype.drawShape = function () {
    console.warn("drawShape() is deprecated, please use the stroke() or fill() function");
    me.Renderer.prototype.stroke.apply(this, arguments);
};

/**
 * @ignore
 */
me.CanvasRenderer.prototype.Texture = me.Renderer.prototype.Texture;

/**
 * @ignore
 */
me.WebGLRenderer.prototype.Texture = me.Renderer.prototype.Texture;

 /**
  * @function me.video.getPos
  * @deprecated since 7.0.0
  * @see me.device.getElementBounds
  */
me.video.getPos = function() {
    console.warn("me.video.getPos() is deprecated, please use me.device.getElementBounds(me.video.renderer.getScreenCanvas());");
    return me.device.getElementBounds(me.video.renderer.getScreenCanvas());
};

/**
 * melonJS base class for exception handling.
 * @class
 * @extends me.Object
 * @memberOf me
 * @constructor
 * @deprecated since 7.0.0
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
 * @param {String} msg Error message.
 */
me.Error = me.Object.extend.bind(Error)({
    /**
     * @ignore
     */
    init : function (msg) {
        this.name = "me.Error";
        this.message = msg;
    }
});

/**
 * @function me.sys.checkVersion
 * @deprecated since 7.1.0
 * @see me.utils.checkVersion
 */
me.sys.checkVersion = function(first, second) {
    console.warn("me.sys.checkVersion() is deprecated, please use me.utils.checkVersion()");
    return me.utils.checkVersion(first, second);
};

/**
 * @public
 * @type {Object}
 * @name HASH
 * @memberOf me.game
 * @deprecated since 7.1.0
 * @see me.utils.getUriFragment
 */
Object.defineProperty(me.game, "HASH", {
    /**
     * @ignore
     */
    get : function () {
        console.warn("me.game.HASH is deprecated, please use me.utils.getUriFragment()");
        return me.utils.getUriFragment();
    },
    configurable : false
});

/**
 * @function me.video.updateDisplaySize
 * @deprecated since 7.1.0
 * @see me.video.scale
 */
me.video.updateDisplaySize = function(x, y) {
    console.warn("me.video.updateDisplaySize() is deprecated, please use me.video.scale()");
    return me.video.scale(x, y);
};

/**
 * @function me.Renderer.scaleCanvas
 * @deprecated since 7.1.0
 * @see me.video.scale
 */
me.Renderer.prototype.scaleCanvas = function (x, y) {
    console.warn("scaleCanvas() is deprecated, please use me.video.scale()");
    return me.video.scale(x, y);
};

/**
 * @function me.Entity.distanceToPoint
 * @deprecated since 7.1.0
 * @see me.Renderable.distanceTo
*/
me.Entity.prototype.distanceToPoint = function (v) {
    console.warn("distanceToPoint() is deprecated, please use me.Renderable.distanceTo()");
    return this.distanceTo(v);
};

/**
 * @function me.Entity.angleToPoint
 * @deprecated since 7.1.0
 * @see me.Renderable.angleTo
*/
me.Entity.prototype.angleToPoint = function (v) {
    console.warn("angleToPoint() is deprecated, please use me.Renderable.angleTo()");
    return this.angleTo(v);
};

/**
 * @public
 * @type {Number}
 * @name gravity
 * @memberOf me.sys
 * @deprecated since 8.0.0
 * @see me.World.gravity
 */
Object.defineProperty(me.sys, "gravity", {
    /**
     * @ignore
     */
    get : function () {
        console.warn("me.sys.gravity is deprecated, please use me.game.world.gravity");
        return me.game.world ? me.game.world.gravity.y : undefined;
    },

    /**
     * @ignore
     */
    set : function (value) {
        console.warn("me.sys.gravity is deprecated, please use me.game.world.gravity");
        if (me.game.world) me.game.world.gravity.y = value;
    },
    configurable : false
});

/**
 * @ignore
 */
me.WebGLRenderer.Compositor = me.WebGLCompositor;

/**
 * Draw triangle(s)
 * @name drawTriangle
 * @deprecated since 8.0.0
 * @see me.WebGLRenderer.Compositor
 * @memberOf me.WebGLRenderer.Compositor.drawVertices
 * @function
 * @param {me.Vector2d[]} points vertices
 * @param {Number} [len=points.length] amount of points defined in the points array
 * @param {Boolean} [strip=false] Whether the array defines a serie of connected triangles, sharing vertices
 */
me.WebGLRenderer.Compositor.prototype.drawTriangle = function (points, len, strip) {
    var gl = this.gl;
    this.drawVertices(strip === true ? gl.TRIANGLE_STRIP : gl.TRIANGLES, points, len);
    console.warn("drawTriangle is deprecated, please use drawVertices");
};

/**
 * Draw a line
 * @name drawLine
 * @deprecated since 8.0.0
 * @memberOf me.WebGLRenderer.Compositor.drawVertices
 * @memberOf me.WebGLRenderer.Compositor
 * @function
 * @param {me.Vector2d[]} points Line vertices
 * @param {Number} [len=points.length] amount of points defined in the points array
 * @param {Boolean} [open=false] Whether the line is open (true) or closed (false)
 */
me.WebGLRenderer.Compositor.prototype.drawLine = function (points, len, open) {
    var gl = this.gl;
    this.drawVertices(open === true ? gl.LINE_STRIP : gl.LINE_LOOP, points, len);
    console.warn("drawLine is deprecated, please use drawVertices");
};

/**
 * @public
 * @type {me.Vector2d}
 * @name scale
 * @memberOf me.sys
 * @deprecated since 8.0.0
 * @see me.video.scaleRatio
 */
Object.defineProperty(me.sys, "scale", {
    /**
     * @ignore
     */
    get : function () {
        console.warn("me.sys.scale is deprecated, please use me.video.scaleRatio");
        return me.video.scaleRatio;
    },
    configurable : false
});

/**
 * @function me.video.getWrapper
 * @deprecated since 8.0.0
 * @see me.video.getParent
 */
me.video.getWrapper = function() {
    console.warn("me.video.getWrapper()is deprecated, please use me.device.getParent();");
    return me.video.getParent();
};
<|endoftext|>


<commit_before>var slice = require('../array/sliced')

function isEmpty () {
  var args = slice(arguments)
  return args.every(function (val) {
    return !val.length
  })
}

module.exports = isEmpty
<commit_msg>update lang/isArrEmpty<commit_after>var slice = require('../array/slice')

function isEmpty () {
  var args = slice(arguments)
  return args.every(function (val) {
    return !val.length
  })
}

module.exports = isEmpty
<|endoftext|>


<commit_before>/// Custom Utilities

export function isUndefined (value) {
  return typeof(value) === 'undefined';
}

export function isNull (value) {
  return value === null;
}

export function randomInt (max) {
  if (isUndefined(max)) {
    throw new MissingParameter('Max value not set.');
  }
  return Math.floor(Math.random() * max);
}<commit_msg>Bugfix: Make sure to import the MissingParameter exception into utils before using it<commit_after>/// Custom Utilities
import { MissingParameter } from 'exceptions';

export function isUndefined (value) {
  return typeof(value) === 'undefined';
}

export function isNull (value) {
  return value === null;
}

export function randomInt (max) {
  if (isUndefined(max)) {
    throw new MissingParameter('Max value not set.');
  }
  return Math.floor(Math.random() * max);
}<|endoftext|>


<commit_before>var _ = exports
var toStr = Object.prototype.toString
var slice = Array.prototype.slice
var hasOwn = Object.prototype.hasOwnProperty
var isArrayNative = Array.isArray

exports.now = function () {
  return new Date().getTime()
}

exports.isFn = function (obj) {
  return typeof obj === 'function'
}

exports.isObj = function (o) {
  return o && toStr.call(o) === '[object Object]'
}

exports.isArr = function (o) {
  return o && isArrayNative ? isArrayNative(o) : toStr.call(o) === '[object Array]'
}

exports.toArr = function (args) {
  return slice.call(args)
}

exports.defer = function (fn) {
  setTimeout(fn, 1)
}

exports.each = function (obj, fn) {
  var i, l
  if (_.isArr(obj))
    for (i = 0, l = obj.length; i < l; i += 1) fn(obj[i], i)
  else if (_.isObj(obj))
    for (i in obj) if (hasOwn.call(obj, i)) fn(obj[i], i)
}

exports.extend = function (target) {
  var args = _.toArr(arguments).slice(1)
  _.each(args, function (obj) {
    if (_.isObj(obj)) {
      _.each(obj, function (value, key) {
        target[key] = value
      })
    }
  })
  return target
}

exports.getSource = function (fn) {
  return '(' + fn.toString() + ').call(this)'
}

exports.fnName = function (fn) {
  return fn.name || (fn = /\W*function\s+([\w\$]+)\(/.exec(fn.toString()) ? fn[1] : '')
}

exports.serializeMap = function (obj) {
  if (_.isObj(obj)) {
    _.each(obj, function (fn, key) {
      if (_.isFn(fn)) {
        obj['$$fn$$' + key] = fn.toString()
        obj[key] = undefined
      }
    })
  }
  return obj
}

exports.uuid = function () {
  var uuid = '', i, random
  for (i = 0; i < 32; i++) {
    random = Math.random() * 16 | 0;
    if (i === 8 || i === 12 || i === 16 || i === 20) uuid += '-'
    uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)).toString(16)
  }
  return uuid
}
<commit_msg>refactor(utils): use lodash shortcut to exports<commit_after>var _ = exports
var toStr = Object.prototype.toString
var slice = Array.prototype.slice
var hasOwn = Object.prototype.hasOwnProperty
var isArrayNative = Array.isArray

_.now = function () {
  return new Date().getTime()
}

_.isFn = function (obj) {
  return typeof obj === 'function'
}

_.isObj = function (o) {
  return o && toStr.call(o) === '[object Object]'
}

_.isArr = function (o) {
  return o && isArrayNative ? isArrayNative(o) : toStr.call(o) === '[object Array]'
}

_.toArr = function (args) {
  return slice.call(args)
}

_.defer = function (fn) {
  setTimeout(fn, 1)
}

_.each = function (obj, fn) {
  var i, l
  if (_.isArr(obj))
    for (i = 0, l = obj.length; i < l; i += 1) fn(obj[i], i)
  else if (_.isObj(obj))
    for (i in obj) if (hasOwn.call(obj, i)) fn(obj[i], i)
}

_.extend = function (target) {
  var args = _.toArr(arguments).slice(1)
  _.each(args, function (obj) {
    if (_.isObj(obj)) {
      _.each(obj, function (value, key) {
        target[key] = value
      })
    }
  })
  return target
}

_.getSource = function (fn) {
  return '(' + fn.toString() + ').call(this)'
}

_.fnName = function (fn) {
  return fn.name || (fn = /\W*function\s+([\w\$]+)\(/.exec(fn.toString()) ? fn[1] : '')
}

_.serializeMap = function (obj) {
  if (_.isObj(obj)) {
    _.each(obj, function (fn, key) {
      if (_.isFn(fn)) {
        obj['$$fn$$' + key] = fn.toString()
        obj[key] = undefined
      }
    })
  }
  return obj
}

_.uuid = function () {
  var uuid = '', i, random
  for (i = 0; i < 32; i++) {
    random = Math.random() * 16 | 0;
    if (i === 8 || i === 12 || i === 16 || i === 20) uuid += '-'
    uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)).toString(16)
  }
  return uuid
}
<|endoftext|>