<commit_before>'use strict';

angular.module('<%=angularAppName%>')
    .factory('Principal', function Principal($q, Account<% if (websocket == 'spring-websocket') { %>, Tracker<% } %>) {
        var _identity,
            _authenticated = false;

        return {
            isIdentityResolved: function () {
                return angular.isDefined(_identity);
            },
            isAuthenticated: function () {
                return _authenticated;
            },
            isInRole: function (role) {
                if (!_authenticated || !_identity || !_identity.roles) {
                    return false;
                }

                return _identity.roles.indexOf(role) !== -1;
            },
            isInAnyRole: function (roles) {
                if (!_authenticated || !_identity.roles) {
                    return false;
                }

                for (var i = 0; i < roles.length; i++) {
                    if (this.isInRole(roles[i])) {
                        return true;
                    }
                }

                return false;
            },
            authenticate: function (identity) {
                _identity = identity;
                _authenticated = identity !== null;
            },
            identity: function (force) {
                var deferred = $q.defer();

                if (force === true) {
                    _identity = undefined;
                }

                // check and see if we have retrieved the identity data from the server.
                // if we have, reuse it by immediately resolving
                if (angular.isDefined(_identity)) {
                    deferred.resolve(_identity);

                    return deferred.promise;
                }

                // retrieve the identity data from the server, update the identity object, and then resolve.
                Account.get().$promise
                    .then(function (account) {
                        _identity = account.data;
                        _authenticated = true;
                        deferred.resolve(_identity);<% if (websocket == 'spring-websocket') { %>
                        Tracker.connect();<% } %>
                    })
                    .catch(function() {
                        _identity = null;
                        _authenticated = false;
                        deferred.resolve(_identity);
                    });
                return deferred.promise;
            }
        };
    });
<commit_msg>Add "_identity check" to Principal.isInAyRole<commit_after>'use strict';

angular.module('<%=angularAppName%>')
    .factory('Principal', function Principal($q, Account<% if (websocket == 'spring-websocket') { %>, Tracker<% } %>) {
        var _identity,
            _authenticated = false;

        return {
            isIdentityResolved: function () {
                return angular.isDefined(_identity);
            },
            isAuthenticated: function () {
                return _authenticated;
            },
            isInRole: function (role) {
                if (!_authenticated || !_identity || !_identity.roles) {
                    return false;
                }

                return _identity.roles.indexOf(role) !== -1;
            },
            isInAnyRole: function (roles) {
                if (!_authenticated || !_identity || !_identity.roles) {
                    return false;
                }

                for (var i = 0; i < roles.length; i++) {
                    if (this.isInRole(roles[i])) {
                        return true;
                    }
                }

                return false;
            },
            authenticate: function (identity) {
                _identity = identity;
                _authenticated = identity !== null;
            },
            identity: function (force) {
                var deferred = $q.defer();

                if (force === true) {
                    _identity = undefined;
                }

                // check and see if we have retrieved the identity data from the server.
                // if we have, reuse it by immediately resolving
                if (angular.isDefined(_identity)) {
                    deferred.resolve(_identity);

                    return deferred.promise;
                }

                // retrieve the identity data from the server, update the identity object, and then resolve.
                Account.get().$promise
                    .then(function (account) {
                        _identity = account.data;
                        _authenticated = true;
                        deferred.resolve(_identity);<% if (websocket == 'spring-websocket') { %>
                        Tracker.connect();<% } %>
                    })
                    .catch(function() {
                        _identity = null;
                        _authenticated = false;
                        deferred.resolve(_identity);
                    });
                return deferred.promise;
            }
        };
    });
<|endoftext|>


<commit_before>// Logger variable. Set to true to turn on logging.
var LOG = true;
// Initialization status variable. Helps elimiate duplicate buttons.
var pinitInitInitialized = false;

(function() {
  try {
    // In case of insite navigation, document.ready will work.
    $(document).ready(function(){
      LOG && console.debug("DOM is ready. Time to start up Pin It.");
      visioplanetPinItInit();
    });
    $(window).load(function() {
      LOG && console.debug("Window load is complete. Time to start up Pin It.");
      visioplanetPinItInit();
    });
  } catch(e) {
    console.error('Visioplanet Fotomoto plugin Exception: ' + e);
    windowLoadMethod();
  }
})();

function windowLoadMethod() {
  try {
    // If this is a direct post load, document.ready may not work and we will have to use window.load
    $(window).load(function() {
      visioplanetPinItInit();
    });
  } catch(e) {
    console.error('Visioplanet Fotomoto plugin Exception: ' + e);
  }
}

function visioplanetPinItInit(){
  setTimeout (
    function() {
      if (document.readyState !== 'complete') {
        LOG && console.debug("Document's not ready. Waiting...");
        setTimeout(visioplanetPinItInit,1000);
      } else {
        // We're gonna wait for sometime and then do our work (URL remains the old one otherwise).
	    LOG && console.debug("Let's begin PinIt Initialization...");
        // We're gonna put the button on top of the image at the top right corner of it.
        // For that, we'd have to check the width of the image.

        // The following line will make sure that PinIt button initialization runs only once.
        // So that multiple PinIt buttons don't show up.
        if(pinitInitInitialized == true) {
          LOG && console.debug("PinIt initialization already started. Exiting visioplanetPinItInit() to avoid duplicates.")
          return;
        }

        pinitInitInitialized = true;
        var imgURL = "";
        var img = new Image();

        $("img").each(
          function(){
            img.src = $(this).attr('src');
            var theWidth = img.width;
            var theHeight = img.height;

            LOG && console.debug($(this).attr("src") + ": " + theWidth + "x" + theHeight);
            if((theWidth >= 400) || (theHeight >= 400)) {
              imgURL = $(this).attr("src");
              LOG && console.debug("Got the image URL: " + imgURL);
              return false;
              LOG && console.debug("This line shouldn't come up.");
            }
        });

        var htmlStr = "";

        LOG && console.debug("The tag's as follows:\n\n" + htmlStr);

        $(htmlStr).insertAfter("span.share-facebook.delay");
        // We're placing this button right after the +1 button.
        $("a.visioplanetPinItButton").css("z-index", 1000);
      }
    }
  , 2000);
}
<commit_msg>Update VisioplanetPinItByImgSizeInShareSection.js<commit_after>// Logger variable. Set to true to turn on logging.
var LOG = true;
// Initialization status variable. Helps elimiate duplicate buttons.
var pinitInitInitialized = false;

(function() {
  try {
    // In case of insite navigation, document.ready will work.
    $(document).ready(function(){
      LOG && console.debug("DOM is ready. Time to start up Pin It.");
      visioplanetPinItInit();
    });
    $(window).load(function() {
      LOG && console.debug("Window load is complete. Time to start up Pin It.");
      visioplanetPinItInit();
    });
  } catch(e) {
    console.error('Visioplanet Fotomoto plugin Exception: ' + e);
    windowLoadMethod();
  }
})();

function windowLoadMethod() {
  try {
    // If this is a direct post load, document.ready may not work and we will have to use window.load
    $(window).load(function() {
      visioplanetPinItInit();
    });
  } catch(e) {
    console.error('Visioplanet Fotomoto plugin Exception: ' + e);
  }
}

function visioplanetPinItInit(){
  setTimeout (
    function() {
      if (document.readyState !== 'complete') {
        LOG && console.debug("Document's not ready. Waiting...");
        setTimeout(visioplanetPinItInit,1000);
      } else {
        // The following line will make sure that PinIt button initialization runs only once.
        // So that multiple PinIt buttons don't show up.
        if(pinitInitInitialized == true) {
          LOG && console.debug("PinIt initialization already started. Exiting visioplanetPinItInit() to avoid duplicates.")
          return;
        }

        // We're gonna wait for sometime and then do our work (URL remains the old one otherwise).
	    LOG && console.debug("Let's begin PinIt Initialization...");
        // We're gonna put the button on top of the image at the top right corner of it.
        // For that, we'd have to check the width of the image.

        pinitInitInitialized = true;
        var imgURL = "";
        var img = new Image();

        $("img").each(
          function(){
            img.src = $(this).attr('src');
            var theWidth = img.width;
            var theHeight = img.height;

            LOG && console.debug($(this).attr("src") + ": " + theWidth + "x" + theHeight);
            if((theWidth >= 400) || (theHeight >= 400)) {
              imgURL = $(this).attr("src");
              LOG && console.debug("Got the image URL: " + imgURL);
              return false;
              LOG && console.debug("This line shouldn't come up.");
            }
        });

        var htmlStr = "";

        LOG && console.debug("The tag's as follows:\n\n" + htmlStr);

        $(htmlStr).insertAfter("span.share-facebook.delay");
        // We're placing this button right after the +1 button.
        $("a.visioplanetPinItButton").css("z-index", 1000);
      }
    }
  , 2000);
}
<|endoftext|>


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

/**
 * Create Variant Report Chart Panel
 */
Ext.define( 'ASPIREdb.view.report.VariantReportPanel', {
   extend : 'Ext.Panel',
   alias : 'widget.variantReportPanel',
   id : 'variantReport',
   xtype : 'clustered-column',
   resizable : true,
   layout : 'fit',

   initComponent : function() {
      this.callParent();
   },

   /**
    * Return the value where the bin is found
    */
   findBin : function(val, BINS, BINS_TEXT) {
      for (var i = 0; i < BINS.length; i++) {
         if ( (BINS[i] - val) >= 0 ) {
//            console.log( val + " is in bin " + BINS_TEXT[i] );
            return BINS_TEXT[i];
         }
      }

      // it must be the last bin
//      console.log( val + " is in bin " + BINS_TEXT[BINS_TEXT.length - 1] );
      return BINS_TEXT[BINS_TEXT.length - 1];
   },

   /**
    * Returns the textual representation of the bins for the chart axis, e.g. <100000, 20000-30000
    */
   bins2text : function(BINS) {
      var BINS_TEXT = [];
      for (var i = 0; i < BINS.length; i++) {
         var bin = "";
         if ( i == 0 ) {
            bin = "<=" + BINS[i];
         } else if ( i == BINS.length - 1 ) {
            bin = (BINS[i - 1] + 1) + "-" + BINS[i];
            BINS_TEXT.push( bin );
            bin = ">=" + ( BINS[i] + 1 );
         } else {
            bin = (BINS[i - 1] + 1) + "-" + BINS[i];
         }
         BINS_TEXT.push( bin );
      }
      return BINS_TEXT;
   },

   /**
    * Use for numerical data types, bin the data first and plot the frequencies
    *
    */
   calculateBinFrequencies : function(store, columnName, countColumnName) {

      var map = new Ext.util.HashMap();
      var fields = [ columnName, countColumnName ];

      // setup bins
      var BINS = Array.apply( 0, Array( 20 ) ).map( function(val, i) {
         return 10000 * (i + 1);
      } );
      var BINS_TEXT = this.bins2text( BINS );

      // initialize map with all the bins
      for (var i = 0; i < BINS_TEXT.length; i++) {
         map.add( BINS_TEXT[i], 0 );
      }

      for (var i = 0; i < store.data.length; i++) {

         // extract values
         var row = store.data.getAt( i ).data;
         var val = row[columnName];
         if ( val == undefined ) {
            console.log( "Column '" + columnName + "' not found" );
            return;
         }

         // bin the value
         var bin = this.findBin( val, BINS, BINS_TEXT );

         // now lets calculate and store it!
         var count = map.get( bin );
         count++;
         map.add( bin, count );
      }

      // a collection of freq objects
      var data = [];
      map.each( function(key, value, length) {
         // console.log( key, value, length );
         var freq = {}
         freq[columnName] = key;
         freq[countColumnName] = value;
         data.push( freq );
      } );

      // convert to Extjs Store
      var newStore = Ext.create( 'Ext.data.JsonStore', {
         storeId : 'reportStore',
         fields : fields,
         data : data,
      } );

      return newStore;
   },

   /**
    * @param store
    *           Array of Variant objects,
    *
    * e.g. [ Object{"id":"var1", "type":"LOSS" }, Object{"id":"var2", "type":"LOSS" }, ]
    *
    * @param columnName
    *           input column to extract, e.g. 'type'
    * @param countColumnName
    *           output column name to store the frequency in, e.g. 'count'
    * @returns e.g. { "type" : "LOSS", "count" : 2 }
    */
   calculateFrequencies : function(store, columnName, countColumnName) {
      var map = new Ext.util.HashMap();
      var fields = [ columnName, countColumnName ];

      for (var i = 0; i < store.data.length; i++) {

         // extract values
         var row = store.data.getAt( i ).data;
         var val = row[columnName];
         if ( val == undefined ) {
            console.log( "Column '" + columnName + "' not found" );
            return;
         }

         // now lets calculate and store it!
         if ( map.get( val ) == undefined ) {
            map.add( val, 1 );
         } else {
            var count = map.get( val );
            count++;
            map.add( val, count );
         }
      }

      // a collection of freq objects
      var data = [];
      map.each( function(key, value, length) {
         // console.log(key, value, length);
         var freq = {}
         freq[columnName] = key;
         freq[countColumnName] = value;
         data.push( freq );
      } );

      // convert to Extjs Store
      var newStore = Ext.create( 'Ext.data.JsonStore', {
         storeId : 'reportStore',
         fields : fields,
         data : data,
      } );

      return newStore;
   },

   createReport : function(store, columnName) {

      var me = this;

      // var columnName = 'type';
      var countColumnName = 'count';
      var title = ASPIREdb.ActiveProjectSettings.getActiveProjectName();
      var xField = columnName;
      var yField = countColumnName;

      // columns that needs binning
      var COLUMN_TYPE_BIN = [ "cnvLength" ];
      var myDataStore = null;
      if ( COLUMN_TYPE_BIN.indexOf( columnName ) != -1 ) {
         myDataStore = this.calculateBinFrequencies( store, columnName, countColumnName );
      } else {
         myDataStore = this.calculateFrequencies( store, columnName, countColumnName );
      }

      me.add( [ {
         xtype : 'chart',
         id : 'variantChart',
         width : '100%',
         // height : 410,
         padding : '10 0 0 0',
         animate : true,
         resizable : true,
         shadow : false,
         layout : 'fit',
         style : 'background: #fff;',
         // legend : {
         // position : 'bottom',
         // boxStrokeWidth : 0,
         // labelFont : '12px Helvetica'
         // },
         store : myDataStore,
         insetPadding : 40,
         items : [ {
            type : 'text',
            text : title,
            font : '20px Helvetica',
            width : 100,
            height : 30,
            x : 40, // the sprite x position
            y : 12
         // the sprite y position
         }, {
            type : 'text',
            text : 'ASPIREdb',
            font : '10px Helvetica',
            x : 12,
            y : 380
         } ],
         axes : [ {
            type : 'numeric',
            position : 'left',
            fields : yField,
            grid : true,
            minimum : 0,
            title : countColumnName,
            label : {
               renderer : function(v) {
                  // return v + '%';
                  return v;
               }
            }
         }, {
            type : 'category',
            position : 'bottom',
            fields : xField,
            title : columnName,
            grid : true,
            label : {
               rotate : {
                  degrees : -45
               }
            }
         } ],
         series : [ {
            type : 'column',
            axis : 'left',
            xField : xField,
            yField : yField,
            style : {
               opacity : 0.80
            },
            highlight : {
               fill : '#000',
               'stroke-width' : 1,
               stroke : '#000'
            },
            tips : {
               trackMouse : true,
               width : 150,
               style : 'background: #FFF',
               renderer : function(storeItem, item) {
                  var msg = storeItem.get( xField ) + ': ' + storeItem.get( item.yField );
                  this.update( msg );
               }
            }
         } ]
      } ] );

      me.doLayout();
      me.show();

   },

} );
<commit_msg>Disabled glitchy plot panel resizing. Resize using the parent window instead.<commit_after>/*
 * The aspiredb project
 *
 * Copyright (c) 2013 University of British Columbia
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
Ext.require( [] );

/**
 * Create Variant Report Chart Panel
 */
Ext.define( 'ASPIREdb.view.report.VariantReportPanel', {
   extend : 'Ext.Panel',
   alias : 'widget.variantReportPanel',
   id : 'variantReport',
   xtype : 'clustered-column',
   layout : 'fit',

   initComponent : function() {
      this.callParent();
   },

   /**
    * Return the value where the bin is found
    */
   findBin : function(val, BINS, BINS_TEXT) {
      for (var i = 0; i < BINS.length; i++) {
         if ( (BINS[i] - val) >= 0 ) {
//            console.log( val + " is in bin " + BINS_TEXT[i] );
            return BINS_TEXT[i];
         }
      }

      // it must be the last bin
//      console.log( val + " is in bin " + BINS_TEXT[BINS_TEXT.length - 1] );
      return BINS_TEXT[BINS_TEXT.length - 1];
   },

   /**
    * Returns the textual representation of the bins for the chart axis, e.g. <100000, 20000-30000
    */
   bins2text : function(BINS) {
      var BINS_TEXT = [];
      for (var i = 0; i < BINS.length; i++) {
         var bin = "";
         if ( i == 0 ) {
            bin = "<=" + BINS[i];
         } else if ( i == BINS.length - 1 ) {
            bin = (BINS[i - 1] + 1) + "-" + BINS[i];
            BINS_TEXT.push( bin );
            bin = ">=" + ( BINS[i] + 1 );
         } else {
            bin = (BINS[i - 1] + 1) + "-" + BINS[i];
         }
         BINS_TEXT.push( bin );
      }
      return BINS_TEXT;
   },

   /**
    * Use for numerical data types, bin the data first and plot the frequencies
    *
    */
   calculateBinFrequencies : function(store, columnName, countColumnName) {

      var map = new Ext.util.HashMap();
      var fields = [ columnName, countColumnName ];

      // setup bins
      var BINS = Array.apply( 0, Array( 20 ) ).map( function(val, i) {
         return 10000 * (i + 1);
      } );
      var BINS_TEXT = this.bins2text( BINS );

      // initialize map with all the bins
      for (var i = 0; i < BINS_TEXT.length; i++) {
         map.add( BINS_TEXT[i], 0 );
      }

      for (var i = 0; i < store.data.length; i++) {

         // extract values
         var row = store.data.getAt( i ).data;
         var val = row[columnName];
         if ( val == undefined ) {
            console.log( "Column '" + columnName + "' not found" );
            return;
         }

         // bin the value
         var bin = this.findBin( val, BINS, BINS_TEXT );

         // now lets calculate and store it!
         var count = map.get( bin );
         count++;
         map.add( bin, count );
      }

      // a collection of freq objects
      var data = [];
      map.each( function(key, value, length) {
         // console.log( key, value, length );
         var freq = {}
         freq[columnName] = key;
         freq[countColumnName] = value;
         data.push( freq );
      } );

      // convert to Extjs Store
      var newStore = Ext.create( 'Ext.data.JsonStore', {
         storeId : 'reportStore',
         fields : fields,
         data : data,
      } );

      return newStore;
   },

   /**
    * @param store
    *           Array of Variant objects,
    *
    * e.g. [ Object{"id":"var1", "type":"LOSS" }, Object{"id":"var2", "type":"LOSS" }, ]
    *
    * @param columnName
    *           input column to extract, e.g. 'type'
    * @param countColumnName
    *           output column name to store the frequency in, e.g. 'count'
    * @returns e.g. { "type" : "LOSS", "count" : 2 }
    */
   calculateFrequencies : function(store, columnName, countColumnName) {
      var map = new Ext.util.HashMap();
      var fields = [ columnName, countColumnName ];

      for (var i = 0; i < store.data.length; i++) {

         // extract values
         var row = store.data.getAt( i ).data;
         var val = row[columnName];
         if ( val == undefined ) {
            console.log( "Column '" + columnName + "' not found" );
            return;
         }

         // now lets calculate and store it!
         if ( map.get( val ) == undefined ) {
            map.add( val, 1 );
         } else {
            var count = map.get( val );
            count++;
            map.add( val, count );
         }
      }

      // a collection of freq objects
      var data = [];
      map.each( function(key, value, length) {
         // console.log(key, value, length);
         var freq = {}
         freq[columnName] = key;
         freq[countColumnName] = value;
         data.push( freq );
      } );

      // convert to Extjs Store
      var newStore = Ext.create( 'Ext.data.JsonStore', {
         storeId : 'reportStore',
         fields : fields,
         data : data,
      } );

      return newStore;
   },

   createReport : function(store, columnName) {

      var me = this;

      // var columnName = 'type';
      var countColumnName = 'count';
      var title = ASPIREdb.ActiveProjectSettings.getActiveProjectName();
      var xField = columnName;
      var yField = countColumnName;

      // columns that needs binning
      var COLUMN_TYPE_BIN = [ "cnvLength" ];
      var myDataStore = null;
      if ( COLUMN_TYPE_BIN.indexOf( columnName ) != -1 ) {
         myDataStore = this.calculateBinFrequencies( store, columnName, countColumnName );
      } else {
         myDataStore = this.calculateFrequencies( store, columnName, countColumnName );
      }

      me.add( [ {
         xtype : 'chart',
         id : 'variantChart',
         width : '100%',
         // height : 410,
         padding : '10 0 0 0',
         animate : true,
         shadow : false,
         layout : 'fit',
         style : 'background: #fff;',
         // legend : {
         // position : 'bottom',
         // boxStrokeWidth : 0,
         // labelFont : '12px Helvetica'
         // },
         store : myDataStore,
         insetPadding : 40,
         items : [ {
            type : 'text',
            text : title,
            font : '20px Helvetica',
            width : 100,
            height : 30,
            x : 40, // the sprite x position
            y : 12
         // the sprite y position
         }, {
            type : 'text',
            text : 'ASPIREdb',
            font : '10px Helvetica',
            x : 12,
            y : 380
         } ],
         axes : [ {
            type : 'numeric',
            position : 'left',
            fields : yField,
            grid : true,
            minimum : 0,
            title : countColumnName,
            label : {
               renderer : function(v) {
                  // return v + '%';
                  return v;
               }
            }
         }, {
            type : 'category',
            position : 'bottom',
            fields : xField,
            title : columnName,
            grid : true,
            label : {
               rotate : {
                  degrees : -45
               }
            }
         } ],
         series : [ {
            type : 'column',
            axis : 'left',
            xField : xField,
            yField : yField,
            style : {
               opacity : 0.80
            },
            highlight : {
               fill : '#000',
               'stroke-width' : 1,
               stroke : '#000'
            },
            tips : {
               trackMouse : true,
               width : 150,
               style : 'background: #FFF',
               renderer : function(storeItem, item) {
                  var msg = storeItem.get( xField ) + ': ' + storeItem.get( item.yField );
                  this.update( msg );
               }
            }
         } ]
      } ] );

      me.doLayout();
      me.show();

   },

} );
<|endoftext|>


<commit_before>define(['effects/SlideEffect'], function (SlideEffect) {

    /**
     * Private common push method.
     *
     * @param fromViewRef - reference to from view
     * @param toViewRef - reference to to view
     * @param transition - transition to played during push
     */
    var push = function (fromViewRef, toViewRef, transition) {

        // Hiding view
        toViewRef.instance.$el.data('original-display', toViewRef.instance.$el.css('display'));
        toViewRef.instance.$el.css('display', 'none');

        // Adding view to the DOM
        this.$el.append(toViewRef.instance.$el);

        // Rendering view if required
        if (!toViewRef.instance.rendered) {
            toViewRef.instance.render.call(toViewRef.instance);
            toViewRef.instance.rendered = true;
        }
        // Adding view to the stack internal array
        this.viewsStack.push(toViewRef);

        transition = transition || this.defaultPushTransition || (this.defaultPushTransition = new SlideEffect({direction:'left'}));
        transition.play(fromViewRef ? fromViewRef.instance.$el : null, toViewRef.instance.$el,
            function () {

                this.activeView = toViewRef.instance;
                toViewRef.instance.$el.trigger('viewActivate');

                if (fromViewRef) {
                    fromViewRef.instance.$el.trigger('viewDeactivate');

                    if (fromViewRef.instance.destructionPolicy == 'never') {
                        fromViewRef.instance.$el.detach();
                    } else {
                        fromViewRef.instance.remove();
                        fromViewRef.instance = null;
                    }
                }

                this.trigger('viewChanged');
            }, this);
    };

    /**
     * Private common pop method.
     *
     * @param fromViewRef - reference to from view
     * @param toViewRef - reference to to view
     * @param transition - transition to played during pop
     */
    var pop = function (fromViewRef, toViewRef, transition) {

        // Removing top view ref from the stack array
        this.viewsStack.pop();

        if (toViewRef) {

            if (!toViewRef.instance) {
                // Getting view class declaration
                var viewClass = toViewRef.viewClass;
                // Creating view instance
                toViewRef.instance = new viewClass(toViewRef.options);
                // Setting ref to StackNavigator
                toViewRef.instance.setStackNavigator(this, toViewRef.options ? toViewRef.options.navigationOptions : null);
            }

            // Hiding view
            toViewRef.instance.$el.data('original-display', toViewRef.instance.$el.css('display'));
            toViewRef.instance.$el.css('display', 'none');

            // Adding view to the DOM
            this.$el.append(toViewRef.instance.$el);
            // Rendering view if required
            if (!toViewRef.instance.rendered) {
                toViewRef.instance.render.call(toViewRef.instance);
                toViewRef.instance.rendered = true;
            }

        }

        transition = transition || this.defaultPopTransition || (this.defaultPopTransition = new SlideEffect({direction:'right'}));
        transition.play(fromViewRef.instance.$el, toViewRef ? toViewRef.instance.$el : null,
            function () {

                if (toViewRef) {
                    this.activeView = toViewRef.instance;
                    toViewRef.instance.$el.trigger('viewActivate');
                } else {
                    this.activeView = null;
                }

                fromViewRef.instance.$el.trigger('viewDeactivate');
                fromViewRef.instance.remove();
                fromViewRef.instance = null;

                this.trigger('viewChanged');
            }, this);
    };

    var StackNavigator = Backbone.View.extend({

        viewsStack:null,

        activeView:null,

        defaultPushTransition:null,

        defaultPopTransition:null,

        events:{
            'viewActivate':'proxyActivationEvents',
            'viewDeactivate':'proxyActivationEvents'
        },

        proxyActivationEvents:function (event) {
            this.trigger(event.type, event);
        },

        initialize:function (options) {
            // Setting default styles
            this.$el.css({overflow:'hidden'});

            // Setting new viewsStack array
            this.viewsStack = [];
        },

        pushView:function (view, viewOptions, transition) {
            var toView, toViewRef,
                isViewInstance = (typeof view !== 'function'),
                fromViewRef = _.last(this.viewsStack);

            toView = (!isViewInstance) ? new view(viewOptions) : view;
            toView.setStackNavigator(this, (viewOptions) ? viewOptions.navigationOptions : null);
            toViewRef = {instance:toView, viewClass:toView.constructor, options:viewOptions};

            var event = $.Event('viewChanging',
                {
                    action:'push',
                    fromViewClass:fromViewRef ? fromViewRef.viewClass : null,
                    fromView:fromViewRef ? fromViewRef.instance : null,
                    toViewClass:toViewRef.viewClass,
                    toView:toViewRef.instance
                });
            this.trigger(event.type, event);

            if (!event.isDefaultPrevented()) {

                push.call(this, fromViewRef, toViewRef, transition);

                return toView;
            }

            return null;
        },

        popView:function (transition) {
            var toViewRef, fromViewRef;
            if (this.viewsStack.length > 0)
                fromViewRef = this.viewsStack[this.viewsStack.length - 1];

            if (this.viewsStack.length > 1)
                toViewRef = this.viewsStack[this.viewsStack.length - 2];

            var event = $.Event('viewChanging',
                {
                    action:'pop',
                    fromViewClass:fromViewRef ? fromViewRef.viewClass : null,
                    fromView:fromViewRef ? fromViewRef.instance : null,
                    toViewClass:toViewRef ? toViewRef.viewClass : null,
                    toView:toViewRef ? toViewRef.instance : null
                });
            this.trigger(event.type, event);

            if (!event.isDefaultPrevented()) {

                var fromView = fromViewRef.instance;
                pop.call(this, fromViewRef, toViewRef, transition);

                return fromView;
            }

            return null;
        },

        popAll:function (transition) {
            if (this.viewsStack.length > 0) {

                var fromViewRef;
                if (this.viewsStack.length > 0)
                    fromViewRef = this.viewsStack[this.viewsStack.length - 1];

                var event = $.Event('viewChanging',
                    {
                        action:'popAll',
                        fromViewClass:fromViewRef ? fromViewRef.viewClass : null,
                        fromView:fromViewRef ? fromViewRef.instance : null,
                        toViewClass:null,
                        toView:null
                    });
                this.trigger(event.type, event);

                if (!event.isDefaultPrevented()) {
                    // Removing views except the top one
                    this.viewsStack.splice(0, this.viewsStack.length - 1);
                    pop.call(this, fromViewRef, null, transition);
                }
            }
            return null;
        },

        replaceView:function (view, viewOptions, transition) {
            if (this.viewsStack.length > 0) {

                var toView, toViewRef,
                    isViewInstance = (typeof view !== 'function'),
                    fromViewRef = this.viewsStack[this.viewsStack.length - 1];

                toView = (!isViewInstance) ? new view(viewOptions) : view;
                toView.setStackNavigator(this, (viewOptions) ? viewOptions.navigationOptions : null);
                toViewRef = {instance:toView, viewClass:toView.constructor, options:viewOptions};

                var event = $.Event('viewChanging',
                    {
                        action:'replace',
                        fromViewClass:fromViewRef.viewClass,
                        fromView:fromViewRef.instance,
                        toViewClass:toViewRef.viewClass,
                        toView:toViewRef.instance
                    });
                this.trigger(event.type, event);

                if (!event.isDefaultPrevented()) {

                    this.viewsStack.pop();
                    push.call(this, fromViewRef, toViewRef, transition);

                    return toView;
                }
            }
            return null;
        }
    });

    return StackNavigator;
});<commit_msg>- added replaceAll function<commit_after>define(['effects/SlideEffect'], function (SlideEffect) {

    /**
     * Private common push method.
     *
     * @param fromViewRef - reference to from view
     * @param toViewRef - reference to to view
     * @param transition - transition to played during push
     */
    var push = function (fromViewRef, toViewRef, transition) {

        // Hiding view
        toViewRef.instance.$el.data('original-display', toViewRef.instance.$el.css('display'));
        toViewRef.instance.$el.css('display', 'none');

        // Adding view to the DOM
        this.$el.append(toViewRef.instance.$el);

        // Rendering view if required
        if (!toViewRef.instance.rendered) {
            toViewRef.instance.render.call(toViewRef.instance);
            toViewRef.instance.rendered = true;
        }
        // Adding view to the stack internal array
        this.viewsStack.push(toViewRef);

        transition = transition || this.defaultPushTransition || (this.defaultPushTransition = new SlideEffect({direction:'left'}));
        transition.play(fromViewRef ? fromViewRef.instance.$el : null, toViewRef.instance.$el,
            function () {

                this.activeView = toViewRef.instance;
                toViewRef.instance.$el.trigger('viewActivate');

                if (fromViewRef) {
                    fromViewRef.instance.$el.trigger('viewDeactivate');

                    if (fromViewRef.instance.destructionPolicy == 'never') {
                        fromViewRef.instance.$el.detach();
                    } else {
                        fromViewRef.instance.remove();
                        fromViewRef.instance = null;
                    }
                }

                this.trigger('viewChanged');
            }, this);
    };

    /**
     * Private common pop method.
     *
     * @param fromViewRef - reference to from view
     * @param toViewRef - reference to to view
     * @param transition - transition to played during pop
     */
    var pop = function (fromViewRef, toViewRef, transition) {

        // Removing top view ref from the stack array
        this.viewsStack.pop();

        if (toViewRef) {

            if (!toViewRef.instance) {
                // Getting view class declaration
                var viewClass = toViewRef.viewClass;
                // Creating view instance
                toViewRef.instance = new viewClass(toViewRef.options);
                // Setting ref to StackNavigator
                toViewRef.instance.setStackNavigator(this, toViewRef.options ? toViewRef.options.navigationOptions : null);
            }

            // Hiding view
            toViewRef.instance.$el.data('original-display', toViewRef.instance.$el.css('display'));
            toViewRef.instance.$el.css('display', 'none');

            // Adding view to the DOM
            this.$el.append(toViewRef.instance.$el);
            // Rendering view if required
            if (!toViewRef.instance.rendered) {
                toViewRef.instance.render.call(toViewRef.instance);
                toViewRef.instance.rendered = true;
            }

        }

        transition = transition || this.defaultPopTransition || (this.defaultPopTransition = new SlideEffect({direction:'right'}));
        transition.play(fromViewRef.instance.$el, toViewRef ? toViewRef.instance.$el : null,
            function () {

                if (toViewRef) {
                    this.activeView = toViewRef.instance;
                    toViewRef.instance.$el.trigger('viewActivate');
                } else {
                    this.activeView = null;
                }

                fromViewRef.instance.$el.trigger('viewDeactivate');
                fromViewRef.instance.remove();
                fromViewRef.instance = null;

                this.trigger('viewChanged');
            }, this);
    };

    var StackNavigator = Backbone.View.extend({

        viewsStack:null,

        activeView:null,

        defaultPushTransition:null,

        defaultPopTransition:null,

        events:{
            'viewActivate':'proxyActivationEvents',
            'viewDeactivate':'proxyActivationEvents'
        },

        proxyActivationEvents:function (event) {
            this.trigger(event.type, event);
        },

        initialize:function (options) {
            // Setting default styles
            this.$el.css({overflow:'hidden'});

            // Setting new viewsStack array
            this.viewsStack = [];
        },

        pushView:function (view, viewOptions, transition) {
            var toView, toViewRef,
                isViewInstance = (typeof view !== 'function'),
                fromViewRef = _.last(this.viewsStack);

            toView = (!isViewInstance) ? new view(viewOptions) : view;
            toView.setStackNavigator(this, (viewOptions) ? viewOptions.navigationOptions : null);
            toViewRef = {instance:toView, viewClass:toView.constructor, options:viewOptions};

            var event = $.Event('viewChanging',
                {
                    action:'push',
                    fromViewClass:fromViewRef ? fromViewRef.viewClass : null,
                    fromView:fromViewRef ? fromViewRef.instance : null,
                    toViewClass:toViewRef.viewClass,
                    toView:toViewRef.instance
                });
            this.trigger(event.type, event);

            if (!event.isDefaultPrevented()) {

                push.call(this, fromViewRef, toViewRef, transition);

                return toView;
            }

            return null;
        },

        popView:function (transition) {
            var toViewRef, fromViewRef;
            if (this.viewsStack.length > 0)
                fromViewRef = this.viewsStack[this.viewsStack.length - 1];

            if (this.viewsStack.length > 1)
                toViewRef = this.viewsStack[this.viewsStack.length - 2];

            var event = $.Event('viewChanging',
                {
                    action:'pop',
                    fromViewClass:fromViewRef ? fromViewRef.viewClass : null,
                    fromView:fromViewRef ? fromViewRef.instance : null,
                    toViewClass:toViewRef ? toViewRef.viewClass : null,
                    toView:toViewRef ? toViewRef.instance : null
                });
            this.trigger(event.type, event);

            if (!event.isDefaultPrevented()) {

                var fromView = fromViewRef.instance;
                pop.call(this, fromViewRef, toViewRef, transition);

                return fromView;
            }

            return null;
        },

        popAll:function (transition) {
            if (this.viewsStack.length > 0) {

                var fromViewRef;
                if (this.viewsStack.length > 0)
                    fromViewRef = this.viewsStack[this.viewsStack.length - 1];

                var event = $.Event('viewChanging',
                    {
                        action:'popAll',
                        fromViewClass:fromViewRef ? fromViewRef.viewClass : null,
                        fromView:fromViewRef ? fromViewRef.instance : null,
                        toViewClass:null,
                        toView:null
                    });
                this.trigger(event.type, event);

                if (!event.isDefaultPrevented()) {
                    // Removing views except the top one
                    this.viewsStack.splice(0, this.viewsStack.length - 1);
                    pop.call(this, fromViewRef, null, transition);
                }
            }
            return null;
        },

        replaceView:function (view, viewOptions, transition) {
            if (this.viewsStack.length > 0) {

                var toView, toViewRef,
                    isViewInstance = (typeof view !== 'function'),
                    fromViewRef = this.viewsStack[this.viewsStack.length - 1];

                toView = (!isViewInstance) ? new view(viewOptions) : view;
                toView.setStackNavigator(this, (viewOptions) ? viewOptions.navigationOptions : null);
                toViewRef = {instance:toView, viewClass:toView.constructor, options:viewOptions};

                var event = $.Event('viewChanging',
                    {
                        action:'replace',
                        fromViewClass:fromViewRef.viewClass,
                        fromView:fromViewRef.instance,
                        toViewClass:toViewRef.viewClass,
                        toView:toViewRef.instance
                    });
                this.trigger(event.type, event);

                if (!event.isDefaultPrevented()) {

                    this.viewsStack.pop();
                    push.call(this, fromViewRef, toViewRef, transition);

                    return toView;
                }
            }
            return null;
        },

        replaceAll:function (view, viewOptions, transition) {
            if (this.viewsStack.length > 0) {

                var toView, toViewRef,
                    isViewInstance = (typeof view !== 'function'),
                    fromViewRef = this.viewsStack[this.viewsStack.length - 1];

                toView = (!isViewInstance) ? new view(viewOptions) : view;
                toView.setStackNavigator(this, (viewOptions) ? viewOptions.navigationOptions : null);
                toViewRef = {instance:toView, viewClass:toView.constructor, options:viewOptions};

                var event = $.Event('viewChanging',
                    {
                        action:'replaceAll',
                        fromViewClass:fromViewRef.viewClass,
                        fromView:fromViewRef.instance,
                        toViewClass:toViewRef.viewClass,
                        toView:toViewRef.instance
                    });
                this.trigger(event.type, event);

                if (!event.isDefaultPrevented()) {

                    this.viewsStack.splice(0, this.viewsStack.length);
                    push.call(this, fromViewRef, toViewRef, transition);

                    return toView;
                }
            }
            return null;
        }
    });

    return StackNavigator;
});<|endoftext|>


<commit_before>var inherits = require('util').inherits;

// var Property = require('gremlin-core/src/structure/Property');
// var GraphKey = require('gremlin-core/src/structure/Graph.Key');

function TinkerProperty(element, key, value) {
  this.element = element;
  this.key = key;
  this.value = value;
  this.graph = this.element.graph;
}

// inherits(TinkerProperty, Property);

TinkerProperty.prototype.getElement = function() {
  return this.element;
};

TinkerProperty.prototype.getKey = function() {
  // return GraphKey.unHide(this.key);
};

TinkerProperty.prototype.getValue = function() {
  return this.value;
};

TinkerProperty.prototype.isPresent = function() {
  return !!this.value;
};

TinkerProperty.prototype.isHidden = function() {
  // return GraphKey.isHidden(this.key);
};

module.exports = TinkerProperty;<commit_msg>Convert Property to ES6 class<commit_after>class TinkerProperty {
  constructor(element, key, value) {
    this.element = element;
    this.key = key;
    this.value = value;
    this.graph = this.element.graph;
  }

  getElement() {
    return this.element;
  };

  getKey() {
    // return GraphKey.unHide(this.key);
  };

  getValue() {
    return this.value;
  };

  isPresent() {
    return !!this.value;
  };

  isHidden() {
    // return GraphKey.isHidden(this.key);
  };
}

export default TinkerProperty;
<|endoftext|>


<commit_before>var Sockets = {}

Sockets.Socket = function Socket (signal, namespace) {
    "use strict";
    //TODO -- revert to long poll on false?
    if(!('WebSocket' in window)) throw new Error("Websockets not supported in this browser")

    var thus = this
    this.connection = io ? io.connect('http://localhost:3001') : new WebSocket("ws://localhost:3001")
    this.signal = signal

    this.send = this.connection.emit ? function (value) {
        thus.connection.emit(namespace || 'data', value)
    } : function (value) {
        //stringify?
        thus.connection.send(value)
    }

    if(this.connection.on)
    this.connection.on(namespace || 'data', function(value) {
        //socket.io is too fancy for its own good and converts this
        //to json -- need to stringify for client consistency
        thus.signal.push(JSON.stringify(value))
    })
    else this.connection.onmessage = function(value) {
        thus.signal.push(value)
    }

}

Sockets.createSocketedSignal = function(namespace) {
    var signal = new Signals.Signal()
    var socket = new Sockets.Socket(signal, namespace)
    return signal
}<commit_msg>Update Socket.js<commit_after>var Sockets = {}

Sockets.Socket = function Socket (signal, namespace) {
    "use strict";
    //TODO -- revert to long poll on false?
    if(!('WebSocket' in window)) throw new Error("Websockets not supported in this browser")

    var thus = this
    //TODO -- this host should be configurable -- how to handle configs in haskell?
    this.connection = io ? io.connect('http://localhost:3001') : new WebSocket("ws://localhost:3001")
    this.signal = signal

    this.send = this.connection.emit ? function (value) {
        thus.connection.emit(namespace || 'data', value)
    } : function (value) {
        //stringify?
        thus.connection.send(value)
    }

    if(this.connection.on)
    this.connection.on(namespace || 'data', function(value) {
        //socket.io is too fancy for its own good and converts this
        //to json -- need to stringify for client consistency
        thus.signal.push(JSON.stringify(value))
    })
    else this.connection.onmessage = function(value) {
        thus.signal.push(value)
    }

}

Sockets.createSocketedSignal = function(namespace) {
    var signal = new Signals.Signal()
    var socket = new Sockets.Socket(signal, namespace)
    return signal
}
<|endoftext|>


<commit_before>define(
	[
		"../meta",
		"../type",
		"./method",
		"../shim/array"
	],
	function (meta, type) {
		"use strict";

		meta({
			"entity": "module",
			"description": "Augments Function prototype with mixin method for decorating a constructor function's prototype."
		});

		meta({
			"entity": "class",
			"name": "Function",
			"global": true
		});

		if (!Function.prototype.mixin) {
			Function.method(
				meta({
					"entity": "method",
					"name": "mixin",
					"description": "Objects own methods will be appended to function's prototype.",
					"arguments": [{
						"name": "mixins",
						"type": "object"
					}],
					"returns": "function"
				}),
				mixin
			);

			Function.method(
				meta({
					"entity": "method",
					"name": "mixin",
					"description": "Constructor's own methods will be appended to function's prototype.",
					"arguments": [{
						"name": "constructor",
						"type": "function"
					}],
					"returns": "function"
				}),
				function (constructor) {
					return mixin.call(this, constructor.prototype);
				}
			);

			Function.method(
				meta({
					"entity": "method",
					"name": "mixin",
					"description": "Object's and Constructor's own methods will be appended to function's prototype.",
					"arguments": [{
						"name": "mixins",
						"type": "array",
						"description": "Array of objects or constructor functions"
					}],
					"returns": "function"
				}),
				function (mixins) {
					mixins.forEach(mixinConstructorOrObject, this);
					return this;
				}
			);
		}

		function mixinConstructorOrObject (mixin, index, array) {
			this.mixin(mixin);
		}

		function mixin (mixins) {
			var Constructor = this;
			Object.keys(mixins).filter(isFunction).forEach(attachMethod);

			function isFunction (name) {
				return type.is("function", mixins[name]);
			}

			function attachMethod (name) {
				Constructor.method(name, mixins[name]);
			}

			return Constructor;
		}
	}
);
<commit_msg>adding missing dependency shim/object to class/mixin module<commit_after>define(
	[
		"../meta",
		"../type",
		"./method",
		"../shim/object",
		"../shim/array"
	],
	function (meta, type) {
		"use strict";

		meta({
			"entity": "module",
			"description": "Augments Function prototype with mixin method for decorating a constructor function's prototype."
		});

		meta({
			"entity": "class",
			"name": "Function",
			"global": true
		});

		if (!Function.prototype.mixin) {
			Function.method(
				meta({
					"entity": "method",
					"name": "mixin",
					"description": "Objects own methods will be appended to function's prototype.",
					"arguments": [{
						"name": "mixins",
						"type": "object"
					}],
					"returns": "function"
				}),
				mixin
			);

			Function.method(
				meta({
					"entity": "method",
					"name": "mixin",
					"description": "Constructor's own methods will be appended to function's prototype.",
					"arguments": [{
						"name": "constructor",
						"type": "function"
					}],
					"returns": "function"
				}),
				function (constructor) {
					return mixin.call(this, constructor.prototype);
				}
			);

			Function.method(
				meta({
					"entity": "method",
					"name": "mixin",
					"description": "Object's and Constructor's own methods will be appended to function's prototype.",
					"arguments": [{
						"name": "mixins",
						"type": "array",
						"description": "Array of objects or constructor functions"
					}],
					"returns": "function"
				}),
				function (mixins) {
					mixins.forEach(mixinConstructorOrObject, this);
					return this;
				}
			);
		}

		function mixinConstructorOrObject (mixin, index, array) {
			this.mixin(mixin);
		}

		function mixin (mixins) {
			var Constructor = this;
			Object.keys(mixins).filter(isFunction).forEach(attachMethod);

			function isFunction (name) {
				return type.is("function", mixins[name]);
			}

			function attachMethod (name) {
				Constructor.method(name, mixins[name]);
			}

			return Constructor;
		}
	}
);
<|endoftext|>


<commit_before>/**
 * boot.js -- loads lively in any page that inserts through a script tag
 *
 **/

/* global lively4performance */
/* eslint no-console: off */

/*
 #TODO refactor booting/loading/init of lively4
  - currently we have different entry points we should unify
 */

async function loadJavaScript(name, src, force) {
  var code = await fetch(src).then(r => r.text())
  eval(code)
}

self.lively4currentbootid = "" + new Date()
self.lively4bootlogData = []
self.lively4bootlog = function add(url, date=Date.now(), mode="load", time=0, parentURL) {
  self.lively4bootlogData.push({
    url, date, mode, time, parentURL, bootid: self.lively4currentbootid
  })
}

if (!(localStorage["logLivelyBoot"] == "true")) {
  self.lively4bootlog = function() {
    // do nothing
  }
}

self.lively4transpilationCache = {
  update(cacheKey, cache) {
    this.cache.set(cacheKey, cache)
      var cacheJSO = {
        url: cacheKey,
        input: cache.input,
        output: cache.output,
        map: JSON.stringify(cache.map),
      }

      if (!cacheKey.match(/^workspace/) && !self.__karma__) {
        console.log("[babel] update transpilation cache " + cacheKey) // from client to server :-) #Security anybody?
        var transpileCacheURL = lively4url + "/.transpiled/" + cacheKey.replace(lively4url + "/","").replace(/\//g,"_") // flatten path
        fetch(transpileCacheURL, {
          method: "PUT",
          headers: {
            nocommit: true, // .transpiled is in gitignore... and the server cannot handle it automaitcally
          },
          body: cacheJSO.output
        })

        fetch(transpileCacheURL + ".map.json", {
          method: "PUT",
          headers: {
            nocommit: true
          },
          body: cacheJSO.map
        })
      }
  },
  cache: new Map()
}

self.lively4syncCache = new Map()
self.lively4optionsCache = new Map()
self.lively4fetchLog = []

async function invalidateFileCaches()  {
  var url = lively4url + "/"

  if (self.lively && lively.fileIndexWorker) {
    lively.fileIndexWorker.postMessage({message: "updateDirectory", url})
  }

  const FilesCaches = await System.import("src/client/files-caches.js")
  console.log("[boot] invalidateFileCaches:\n" + FilesCaches.invalidateTranspiledFiles())

}
self.lively4invalidateFileCaches = invalidateFileCaches

async function preloadFileCaches() {
  await loadJavaScript("JSZip", lively4url + "/src/external/jszip.js" )

  var start = performance.now()
  var preloadurl = lively4url + "/.lively4bundle.zip" + "?" + Date.now()
  var resp = await fetch(preloadurl)
  if (resp.status != "200") {
    console.warn("NO preload cache found in", preloadurl)
    return
  }
  var contents = await resp.blob()

  var archive = await self.JSZip.loadAsync(contents)
  console.log("[boot] preloadFileCache fetched contents in  " + Math.round(performance.now() - start) + "ms")

  start = performance.now()
  for(var ea of Object.keys(archive.files)) {
    if (ea.match(/\.transpiled\//) || ea.match(/\.options\//)) continue;

    var file = archive.file(ea);
    if (file) {
      var modified = file.date.toISOString().replace(/T/, " ").replace(/\..*/, "")
      var url = lively4url + "/" + ea
      var content = await file.async("string")
      var mimeType = " text/plain"
      if (url.match(/\.js$/)) mimeType = "application/javascript"
      if (url.match(/\.css$/)) mimeType = "text/css"
      var response = new Response(content, {
        headers: {
          "content-type": mimeType,
          modified: modified
        }
      })
      self.lively4syncCache.set(url, response)
      // var cached = await self.lively4offlineFirstCache.match(url)
      // if (cached && cached.headers.get("modified") == modified) {
      //   // do nothing
      //   // console.log("PRECACHE IGNORE " + ea)
      // } else {
      //   // console.log("[boot] preloadFileCaches: " + ea)
      //   self.lively4offlineFirstCache.put(url, response)
      // }

      var optionsPath = ".options/" + ea.replace(/\//g,"_")
      var optionsFile = archive.file(optionsPath)
      if (optionsFile) {
        var optionsContent = await optionsFile.async("string")
        self.lively4optionsCache.set(url, new Response(optionsContent, {
          headers: {
            "content-type": "application/json"
          }
        }))
      }

      if (ea.match(/.js$/)) {
          var transpiledPath = ".transpiled/" + ea.replace(/\//g,"_")
          var transpiledFile = archive.file(transpiledPath)
          var mapFile = archive.file(transpiledPath + ".map.json");

          if (transpiledFile) {
            // console.log("[boot] preloadFileCache initialize transpiled javascript: " + ea)
            try {
              var transpiledCode = await transpiledFile.async("string")
              if (mapFile) {
                var map = JSON.parse(await mapFile.async("string"))
              }
              self.lively4transpilationCache.cache.set(url, {
                  input: content,
                  output: transpiledCode,
                  map: map,
                  modified: modified
                })
            } catch(e) {
              console.error("[boot] error in loading transpiled code: " + ea, e)
            }
          }
        }
    }
  }
  console.log("[boot] preloadFileCache updated caches in  " + Math.round(performance.now() - start) + "ms")
}

self.lively4fetchHandlers = []
function instrumentFetch() {
  if (!self.originalFetch) self.originalFetch = self.fetch
  self.fetch = async function(request, options, ...rest) {
    var result = await new Promise(resolve => {
      if (self.lively4fetchHandlers) {
        // go through our list of handlers... the first one who handles it wins
        for(var handler of self.lively4fetchHandlers) {
          var handled = handler.handle && handler.handle(request, options)
          if (handled) return resolve(handled.result);
        }
      }
      return resolve(self.originalFetch.apply(self, [request, options, ...rest]))
    })
    if (self.lively4fetchHandlers) {
      // anybody insterested when it finished
      for(var handler of self.lively4fetchHandlers) {
        handler.finsihed && handler.finsihed(request, options)
      }
    }
    return result
  }
}

function installCachingFetch() {
  self.lively4fetchHandlers.push({
    handle(request, options) {
      var url = (request.url || request).toString()
      var method = "GET"
      if (options && options.method) method = options.method;

      if (url.match(lively4url)) {
        self.lively4fetchLog.push({
          time: performance.now(),
          method: method,
          url: url
        })
        if (!self.lively4syncCache) return
        if (method == "GET") {
          if (options && options.headers && options.headers["fileversion"]) {
            return // don't cache versions request...
          }

          let match = self.lively4syncCache.get(url)
          if (match) {
            // console.log("[boot] SYNC CACHED " + url)
            return {
              result: Promise.resolve(match.clone())
            }
          } else {
            // console.log("[boot] SYNC MISSED " + url)
          }
        } else if (method == "PUT") {
          // clear cache for PUT
          // so next GET will get the new content
          self.lively4syncCache.set(url, null)

          // #TODO we could further store the PUT already locally?
          // PRO: offline support
          // CONTRA: not sure if the file reached the server....

          // and don't further handle it... so that it will be saved on the server
        } else if (method == "OPTIONS") {
           if (options && options.headers && options.headers["showversions"]) {
            return // don't cache versions request...
          }

          let match = self.lively4optionsCache.get(url)
          if (match) {
            // console.log("[boot] SYNC OPTIONS CACHED " + url)
            return {
              result: Promise.resolve(match.clone())
            }
          } else {
            // console.log("[boot] SYNC OPTIONS MISSED " + url)
          }
        } else {
          // do nothing
        }
      }
    },
    finished(request, options) {
      console.log("[boot] FINISHED fetch " + request.toString())
    }
  })
}

if (self.lively && self.lively4url) {
  console.log("CANCEL BOOT Lively4, because it is already loaded")
} else {
  (async () => {

    // for finding the baseURL...
    var script = document.currentScript;
    var scriptURL = script.src;
    self.lively4url = scriptURL.replace("/src/client/boot.js","");

    // early feedback due to long loading time
    let livelyBooting = document.createElement('div');
    Object.assign(livelyBooting.style, {
      position: 'fixed',
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)',

      zIndex: '10000',

      backgroundColor: 'white',
      border: 'black 1px solid',
      padding: '5px',
      boxShadow: '0px 0px 3px 0px rgba(40, 40, 40,0.66)'
    });
    livelyBooting.innerHTML = `
Booting:

`;
    document.body.appendChild(livelyBooting);

    self.lively4bootGroupedMessages = []
    var lastMessage

    var estimatedSteps = 10;
    var stepCounter = 1;

    function groupedMessage( message) {
      var part = stepCounter++
      var numberOfSteps = estimatedSteps
      lastMessage =  {part, message, begin: performance.now()}

      console.group(`${part}/${numberOfSteps}: ${message}.`);

      let messageDiv = document.body.querySelector('#lively-booting-message');
      if(messageDiv) {
        messageDiv.innerHTML = `<span>${part}</span>/<span>${numberOfSteps}</span>: <span>${message}.</span>`;
      }
    }

    function groupedMessageEnd() {
      console.groupEnd();
      if (lastMessage) {
        lastMessage.end = performance.now()
        self.lively4bootGroupedMessages.push(lastMessage)
      }
    }

    console.group("BOOT");

    // some performance logging
    self.lively4performance = {start: performance.now()}
    try {
      Object.defineProperty(window, 'lively4stamp', {
        get: function() {
          if (!self.lively4performance) return;
          var newLast = performance.now()
          var t = (newLast - (lively4performance.last || lively4performance.start)) / 1000
          lively4performance.last = newLast
          return (t.toFixed(3) + "s ")
        }
      })
    } catch(e) {
      console.error(e)
    }

    var loadContainer = script.getAttribute("data-container"); // some simple configuration

    console.log("lively4url: " + lively4url);

      // first things first
      instrumentFetch()
      installCachingFetch()

      groupedMessage('Preload Files');
        await preloadFileCaches()
        // we could wait, or not... if we load transpiled things... waiting is better
      groupedMessageEnd();

      groupedMessage('Setup SystemJS');
        await loadJavaScript("systemjs", lively4url + "/src/external/systemjs/system.src.js");
        await loadJavaScript("systemjs-config", lively4url + "/src/systemjs-config.js");
      groupedMessageEnd();

      try {
          groupedMessage('Initialize SystemJS');
            await System.import(lively4url + "/src/client/preload.js");
          groupedMessageEnd();

          groupedMessage('Setup fetch proxy');
            await System.import(lively4url + "/src/client/fetch.js").then(mod => {
              return mod.installProxyFetch()
            })
          groupedMessageEnd();

          groupedMessage('Wait on service worker (in load.js)');
            await (await System.import(lively4url + "/src/client/load-swx.js")).whenLoaded; // wait on service worker
          groupedMessageEnd();

          groupedMessage('Load Base System (lively.js)');
            await System.import("src/client/lively.js")

            // from load.js
            // lively.components.loadUnresolved(document.body, true, "load.js", true)

            // Customize.... #TODO where should it go?
            if (!self.__karma__ && navigator.userAgent.toLowerCase().indexOf('electron/') == -1) {
              self.onbeforeunload = function() {
                return 'Do you really want to leave this page?'; // gets overriden by Chrome native
              };
              self.onunload = function() {
                lively.onUnload && lively.onUnload()
              };
            }
          groupedMessageEnd();

          groupedMessage('Load Standard Library');
            await System.import("lang");
            await System.import("lang-ext");
          groupedMessageEnd();

          groupedMessage('Initialize Document (in lively.js)' );
            await lively.initializeDocument(document, self.lively4chrome, loadContainer);
          groupedMessageEnd();

          groupedMessage('Look for uninitialized instances of Web Compoments');
            await lively.components.loadUnresolved(document.body, true, "boot.js", true)
          groupedMessageEnd();

          var componentWithContent = Array.from(lively.allElements(document.body))
              .filter(ea => ea.livelyContentLoaded && ea.livelyContentLoaded.then)
          groupedMessage(`Wait on ${componentWithContent.length} components with content`);

          // wait on all components to intialize their content.... e.g. the container loading a file
            await Promise.all(componentWithContent.map(ea => ea.livelyContentLoaded))
          groupedMessageEnd();

          console.log("Finally loaded!");
          if (self.lively4bootGroupedMessages) {
            var str =  self.lively4bootGroupedMessages.map(ea => {
              return ea.part + " "  + Math.round(ea.end - ea.begin) + "ms "+ ea.message
            }).join("\n")
            console.log("BOOT", str)
          }

          if (self.lively4bootlogData) {
            System.import("src/client/bootlog.js").then(m => {
              m.default.current().addLogs(self.lively4bootlogData)
            }).then(() => console.log("saved bootlog"))
          }

          document.dispatchEvent(new Event("livelyloaded"));
      // } catch(err) {
      //   console.error("Lively Loading failed");
      //   console.error(err);
      } finally {
        console.groupEnd(); // BOOT
        livelyBooting.remove();
      }

  })();
}<commit_msg>light boot.js refactoring<commit_after>/**
 * boot.js -- loads lively in any page that inserts through a script tag
 *
 **/

/* eslint no-console: off */

/*
 * HELPER
 */

async function loadJavaScript(name, src, force) {
  var code = await fetch(src).then(r => r.text())
  eval(code)
}

self.lively4currentbootid = "" + new Date()
self.lively4bootlogData = []
self.lively4bootlog = function add(url, date=Date.now(), mode="load", time=0, parentURL) {
  self.lively4bootlogData.push({
    url, date, mode, time, parentURL, bootid: self.lively4currentbootid
  })
}

if (!(localStorage["logLivelyBoot"] == "true")) {
  self.lively4bootlog = function() {
    // do nothing
  }
}

/*
 * CACHES
 */
self.lively4transpilationCache = {
  update(cacheKey, cache) {
    this.cache.set(cacheKey, cache)
    var cacheJSO = {
      url: cacheKey,
      input: cache.input,
      output: cache.output,
      map: JSON.stringify(cache.map),
    }

    if (!cacheKey.match(/^workspace/) && !self.__karma__) {
      console.log("[babel] update transpilation cache " + cacheKey) // from client to server :-) #Security anybody?
      var transpileCacheURL = lively4url + "/.transpiled/" + cacheKey.replace(lively4url + "/","").replace(/\//g,"_") // flatten path
      fetch(transpileCacheURL, {
        method: "PUT",
        headers: {
          nocommit: true, // .transpiled is in gitignore... and the server cannot handle it automaitcally
        },
        body: cacheJSO.output
      })

      fetch(transpileCacheURL + ".map.json", {
        method: "PUT",
        headers: {
          nocommit: true
        },
        body: cacheJSO.map
      })
    }
  },
  cache: new Map()
}

self.lively4syncCache = new Map()
self.lively4optionsCache = new Map()
self.lively4fetchLog = []

async function invalidateFileCaches()  {
  var url = lively4url + "/"

  if (self.lively && lively.fileIndexWorker) {
    lively.fileIndexWorker.postMessage({message: "updateDirectory", url})
  }

  const FilesCaches = await System.import("src/client/files-caches.js")
  console.log("[boot] invalidateFileCaches:\n" + FilesCaches.invalidateTranspiledFiles())

}
self.lively4invalidateFileCaches = invalidateFileCaches

async function preloadFileCaches() {
  await loadJavaScript("JSZip", lively4url + "/src/external/jszip.js" )

  var start = performance.now()
  var preloadurl = lively4url + "/.lively4bundle.zip" + "?" + Date.now()
  var resp = await fetch(preloadurl)
  if (resp.status != "200") {
    console.warn("NO preload cache found in", preloadurl)
    return
  }
  var contents = await resp.blob()

  var archive = await self.JSZip.loadAsync(contents)
  console.log("[boot] preloadFileCache fetched contents in  " + Math.round(performance.now() - start) + "ms")

  start = performance.now()
  for(let ea of Object.keys(archive.files)) {
    if (ea.match(/\.transpiled\//) || ea.match(/\.options\//)) continue;

    let file = archive.file(ea);
    if (file) {
      let modified = file.date.toISOString().replace(/T/, " ").replace(/\..*/, ""),
        url = lively4url + "/" + ea,
        content = await file.async("string"),
        mimeType = " text/plain"
      if (url.match(/\.js$/)) mimeType = "application/javascript"
      if (url.match(/\.css$/)) mimeType = "text/css"
      var response = new Response(content, {
        headers: {
          "content-type": mimeType,
          modified: modified
        }
      })
      self.lively4syncCache.set(url, response)

      let optionsPath = ".options/" + ea.replace(/\//g,"_"),
        optionsFile = archive.file(optionsPath)
      if (optionsFile) {
        let optionsContent = await optionsFile.async("string")
        self.lively4optionsCache.set(url, new Response(optionsContent, {
          headers: {
            "content-type": "application/json"
          }
        }))
      }

      if (ea.match(/.js$/)) {
        let transpiledPath = ".transpiled/" + ea.replace(/\//g,"_"),
            transpiledFile = archive.file(transpiledPath),
            mapFile = archive.file(transpiledPath + ".map.json");

        if (transpiledFile) {
          // console.log("[boot] preloadFileCache initialize transpiled javascript: " + ea)
          try {
            var transpiledCode = await transpiledFile.async("string")
            if (mapFile) {
              var map = JSON.parse(await mapFile.async("string"))
            }
            self.lively4transpilationCache.cache.set(url, {
              input: content,
              output: transpiledCode,
              map: map,
              modified: modified
            })
          } catch(e) {
            console.error("[boot] error in loading transpiled code: " + ea, e)
          }
        }
      }
    }
  }
  console.log("[boot] preloadFileCache updated caches in  " + Math.round(performance.now() - start) + "ms")
}

self.lively4fetchHandlers = []
function instrumentFetch() {
  if (!self.originalFetch) self.originalFetch = self.fetch
  self.fetch = async function(request, options, ...rest) {
    var result = await new Promise(resolve => {
      if (self.lively4fetchHandlers) {
        // go through our list of handlers... the first one who handles it wins
        for(var handler of self.lively4fetchHandlers) {
          var handled = handler.handle && handler.handle(request, options)
          if (handled) return resolve(handled.result);
        }
      }
      return resolve(self.originalFetch.apply(self, [request, options, ...rest]))
    })
    if (self.lively4fetchHandlers) {
      // anybody insterested when it finished
      for(var handler of self.lively4fetchHandlers) {
        handler.finsihed && handler.finsihed(request, options)
      }
    }
    return result
  }
}

function installCachingFetch() {
  self.lively4fetchHandlers.push({
    handle(request, options) {
      var url = (request.url || request).toString()
      var method = "GET"
      if (options && options.method) method = options.method;

      if (url.match(lively4url)) {
        self.lively4fetchLog.push({
          time: performance.now(),
          method: method,
          url: url
        })
        if (!self.lively4syncCache) return
        if (method == "GET") {
          if (options && options.headers && options.headers["fileversion"]) {
            return // don't cache versions request...
          }

          let match = self.lively4syncCache.get(url)
          if (match) {
            // console.log("[boot] SYNC CACHED " + url)
            return {
              result: Promise.resolve(match.clone())
            }
          } else {
            // console.log("[boot] SYNC MISSED " + url)
          }
        } else if (method == "PUT") {
          // clear cache for PUT
          // so next GET will get the new content
          self.lively4syncCache.set(url, null)

          // #TODO we could further store the PUT already locally?
          // PRO: offline support
          // CONTRA: not sure if the file reached the server....

          // and don't further handle it... so that it will be saved on the server
        } else if (method == "OPTIONS") {
           if (options && options.headers && options.headers["showversions"]) {
            return // don't cache versions request...
          }

          let match = self.lively4optionsCache.get(url)
          if (match) {
            // console.log("[boot] SYNC OPTIONS CACHED " + url)
            return {
              result: Promise.resolve(match.clone())
            }
          } else {
            // console.log("[boot] SYNC OPTIONS MISSED " + url)
          }
        } else {
          // do nothing
        }
      }
    },
    finished(request, options) {
      console.log("[boot] FINISHED fetch " + request.toString())
    }
  })
}

/*
 * MAIN BOOT FUNCTION: load Lively4 and get it going....
 */
async function intializeLively() {
  if(self.lively && self.lively4url) {
    return console.log("CANCEL BOOT Lively4, because it is already loaded")
  }
  // for finding the baseURL...
  var script = document.currentScript;
  var scriptURL = script.src;
  self.lively4url = scriptURL.replace("/src/client/boot.js","");

  // early feedback due to long loading time
  let livelyBooting = document.createElement('div');
  Object.assign(livelyBooting.style, {
    position: 'fixed',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',

    zIndex: '10000',

    backgroundColor: 'white',
    border: 'black 1px solid',
    padding: '5px',
    boxShadow: '0px 0px 3px 0px rgba(40, 40, 40,0.66)'
  });
  livelyBooting.innerHTML = `
Booting:

`;
  document.body.appendChild(livelyBooting);

  self.lively4bootGroupedMessages = []
  var lastMessage

  var estimatedSteps = 10;
  var stepCounter = 1;

  function groupedMessage( message) {
    var part = stepCounter++
    var numberOfSteps = estimatedSteps
    lastMessage =  {part, message, begin: performance.now()}

    console.group(`${part}/${numberOfSteps}: ${message}.`);

    let messageDiv = document.body.querySelector('#lively-booting-message');
    if(messageDiv) {
      messageDiv.innerHTML = `<span>${part}</span>/<span>${numberOfSteps}</span>: <span>${message}.</span>`;
    }
  }

  function groupedMessageEnd() {
    console.groupEnd();
    if (lastMessage) {
      lastMessage.end = performance.now()
      self.lively4bootGroupedMessages.push(lastMessage)
    }
  }

  console.group("BOOT");

  // some performance logging
  self.lively4performance = {start: performance.now()}
  try {
    Object.defineProperty(window, 'lively4stamp', {
      get: function() {
        if (!self.lively4performance) return;
        var newLast = performance.now()
        var t = (newLast - (self.lively4performance.last || self.lively4performance.start)) / 1000
        self.lively4performance.last = newLast
        return (t.toFixed(3) + "s ")
      }
    })
  } catch(e) {
    console.error(e)
  }

  var loadContainer = script.getAttribute("data-container"); // some simple configuration

  console.log("lively4url: " + lively4url);

  // first things first
  instrumentFetch()
  installCachingFetch()

  groupedMessage('Preload Files');
    await preloadFileCaches()
    // we could wait, or not... if we load transpiled things... waiting is better
  groupedMessageEnd();

  groupedMessage('Setup SystemJS');
    await loadJavaScript("systemjs", lively4url + "/src/external/systemjs/system.src.js");
    await loadJavaScript("systemjs-config", lively4url + "/src/systemjs-config.js");
  groupedMessageEnd();

  try {
    groupedMessage('Initialize SystemJS');
      await System.import(lively4url + "/src/client/preload.js");
    groupedMessageEnd();

    groupedMessage('Setup fetch proxy');
      await System.import(lively4url + "/src/client/fetch.js").then(mod => {
        return mod.installProxyFetch()
      })
    groupedMessageEnd();

    groupedMessage('Wait on service worker (in load.js)');
      await (await System.import(lively4url + "/src/client/load-swx.js")).whenLoaded; // wait on service worker
    groupedMessageEnd();

    groupedMessage('Load Base System (lively.js)');
      await System.import("src/client/lively.js")

      // from load.js
      // lively.components.loadUnresolved(document.body, true, "load.js", true)

      // Customize.... #TODO where should it go?
      if (!self.__karma__ && navigator.userAgent.toLowerCase().indexOf('electron/') == -1) {
        self.onbeforeunload = function() {
          return 'Do you really want to leave this page?'; // gets overriden by Chrome native
        };
        self.onunload = function() {
          lively.onUnload && lively.onUnload()
        };
      }
    groupedMessageEnd();

    groupedMessage('Load Standard Library');
      await System.import("lang");
      await System.import("lang-ext");
    groupedMessageEnd();

    groupedMessage('Initialize Document (in lively.js)' );
      await lively.initializeDocument(document, self.lively4chrome, loadContainer);
    groupedMessageEnd();

    groupedMessage('Look for uninitialized instances of Web Compoments');
      await lively.components.loadUnresolved(document.body, true, "boot.js", true)
    groupedMessageEnd();

    // wait on all components to intialize their content.... e.g. the container loading a file
    var componentWithContent = Array.from(lively.allElements(document.body))
        .filter(ea => ea.livelyContentLoaded && ea.livelyContentLoaded.then)
    groupedMessage(`Wait on ${componentWithContent.length} components with content`);
      await Promise.all(componentWithContent.map(ea => ea.livelyContentLoaded))
    groupedMessageEnd();

    console.log("Finally loaded!");
    if (self.lively4bootGroupedMessages) {
      var str =  self.lively4bootGroupedMessages.map(ea => {
        return ea.part + " "  + Math.round(ea.end - ea.begin) + "ms "+ ea.message
      }).join("\n")
      console.log("BOOT", str)
    }

    if (self.lively4bootlogData) {
      System.import("src/client/bootlog.js").then(m => {
        m.default.current().addLogs(self.lively4bootlogData)
      }).then(() => console.log("saved bootlog"))
    }
    document.dispatchEvent(new Event("livelyloaded"));
  } finally {
    console.groupEnd(); // BOOT
    livelyBooting.remove();
  }
}

intializeLively()
<|endoftext|>


<commit_before>"use strict";

class MQ {
  constructor(breakpoints){
    this.bp = breakpoints;
  }

  checkBP(size){
    return checkBP(size, this.bp);
  }

  min(size, callback) {
    return result(
      screenWidth() > this.checkBP(size),
      callback
    );
  }
  //alias for "min"
  minWidth(size, callback){
    return this.min(size, callback);
  }

  max(size, callback){
    return result(
      screenWidth() <= this.checkBP(size),
      callback
    );
  }
  //alias for "max"
  maxWidth(size, callback){
    return this.max(size, callback);
  }

  inside(wideSize, thinSize, callback){
    return result(
      inside(wideSize, thinSize, 'w', this.bp),
      callback
    );
  }

  outside(wideSize, thinSize, callback){
    return result(
      !inside(wideSize, thinSize, 'w', this.bp),
      callback
    );
  }
}

function result (isAllowed, callback = ()=>{}) {
  const screen_size = { width: screenWidth(), height: screenHeight() };
  if (isAllowed) callback.call(window, screen_size);
  return isAllowed;
}

function screenWidth () {
  return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
}

function screenHeight () {
  return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
}

//Checks if the size is a valid breakpoint value
function checkBP(size, breakpoints){
  if (typeof size === 'string'){
    if (typeof breakpoints[size] !== 'undefined'){
      return breakpoints[size];
    } else {
      console.log('Available Breakpoints:', breakpoints);
      throw new Error(`"${size}" breakpoint does not exist`);
    }
  } else if (typeof size === 'number') {
    return size;
  } else {
    console.log('Available Breakpoints:', breakpoints);
    throw new Error(`"${size}" is not a valid breakpoint. It must be a string or a number`);
  }
}

// Test if current screen size is between 2 values
function inside (largeSize, smallSize, dimension, breakpoints) {
  if (values.length > 2){
    throw new Error('More than 2 values provided to "inside" function: '+values);
  }

  const dimensions = {
    w: screenWidth(),
    h: screenHeight(),
  }

  const screen_dimension = dimensions[dimension];

  if (!screen_dimension){
    throw new Error(`invalid direction: "${direction}"; valid directions are: ${dimensions.keys}`);
  }

  let largeSize = checkBP(largeSize, breakpoints);
  let smallSize = checkBP(smallSize, breakpoints);

  //If smallest is first, it swaps the values around
  if (largeSize < smallSize){
    const tmp = largeSize;
    largeSize = smallSize;
    smallSize = tmp;
  }

  return smallSize < screen_dimension && screen_dimension <= largeSize;
}

export default MQ;
<commit_msg>Adding min and max height<commit_after>"use strict";

class MQ {
  constructor(breakpoints){
    this.bp = breakpoints;
  }

  checkBP(size){
    return checkBP(size, this.bp);
  }

  min(size, callback) {
    return result(
      screenWidth() > this.checkBP(size),
      callback
    );
  }
  //alias for "min"
  minWidth(size, callback){
    return this.min(size, callback);
  }

  max(size, callback){
    return result(
      screenWidth() <= this.checkBP(size),
      callback
    );
  }
  //alias for "max"
  maxWidth(size, callback){
    return this.max(size, callback);
  }

  minHeight(size, callback){
    return result(
      screenHeight() > this.checkBP(size),
      callback
    );
  }

  maxHeight(size, callback){
    return result(
      screenHeight() <= this.checkBP(size),
      callback
    );
  }

  inside(wideSize, thinSize, callback){
    return result(
      inside(wideSize, thinSize, 'w', this.bp),
      callback
    );
  }

  outside(wideSize, thinSize, callback){
    return result(
      !inside(wideSize, thinSize, 'w', this.bp),
      callback
    );
  }
}

function result (isAllowed, callback = ()=>{}) {
  const screen_size = { width: screenWidth(), height: screenHeight() };
  if (isAllowed) callback.call(window, screen_size);
  return isAllowed;
}

function screenWidth () {
  return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
}

function screenHeight () {
  return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
}

//Checks if the size is a valid breakpoint value
function checkBP(size, breakpoints){
  if (typeof size === 'string'){
    if (typeof breakpoints[size] !== 'undefined'){
      return breakpoints[size];
    } else {
      console.log('Available Breakpoints:', breakpoints);
      throw new Error(`"${size}" breakpoint does not exist`);
    }
  } else if (typeof size === 'number') {
    return size;
  } else {
    console.log('Available Breakpoints:', breakpoints);
    throw new Error(`"${size}" is not a valid breakpoint. It must be a string or a number`);
  }
}

// Test if current screen size is between 2 values
function inside (largeSize, smallSize, dimension, breakpoints) {
  if (values.length > 2){
    throw new Error('More than 2 values provided to "inside" function: '+values);
  }

  const dimensions = {
    w: screenWidth(),
    h: screenHeight(),
  }

  const screen_dimension = dimensions[dimension];

  if (!screen_dimension){
    throw new Error(`invalid direction: "${direction}"; valid directions are: ${dimensions.keys}`);
  }

  let largeSize = checkBP(largeSize, breakpoints);
  let smallSize = checkBP(smallSize, breakpoints);

  //If smallest is first, it swaps the values around
  if (largeSize < smallSize){
    const tmp = largeSize;
    largeSize = smallSize;
    smallSize = tmp;
  }

  return smallSize < screen_dimension && screen_dimension <= largeSize;
}

export default MQ;
<|endoftext|>


<commit_before>/**
 * @file Color vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import Valid from './Valid';

function _getHueRGB(perCent) {

    const data = [[255, 0, 0], [255, 255, 0], [0, 255, 0], [0, 255, 255], [0, 0, 255], [255, 0, 255], [255, 0, 0]];

    if (Valid.isPerCent(perCent)) {
        return data[Math.floor(perCent * 6)];
    }

    return data[0];

}

function hue2rgb(hue) {

    if (!Valid.isDeg(hue)) {
        return;
    }

    const perCent = hue / 360,
        int = Math.floor(perCent * 6),
        offset = Math.round((perCent * 6 - int) * 255),
        rgb = _getHueRGB(perCent);

    rgb[(int * 2 + 1) % 3] += offset * (Valid.isOdd(int) ? -1 : 1);

    return rgb;

}

function rgb2hsb(rgb) {

    if (!Valid.isRGB(rgb)) {
        return;
    }

    const [r, g, b] = rgb,
        max = Math.max(...rgb),
        min = Math.min(...rgb);

    let h = 0;

    if (max == r && g >= b) {
        h = (g - b) * 60 / (max - min) + 0;
    } else if (max == r && g < b) {
        h = (g - b) * 60 / (max - min) + 360;
    } else if (max == g) {
        h = (b - r) * 60 / (max - min) + 120;
    } else if (max == b) {
        h = (r - g) * 60 / (max - min) + 240;
    }

    return [h, max === 0 ? 0 : (max - min) / max, max / 255];

}

function hsb2rgb(hsb) {

    if (!Valid.isHSB(hsb)) {
        return;
    }

    const [h, s, v] = hsb,
        i = Math.floor((h / 60) % 6),
        f = (h / 60) - i,
        p = v * (1 - s),
        q = v * (1 - f * s),
        t = v * (1 - (1 - f) * s);

    let r = 0, g = 0, b = 0;

    switch (i) {
        case 0:
            r = v;
            g = t;
            b = p;
            break;
        case 1:
            r = q;
            g = v;
            b = p;
            break;
        case 2:
            r = p;
            g = v;
            b = t;
            break;
        case 3:
            r = p;
            g = q;
            b = v;
            break;
        case 4:
            r = t;
            g = p;
            b = v;
            break;
        case 5:
            r = v;
            g = p;
            b = q;
            break;
    }

    return [Math.round(r * 255.0), Math.round(g * 255.0), Math.round(b * 255.0)];

}

function rgb2hex(rgb) {

    if (!Valid.isRGB(rgb)) {
        return;
    }

    return rgb.map(item => item.toString(16)).join('');

}

function hex2rgb(hex, hasHash) {

    if (!Valid.isHex(hex, hasHash)) {
        return;
    }

    function fn(i) {
        const j = hasHash ? 1 : 0;
        return parseInt(hex.slice(i + j, i + j + 2), 16);
    }

    return [fn(0), fn(2), fn(4)];

}

export default {
    hue2rgb,
    rgb2hsb,
    hsb2rgb,
    rgb2hex,
    hex2rgb
};<commit_msg>update Color<commit_after>/**
 * @file Color vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import Valid from './Valid';

function _getHueRGB(perCent) {

    const data = [[255, 0, 0], [255, 255, 0], [0, 255, 0], [0, 255, 255], [0, 0, 255], [255, 0, 255], [255, 0, 0]];

    if (Valid.isPerCent(perCent)) {
        return data[Math.floor(perCent * 6)];
    }

    return data[0];

}

function hue2rgb(hue) {

    if (!Valid.isDeg(hue)) {
        return;
    }

    const perCent = hue / 360,
        int = Math.floor(perCent * 6),
        offset = Math.round((perCent * 6 - int) * 255),
        rgb = _getHueRGB(perCent);

    rgb[(int * 2 + 1) % 3] += offset * (Valid.isOdd(int) ? -1 : 1);

    return rgb;

}

function rgb2hsb(rgb) {

    if (!Valid.isRGB(rgb)) {
        return;
    }

    const [r, g, b] = rgb,
        max = Math.max(...rgb),
        min = Math.min(...rgb);

    let h = 0;

    if (max == r && g >= b) {
        h = (g - b) * 60 / (max - min) + 0;
    } else if (max == r && g < b) {
        h = (g - b) * 60 / (max - min) + 360;
    } else if (max == g) {
        h = (b - r) * 60 / (max - min) + 120;
    } else if (max == b) {
        h = (r - g) * 60 / (max - min) + 240;
    }

    return [h, max === 0 ? 0 : (max - min) / max, max / 255];

}

function hsb2rgb(hsb) {

    if (!Valid.isHSB(hsb)) {
        return;
    }

    let [h, s, v] = hsb;
    h = h === 360 ? 0 : h;

    const i = Math.floor(h / 60) % 6,
        f = h / 60 - i,
        p = v * (1 - s),
        q = v * (1 - f * s),
        t = v * (1 - (1 - f) * s);

    let r = 0, g = 0, b = 0;

    switch (i) {
        case 0:
            r = v;
            g = t;
            b = p;
            break;
        case 1:
            r = q;
            g = v;
            b = p;
            break;
        case 2:
            r = p;
            g = v;
            b = t;
            break;
        case 3:
            r = p;
            g = q;
            b = v;
            break;
        case 4:
            r = t;
            g = p;
            b = v;
            break;
        case 5:
            r = v;
            g = p;
            b = q;
            break;
    }

    return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];

}

function rgb2hex(rgb) {

    if (!Valid.isRGB(rgb)) {
        return;
    }

    return rgb.map(item => item.toString(16)).join('');

}

function hex2rgb(hex, hasHash) {

    if (!Valid.isHex(hex, hasHash)) {
        return;
    }

    function fn(i) {
        const j = hasHash ? 1 : 0;
        return parseInt(hex.slice(i + j, i + j + 2), 16);
    }

    return [fn(0), fn(2), fn(4)];

}

export default {
    hue2rgb,
    rgb2hsb,
    hsb2rgb,
    rgb2hex,
    hex2rgb
};<|endoftext|>


<commit_before>const efs = require('../utils/fs');
const path = require('path');
const config = require('../config');
const log = require('npmlog');

const validateProjects = require('../plugins/validateProjects');
const registerDependencyAndroid = require('../android/registerNativeModule');
const registerDependencyIOS = require('../ios/registerNativeModule');

const getProjectDependencies = () => {
  const pjson = require(path.join(process.cwd(), './package.json'));
  return Object.keys(pjson.dependencies);
};

/**
 * Main action
 * See action description for further informations
 */
function updateProjects(packageName) {
  const project = config.getProjectConfig();

  if (!project) {
    log.error('ERRPACKAGEJSON', `No package found. Are you sure it's a React Native project?`);
    return;
  }

  const dependencies = packageName ? [packageName] : getProjectDependencies();

  if (!packageName) {
    log.info(`Found ${dependencies.length} native dependencies to link`);
  }

  dependencies
    .forEach(name => {
      const dependencyConfig = config.getDependencyConfig(name);

      if (!dependencyConfig) {
        return log.info(`Project ${name} is not a react-native library`);
      }

      if (project.android && dependencyConfig.android) {
        log.info(`Linking ${name} android dependency`);
        registerDependencyAndroid(name, dependencyConfig.android, project.android);
      }

      if (project.ios && dependencyConfig.ios) {
        log.info(`Linking ${name} ios dependency`);
        registerDependencyIOS(dependencyConfig.ios, project.ios);
      }

      if (dependencyConfig.assets) {
        // copy all dependencyConfig.assets to project.assetsFolder
      }
    });
}

module.exports = {
  description: 'This action updates your project and links all native dependencies',
  run: updateProjects,
  args: [{
    name: 'packageName',
  }],
};
<commit_msg>Blacklist react-native from dependencies<commit_after>const efs = require('../utils/fs');
const path = require('path');
const config = require('../config');
const log = require('npmlog');

const validateProjects = require('../plugins/validateProjects');
const registerDependencyAndroid = require('../android/registerNativeModule');
const registerDependencyIOS = require('../ios/registerNativeModule');

const getProjectDependencies = () => {
  const pjson = require(path.join(process.cwd(), './package.json'));
  return Object.keys(pjson.dependencies).filter(name => name !== 'react-native');
};

/**
 * Main action
 * See action description for further informations
 */
function updateProjects(packageName) {
  const project = config.getProjectConfig();

  if (!project) {
    log.error('ERRPACKAGEJSON', `No package found. Are you sure it's a React Native project?`);
    return;
  }

  const dependencies = packageName ? [packageName] : getProjectDependencies();

  if (!packageName) {
    log.info(`Found ${dependencies.length} native dependencies to link`);
  }

  dependencies
    .forEach(name => {
      const dependencyConfig = config.getDependencyConfig(name);

      if (!dependencyConfig) {
        return log.info(`Project ${name} is not a react-native library`);
      }

      if (project.android && dependencyConfig.android) {
        log.info(`Linking ${name} android dependency`);
        registerDependencyAndroid(name, dependencyConfig.android, project.android);
      }

      if (project.ios && dependencyConfig.ios) {
        log.info(`Linking ${name} ios dependency`);
        registerDependencyIOS(dependencyConfig.ios, project.ios);
      }

      if (dependencyConfig.assets) {
        // copy all dependencyConfig.assets to project.assetsFolder
      }
    });
}

module.exports = {
  description: 'This action updates your project and links all native dependencies',
  run: updateProjects,
  args: [{
    name: 'packageName',
  }],
};
<|endoftext|>