<commit_before>/*globals freedom:true, WebSocket */
/*jslint indent:2, white:true, node:true, sloppy:true, browser:true */

/**
 * Implementation of a Social provider that depends on
 * the WebSockets server code in server/router.py
 * The current implementation uses a public facing common server
 * hosted on p2pbr.com
 *
 * The provider offers
 * - A single global buddylist that everyone is on
 * - no reliability
 * - out of order delivery
 * - ephemeral userIds and clientIds
 * @class WSSocialProvider
 * @constructor
 * @param {Function} dispatchEvent callback to signal events
 * @param {WebSocket} webSocket Alternative webSocket implementation for tests
 **/
function WSSocialProvider(dispatchEvent, webSocket) {
  this.dispatchEvent = dispatchEvent;
  this.WS_URL = 'ws://p2pbr.com:8082/route/';
  this.NETWORK_ID = 'websockets';
  var social = freedom.social();
  this.STATUS_NETWORK = social.STATUS_NETWORK;
  this.STATUS_CLIENT = social.STATUS_CLIENT;
  this.conn = null;   // Web Socket
  this.id = null;     // userId of this user
  this.roster = {};   // List of seen users

  this.provider = webSocket || WebSocket;

  setTimeout(this.sendStatus.bind(this, 'OFFLINE', 'offline'), 0);
}

/**
 * Connect to the Web Socket rendezvous server
 * e.g. social.login(Object options)
 * The only login option needed is 'agent', used to determine which group to join in the server
 *
 * @method login
 * @param {Object} loginOptions
 * @return {Object} status - Same schema as 'onStatus' events
 **/
WSSocialProvider.prototype.login = function(loginOpts, continuation) {
  var finishLogin = {
    finished: false,
    continuation: continuation,
    finish: function(msg) {
      if (this.continuation) {
        this.continuation(msg);
        delete this.continuation;
      }
    }
  };

  if (this.conn !== null) {
    console.warn("Already logged in");
    finishLogin.finish(this.sendStatus("ONLINE"));
    return;
  }
  this.conn = new this.provider(this.WS_URL + loginOpts.agent);
  // Save the continuation until we get a status message for
  // successful login.
  this.conn.onmessage = this.onMessage.bind(this, finishLogin);
  this.conn.onerror = function (cont, error) {
    this.conn = null;
    cont.finish(this.sendStatus('ERR_CONNECTION', error));
  }.bind(this, finishLogin);
  this.conn.onclose = function (cont, msg) {
    this.conn = null;
    cont.finish(this.sendStatus('OFFLINE', 'offline'));
  }.bind(this, finishLogin);

  this.sendStatus('CONNECTING', 'connecting');
};

/**
 * Returns all the <user card>s that we've seen so far (from 'onChange' events)
 * Note: the user's own <user card> will be somewhere in this list
 * All user cards will only consist of 1 client, where the clientId is the same as the userId
 * e.g. social.getRoster();
 *
 * @method getRoster
 * @return {Object} { List of <user cards> indexed by userId
 *    'userId1': <user card>,
 *    'userId2': <user card>,
 *     ...
 * }
 **/
WSSocialProvider.prototype.getRoster = function(continuation) {
  continuation(this.roster);
};

/**
 * Send a message to user on your network
 * If the destination is not specified or invalid, the message is dropped
 * Note: userId and clientId are the same for this provider
 * e.g. sendMessage(String destination_id, String message)
 *
 * @method sendMessage
 * @param {String} destination_id - target
 * @return nothing
 **/
WSSocialProvider.prototype.sendMessage = function(to, msg, continuation) {
  if (this.conn) {
    this.conn.send(JSON.stringify({to: to, msg: msg}));
  } else {
    console.error('WS Social Provider: trying to sendMessage when connection not established');
  }
  continuation();
};

/**
   * Disconnects from the Web Socket server
   * e.g. logout(Object options)
   * No options needed
   *
   * @method logout
   * @param {Object} logoutOptions
   * @return {Object} status - same schema as 'onStatus' events
   **/
WSSocialProvider.prototype.logout = function(logoutOpts, continuation) {
  if (this.conn === null) { // We may not have been logged in
    console.warn("Already logged out");
    continuation(this.sendStatus('OFFLINE', 'offline'));
    return;
  }
  this.conn.onclose = function(continuation) {
    this.conn = null;
    continuation(this.sendStatus('OFFLINE', 'offline'));
  }.bind(this, continuation);
  this.conn.close();
};

/**
 * INTERNAL METHODS
 **/

/**
 * Dispatch an 'onStatus' event with the following status
 *
 * @method sendStatus
 * @private
 * @param {String} stat - One of the error codes in STATUS_NETWORK
 * @param {String} message - Display message in the event
 * @return {Object} - same schema as 'onStatus' event
 **/
WSSocialProvider.prototype.sendStatus = function(stat, message) {
  var result = {
    network: this.NETWORK_ID,
    userId: this.id,
    clientId: this.id,
    status: this.STATUS_NETWORK[stat],
    message: message
  };
  this.dispatchEvent('onStatus', result);
  return result;
};

/**
 * Add the following ID to the roster
 * All users only have 1 client which is always messageable
 *
 * @method changeRoster
 * @private
 * @param {String} id - userId of user
 * @return nothing
 **/
WSSocialProvider.prototype.changeRoster = function(id, online) {
  //Keep track if we've actually made changes
  var sendChange = false,
      clients = {};
  //Create entry if not there
  if (!this.roster[id]) {
    sendChange = true;
    clients[id] = {
      clientId: id,
      network: this.NETWORK_ID,
      status: this.STATUS_CLIENT.MESSAGEABLE
    };
    this.roster[id] = {
      userId: id,
      name: id,
      clients: clients
    };
  }
  //Update online/offline status
  if (online && this.roster[id].clients[id].status !==
      this.STATUS_CLIENT.MESSAGEABLE) {
    this.roster[id].clients[id].status = this.STATUS_CLIENT.MESSAGEABLE;
    sendChange = true;
  } else if (!online && this.roster[id].clients[id].status !==
             this.STATUS_CLIENT.OFFLINE) {
    this.roster[id].clients[id].status = this.STATUS_CLIENT.OFFLINE;
    sendChange = true;
  }
  //Only dispatch change events if things have actually changed
  if (sendChange) {
    this.dispatchEvent('onChange', this.roster[id]);
  }
};

/**
 * Interpret messages from the server
 * There are 3 types of messages
 * - Directed messages from friends
 * - State information from the server on initialization
 * - Roster change events (users go online/offline)
 *
 * @method onMessage
 * @private
 * @param {Object} continuation Function to call upon successful login
 * @param {String} msg Message from the server (see server/router.py for schema)
 * @return nothing
 **/
WSSocialProvider.prototype.onMessage = function(continuation, msg) {
  var i;

  msg = JSON.parse(msg.data);
  // If state information from the server
  // Store my own ID and all known users at the time
  if (msg.cmd === 'state') {
    this.id = msg.id;
    this.changeRoster(this.id, true);
    for (i = 0; i < msg.msg.length; i += 1) {
      this.changeRoster(msg.msg[i], true);
    }

    if (!continuation.finished) {
      continuation.finish(this.sendStatus('ONLINE', 'online'));
    }
    // If directed message, emit event
  } else if (msg.cmd === 'message') {
    this.changeRoster(msg.from, true);
    this.dispatchEvent('onMessage', {
      fromUserId: msg.from,
      fromClientId: msg.from,
      toUserId: this.id,
      toClientId: this.id,
      network: this.NETWORK_ID,
      message: msg.msg
    });
  // Roster change event
  } else if (msg.cmd === 'roster') {
    this.changeRoster(msg.id, msg.online);
  // No idea what this message is, but let's keep track of who it's from
  } else if (msg.from) {
    this.changeRoster(msg.from, true);
  }
};

/** REGISTER PROVIDER **/
if (typeof freedom !== 'undefined') {
  freedom.social().provideAsynchronous(WSSocialProvider);
}
<commit_msg>fix #48<commit_after>/*globals freedom:true, WebSocket */
/*jslint indent:2, white:true, node:true, sloppy:true, browser:true */

/**
 * Implementation of a Social provider that depends on
 * the WebSockets server code in server/router.py
 * The current implementation uses a public facing common server
 * hosted on p2pbr.com
 *
 * The provider offers
 * - A single global buddylist that everyone is on
 * - no reliability
 * - out of order delivery
 * - ephemeral userIds and clientIds
 * @class WSSocialProvider
 * @constructor
 * @param {Function} dispatchEvent callback to signal events
 * @param {WebSocket} webSocket Alternative webSocket implementation for tests
 **/
function WSSocialProvider(dispatchEvent, webSocket) {
  this.dispatchEvent = dispatchEvent;
  this.WS_URL = 'wss://p2pbr.com/route/';
  this.NETWORK_ID = 'websockets';
  var social = freedom.social();
  this.STATUS_NETWORK = social.STATUS_NETWORK;
  this.STATUS_CLIENT = social.STATUS_CLIENT;
  this.conn = null;   // Web Socket
  this.id = null;     // userId of this user
  this.roster = {};   // List of seen users

  this.provider = webSocket || WebSocket;

  setTimeout(this.sendStatus.bind(this, 'OFFLINE', 'offline'), 0);
}

/**
 * Connect to the Web Socket rendezvous server
 * e.g. social.login(Object options)
 * The only login option needed is 'agent', used to determine which group to join in the server
 *
 * @method login
 * @param {Object} loginOptions
 * @return {Object} status - Same schema as 'onStatus' events
 **/
WSSocialProvider.prototype.login = function(loginOpts, continuation) {
  var finishLogin = {
    finished: false,
    continuation: continuation,
    finish: function(msg) {
      if (this.continuation) {
        this.continuation(msg);
        delete this.continuation;
      }
    }
  };

  if (this.conn !== null) {
    console.warn("Already logged in");
    finishLogin.finish(this.sendStatus("ONLINE"));
    return;
  }
  this.conn = new this.provider(this.WS_URL + loginOpts.agent);
  // Save the continuation until we get a status message for
  // successful login.
  this.conn.onmessage = this.onMessage.bind(this, finishLogin);
  this.conn.onerror = function (cont, error) {
    this.conn = null;
    cont.finish(this.sendStatus('ERR_CONNECTION', error));
  }.bind(this, finishLogin);
  this.conn.onclose = function (cont, msg) {
    this.conn = null;
    cont.finish(this.sendStatus('OFFLINE', 'offline'));
  }.bind(this, finishLogin);

  this.sendStatus('CONNECTING', 'connecting');
};

/**
 * Returns all the <user card>s that we've seen so far (from 'onChange' events)
 * Note: the user's own <user card> will be somewhere in this list
 * All user cards will only consist of 1 client, where the clientId is the same as the userId
 * e.g. social.getRoster();
 *
 * @method getRoster
 * @return {Object} { List of <user cards> indexed by userId
 *    'userId1': <user card>,
 *    'userId2': <user card>,
 *     ...
 * }
 **/
WSSocialProvider.prototype.getRoster = function(continuation) {
  continuation(this.roster);
};

/**
 * Send a message to user on your network
 * If the destination is not specified or invalid, the message is dropped
 * Note: userId and clientId are the same for this provider
 * e.g. sendMessage(String destination_id, String message)
 *
 * @method sendMessage
 * @param {String} destination_id - target
 * @return nothing
 **/
WSSocialProvider.prototype.sendMessage = function(to, msg, continuation) {
  if (this.conn) {
    this.conn.send(JSON.stringify({to: to, msg: msg}));
  } else {
    console.error('WS Social Provider: trying to sendMessage when connection not established');
  }
  continuation();
};

/**
   * Disconnects from the Web Socket server
   * e.g. logout(Object options)
   * No options needed
   *
   * @method logout
   * @param {Object} logoutOptions
   * @return {Object} status - same schema as 'onStatus' events
   **/
WSSocialProvider.prototype.logout = function(logoutOpts, continuation) {
  if (this.conn === null) { // We may not have been logged in
    console.warn("Already logged out");
    continuation(this.sendStatus('OFFLINE', 'offline'));
    return;
  }
  this.conn.onclose = function(continuation) {
    this.conn = null;
    continuation(this.sendStatus('OFFLINE', 'offline'));
  }.bind(this, continuation);
  this.conn.close();
};

/**
 * INTERNAL METHODS
 **/

/**
 * Dispatch an 'onStatus' event with the following status
 *
 * @method sendStatus
 * @private
 * @param {String} stat - One of the error codes in STATUS_NETWORK
 * @param {String} message - Display message in the event
 * @return {Object} - same schema as 'onStatus' event
 **/
WSSocialProvider.prototype.sendStatus = function(stat, message) {
  var result = {
    network: this.NETWORK_ID,
    userId: this.id,
    clientId: this.id,
    status: this.STATUS_NETWORK[stat],
    message: message
  };
  this.dispatchEvent('onStatus', result);
  return result;
};

/**
 * Add the following ID to the roster
 * All users only have 1 client which is always messageable
 *
 * @method changeRoster
 * @private
 * @param {String} id - userId of user
 * @return nothing
 **/
WSSocialProvider.prototype.changeRoster = function(id, online) {
  //Keep track if we've actually made changes
  var sendChange = false,
      clients = {};
  //Create entry if not there
  if (!this.roster[id]) {
    sendChange = true;
    clients[id] = {
      clientId: id,
      network: this.NETWORK_ID,
      status: this.STATUS_CLIENT.MESSAGEABLE
    };
    this.roster[id] = {
      userId: id,
      name: id,
      clients: clients
    };
  }
  //Update online/offline status
  if (online && this.roster[id].clients[id].status !==
      this.STATUS_CLIENT.MESSAGEABLE) {
    this.roster[id].clients[id].status = this.STATUS_CLIENT.MESSAGEABLE;
    sendChange = true;
  } else if (!online && this.roster[id].clients[id].status !==
             this.STATUS_CLIENT.OFFLINE) {
    this.roster[id].clients[id].status = this.STATUS_CLIENT.OFFLINE;
    sendChange = true;
  }
  //Only dispatch change events if things have actually changed
  if (sendChange) {
    this.dispatchEvent('onChange', this.roster[id]);
  }
};

/**
 * Interpret messages from the server
 * There are 3 types of messages
 * - Directed messages from friends
 * - State information from the server on initialization
 * - Roster change events (users go online/offline)
 *
 * @method onMessage
 * @private
 * @param {Object} continuation Function to call upon successful login
 * @param {String} msg Message from the server (see server/router.py for schema)
 * @return nothing
 **/
WSSocialProvider.prototype.onMessage = function(continuation, msg) {
  var i;

  msg = JSON.parse(msg.data);
  // If state information from the server
  // Store my own ID and all known users at the time
  if (msg.cmd === 'state') {
    this.id = msg.id;
    this.changeRoster(this.id, true);
    for (i = 0; i < msg.msg.length; i += 1) {
      this.changeRoster(msg.msg[i], true);
    }

    if (!continuation.finished) {
      continuation.finish(this.sendStatus('ONLINE', 'online'));
    }
    // If directed message, emit event
  } else if (msg.cmd === 'message') {
    this.changeRoster(msg.from, true);
    this.dispatchEvent('onMessage', {
      fromUserId: msg.from,
      fromClientId: msg.from,
      toUserId: this.id,
      toClientId: this.id,
      network: this.NETWORK_ID,
      message: msg.msg
    });
  // Roster change event
  } else if (msg.cmd === 'roster') {
    this.changeRoster(msg.id, msg.online);
  // No idea what this message is, but let's keep track of who it's from
  } else if (msg.from) {
    this.changeRoster(msg.from, true);
  }
};

/** REGISTER PROVIDER **/
if (typeof freedom !== 'undefined') {
  freedom.social().provideAsynchronous(WSSocialProvider);
}
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: {
        app : './src/main/webapp/main.js',
        vendor : ['react', 'react-dom']
    },
    output: { path: __dirname + '/src/main/webapp/dist', filename: 'bundle.js' },
    devtool: 'source-map',
    module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js")
    ]
};
<commit_msg>UglifyJsPlugin<commit_after>var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: {
        app : './src/main/webapp/main.js',
        vendor : ['react', 'react-dom']
    },
    output: { path: __dirname + '/src/main/webapp/dist', filename: 'bundle.js' },
    devtool: 'source-map',
    module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js"),
        new webpack.optimize.UglifyJsPlugin()
    ]
};
<|endoftext|>


<commit_before>'use strict';

exports['date and time formatting'] = {

  setUp: function (callback) {
    var handlebars = require('handlebars');
    var helper = require('../helpers/date');
    handlebars.registerHelper('date', helper);
    this.handlebars = handlebars;
    callback();
  },

  tearDown: function (callback) {
    callback();
  },

  'date': function (test) {
    var template = '{{{date when}}}',
      context = {when: '1985-04-12T23:20:50.52Z'},
      html = this.handlebars.compile(template)(context).string;

    test.equals(html, 'Saturday, April 13, 1985');
    test.done();
  }

};
<commit_msg>Degrade timestamp resolution to avoid timezone issue<commit_after>'use strict';

exports['date and time formatting'] = {

  setUp: function (callback) {
    var handlebars = require('handlebars');
    var helper = require('../helpers/date');
    handlebars.registerHelper('date', helper);
    this.handlebars = handlebars;
    callback();
  },

  tearDown: function (callback) {
    callback();
  },

  'date': function (test) {
    var template = '{{{date when}}}',
      context = {when: '1985-04-12'},
      html = this.handlebars.compile(template)(context).string;

    test.equals(html, 'Friday, April 12, 1985');
    test.done();
  }

};
<|endoftext|>


<commit_before>/*Copyright 2016 Wipro Limited, NIIT Limited

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.

This code is written by Prateek Reddy Yammanuru, Shiva Manognya Kandikuppa, Uday Kumar Mydam, Nirup TNL, Sandeep Reddy G, Deepak Kumar
 and updated by Ashish Gupta, Tarun Mohandas, Suriya Prakash, Srinivasa Burli, Jishnu Surendran and Bhairavi Balakrishnan*/

angular.module('logAggregator').controller('mainController', ['$scope','$cookies','$rootScope', '$window','$http','$location', 'loadConfig','$state',
'$timeout',function($scope,$cookies,$rootScope, $window,$http,$location, loadConfig, $state,$timeout ) {
      loadConfig.getdata( function(data) {
        $scope.config = data;
        $window.config = $scope.config;
      });

      $scope.aptLogTabs=['Request Rate','Data Rate','Package Count','Package Analytics','Package Repository'];
      $scope.nginxLogTabs=['Log Listing','User Agent','Traffic Rate'];

      $scope.setTab = function(logName){
        var presentRoute=$location.$$path.split("/");
        var stateToGo = logName.split(" ").join("")+"."+presentRoute[2];
        $timeout(function() {
          $state.go(stateToGo);
        },1);
      }

      $scope.dashName = "Dashboard";

    $scope.setDashName = function(val){
      $scope.dashName = val;
    }

    // $scope.setSelection=function(selection_name){
    //     $scope.selection = selection_name;
    // }

    $scope.aboutus=function(){
      var watchlist=document.getElementsByClassName('watchlist-tabs');
      angular.element(watchlist).css('display','none');
      $location.path('/aboutus');
    }

    if($cookies.get('login')==='true'){
      var result=document.getElementsByClassName('homepage');
      angular.element(result).css('display','block');
      $location.path($location.path());
    }
    else{
    $cookies.put("login",'false');
  }
    $scope.showContent=false;
    $scope.logout=function(){
      $rootScope.loginMessage="";
      $rootScope.checkData="";
   $http.get('/auth/signout').then(function(response){
      var result=document.getElementsByClassName('homepage');
      angular.element(result).css('display','none');
      $rootScope.tab="";
      $cookies.remove('login');
      $location.path('/login');
    });
    }
  }
]);
<commit_msg>solving the logout prolem<commit_after>/*Copyright 2016 Wipro Limited, NIIT Limited

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.

This code is written by Prateek Reddy Yammanuru, Shiva Manognya Kandikuppa, Uday Kumar Mydam, Nirup TNL, Sandeep Reddy G, Deepak Kumar
 and updated by Ashish Gupta, Tarun Mohandas, Suriya Prakash, Srinivasa Burli, Jishnu Surendran and Bhairavi Balakrishnan*/

angular.module('logAggregator').controller('mainController', ['$scope','$cookies','$rootScope', '$window','$http','$location', 'loadConfig','$state',
'$timeout',function($scope,$cookies,$rootScope, $window,$http,$location, loadConfig, $state,$timeout ) {
      loadConfig.getdata( function(data) {
        $scope.config = data;
        $window.config = $scope.config;
      });

      $scope.aptLogTabs=['Request Rate','Data Rate','Package Count','Package Analytics','Package Repository'];
      $scope.nginxLogTabs=['Log Listing','User Agent','Traffic Rate'];

      $scope.setTab = function(logName){
        var presentRoute=$location.$$path.split("/");
        var stateToGo = logName.split(" ").join("")+"."+presentRoute[2];
        $timeout(function() {
          $state.go(stateToGo);
        },1);
      }

      $scope.dashName = "Dashboard";

    $scope.setDashName = function(val){
      $scope.dashName = val;
    }

    // $scope.setSelection=function(selection_name){
    //     $scope.selection = selection_name;
    // }

    $scope.aboutus=function(){
      var watchlist=document.getElementsByClassName('watchlist-tabs');
      angular.element(watchlist).css('display','none');
      $location.path('/aboutus');
    }

    if($cookies.get('login')==='true'){
      var result=document.getElementsByClassName('homepage');
      angular.element(result).css('display','block');
      $location.path($location.path());
    }
    else{
    $cookies.put("login",'false');
  }
    $scope.showContent=false;
    $scope.logout=function(){
      $rootScope.loginMessage="";
      $rootScope.checkData="";
      $http.get('/auth/signout').then(function(response){
        var result=document.getElementsByClassName('homepage');
        angular.element(result).css('display','none');
        $rootScope.tab="";
        $cookies.remove('login');
        $location.path('/login');
        $window.location.reload();
      });
    }
  }
]);
<|endoftext|>


<commit_before>/* global __dirname */

const process = require('process');
const { ProvidePlugin } = require('webpack');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = (minimize, analyzeBundle) => {
    return {
        // The inline-source-map is used to allow debugging the unit tests with Karma
        devtool: minimize ? 'source-map' : 'inline-source-map',
        resolve: {
            extensions: [ '', '.js', '.ts' ]
        },
        mode: minimize ? 'production' : 'development',
        module: {
            rules: [ {
                // Version this build of the lib-jitsi-meet library.

                loader: 'string-replace-loader',
                options: {
                    flags: 'g',
                    replace:
                        process.env.LIB_JITSI_MEET_COMMIT_HASH || 'development',
                    search: '{#COMMIT_HASH#}'
                },
                test: `${__dirname}/JitsiMeetJS.js`
            }, {
                // Transpile ES2015 (aka ES6) to ES5.

                exclude: [
                    new RegExp(`${__dirname}/node_modules/(?!@jitsi/js-utils)`)
                ],
                loader: 'babel-loader',
                options: {
                    presets: [
                        [
                            '@babel/preset-env',

                            // Tell babel to avoid compiling imports into CommonJS
                            // so that webpack may do tree shaking.
                            {
                                modules: false,

                                // Specify our target browsers so no transpiling is
                                // done unnecessarily. For browsers not specified
                                // here, the ES2015+ profile will be used.
                                targets: {
                                    chrome: 80,
                                    electron: 10,
                                    firefox: 68,
                                    safari: 14
                                }
                            }
                        ],
                        '@babel/preset-typescript'
                    ]
                },
                test: /\.(js|ts)$/
            } ]
        },
        node: {
            // Allow the use of the real filename of the module being executed. By
            // default Webpack does not leak path-related information and provides a
            // value that is a mock (/index.js).
            __filename: true
        },
        optimization: {
            concatenateModules: minimize
        },
        output: {
            filename: `[name]${minimize ? '.min' : ''}.js`,
            sourceMapFilename: `[name].${minimize ? 'min' : 'js'}.map`
        },
        performance: {
            hints: minimize ? 'error' : false,
            maxAssetSize: 750 * 1024,
            maxEntrypointSize: 750 * 1024
        },
        plugins: [
            analyzeBundle
                && new BundleAnalyzerPlugin({
                    analyzerMode: 'disabled',
                    generateStatsFile: true
                }),
            !minimize
                && new ProvidePlugin({
                    process: 'process/browser'
                })
        ].filter(Boolean)
    };
};
<commit_msg>fix(build) use path.join in webpack-shared.config<commit_after>/* global __dirname */

const path = require('path');
const process = require('process');
const { ProvidePlugin } = require('webpack');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = (minimize, analyzeBundle) => {
    return {
        // The inline-source-map is used to allow debugging the unit tests with Karma
        devtool: minimize ? 'source-map' : 'inline-source-map',
        resolve: {
            extensions: [ '', '.js', '.ts' ]
        },
        mode: minimize ? 'production' : 'development',
        module: {
            rules: [ {
                // Version this build of the lib-jitsi-meet library.

                loader: 'string-replace-loader',
                options: {
                    flags: 'g',
                    replace:
                        process.env.LIB_JITSI_MEET_COMMIT_HASH || 'development',
                    search: '{#COMMIT_HASH#}'
                },
                test: path.join(__dirname, 'JitsiMeetJS.js')
            }, {
                // Transpile ES2015 (aka ES6) to ES5.

                exclude: [
                    new RegExp(`${__dirname}/node_modules/(?!@jitsi/js-utils)`)
                ],
                loader: 'babel-loader',
                options: {
                    presets: [
                        [
                            '@babel/preset-env',

                            // Tell babel to avoid compiling imports into CommonJS
                            // so that webpack may do tree shaking.
                            {
                                modules: false,

                                // Specify our target browsers so no transpiling is
                                // done unnecessarily. For browsers not specified
                                // here, the ES2015+ profile will be used.
                                targets: {
                                    chrome: 80,
                                    electron: 10,
                                    firefox: 68,
                                    safari: 14
                                }
                            }
                        ],
                        '@babel/preset-typescript'
                    ]
                },
                test: /\.(js|ts)$/
            } ]
        },
        node: {
            // Allow the use of the real filename of the module being executed. By
            // default Webpack does not leak path-related information and provides a
            // value that is a mock (/index.js).
            __filename: true
        },
        optimization: {
            concatenateModules: minimize
        },
        output: {
            filename: `[name]${minimize ? '.min' : ''}.js`,
            sourceMapFilename: `[name].${minimize ? 'min' : 'js'}.map`
        },
        performance: {
            hints: minimize ? 'error' : false,
            maxAssetSize: 750 * 1024,
            maxEntrypointSize: 750 * 1024
        },
        plugins: [
            analyzeBundle
                && new BundleAnalyzerPlugin({
                    analyzerMode: 'disabled',
                    generateStatsFile: true
                }),
            !minimize
                && new ProvidePlugin({
                    process: 'process/browser'
                })
        ].filter(Boolean)
    };
};
<|endoftext|>


<commit_before>/**
 * Yobi, Project Hosting SW
 *
 * Copyright 2012 NAVER Corp.
 * http://yobi.io
 *
 * @Author Hwi Ahn
 *
 * 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.
 */
(function(ns){

    var oNS = $yobi.createNamespace(ns);
    oNS.container[oNS.name] = function(htOptions){

        var htVar = {};
        var htElement = {};

        function _init(htOptions){
            _initVar();
            _initElement(htOptions);
            _attachEvent();
            _focusOnFirstField();

            _showErrors(htOptions.htError);
        }

        /**
         * initialize variables
         */
        function _initVar(){
            htVar.rxPrjName = /^[0-9A-Za-z-_\.]+$/;
            htVar.aReservedWords = [".", "..", ".git"];
        }

        /**
         * initialize element
         */
        function _initElement(htOptions){
            htElement.welForm = $(htOptions.sFormId);
            htElement.welInputProjectName = $("#project-name");
            htElement.welInputProjectOwner = $("#project-owner");
            htElement.welInputGitRepoURL = $("#url");

            htElement.vcsSelect = $("#vcs");
            htElement.svnWarning = $("#svn");
            htElement.welProtected = $("#opt-protected");

            htElement.welRepoAuthCheck = $("#useRepoAuth");
            htElement.welRepoAuthWrap = $("#repoAuth");
            htElement.waRepoAuthInput = htElement.welRepoAuthWrap.find("input");
        }

        /**
         * attach event handler
         */
        function _attachEvent(){
            htElement.vcsSelect.on("change", _onChangeVCSItem);
            htElement.welInputProjectOwner.on("change", _onChangeProjectOwner);
            htElement.welForm.on("submit", _validateForm);
            htElement.welRepoAuthCheck.on("change", _onChangeRepoAuthCheck);
        }

        function _onChangeRepoAuthCheck(){
            $("input").popover("destroy");
            htElement.welRepoAuthWrap.toggle("slide");
            htElement.waRepoAuthInput.attr("disabled", !htElement.welRepoAuthCheck.is(":checked"));
        }

        function _onChangeVCSItem(evt){
            if(evt.val.toUpperCase() === "SUBVERSION"){
                htElement.svnWarning.show();
                $('#menuSettingPullRequest')
                    .prop('checked', false)
                    .parent('label').hide();
            } else {
                htElement.svnWarning.hide();
                $('#menuSettingPullRequest')
                    .prop('checked', true)
                    .parent('label').show();
            }
        }

        function _onChangeProjectOwner() {
            var sType = $("#project-owner option:selected").data("type");

            if (sType == "user") {
                if ($("#protected").is(":checked")) {
                    $("#public").prop("checked", true);
                }
                htElement.welProtected.hide();
            } else {
                htElement.welProtected.show();
            }
        }

        function _focusOnFirstField(){
            if(htElement.welRepoAuthCheck.is(":checked")){
                htElement.waRepoAuthInput.get(0).focus();
            } else if(htElement.welInputGitRepoURL.length > 0){
                htElement.welInputGitRepoURL.focus();
            } else {
                htElement.welInputProjectName.focus();
            }
        }

        /**
         * Validate form on submit
         *
         * @private
         */
        function _validateForm(evt){
            var error = {};
            var projectName = htElement.welInputProjectName.val();

            if(projectName.length === 0){
                error.name = error.name || [];
                error.name.push(Messages("project.name.alert"));
            }

            if(!htVar.rxPrjName.test(projectName)){
                error.name = error.name || [];
                error.name.push(Messages("project.name.alert"));
            }

            if(htVar.aReservedWords.indexOf(projectName) > -1){
                error.name = error.name || [];
                error.name.push(Messages("project.name.reserved.alert"));
            }

            if(htElement.welInputGitRepoURL.length > 0 &&
               htElement.welInputGitRepoURL.val().trim().length === 0 ){
                error.url = error.url || [];
                error.url.push(Messages("project.import.error.empty.url"));
            }

            if(!$.isEmptyObject(error)){
                _showErrors(error);
                evt.preventDefault();
                return false;
            }

            yobi.ui.Spinner.show();
        }

        /**
         * Show error message on target element with $.popover
         *
         * @param error
         * @private
         */
        function _showErrors(error){
            if(!error){
                return;
            }

            var targetElement;

            for(var target in error){
                targetElement = htElement.welForm.find("[name=" + target + "]");

                if(targetElement.length > 0) {
                    targetElement.popover({
                        "trigger"  : "manual",
                        "placement": "left",
                        "content"  : error[target].shift()
                    }).popover("show");
                }
            }
        }

        _init(htOptions || {});
    };

})("yobi.project.New");
<commit_msg>Project: pullrequest menu default checked when create svn project<commit_after>/**
 * Yobi, Project Hosting SW
 *
 * Copyright 2012 NAVER Corp.
 * http://yobi.io
 *
 * @Author Hwi Ahn
 *
 * 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.
 */
(function(ns){

    var oNS = $yobi.createNamespace(ns);
    oNS.container[oNS.name] = function(htOptions){

        var htVar = {};
        var htElement = {};

        function _init(htOptions){
            _initVar();
            _initElement(htOptions);
            _attachEvent();
            _focusOnFirstField();

            _showErrors(htOptions.htError);
        }

        /**
         * initialize variables
         */
        function _initVar(){
            htVar.rxPrjName = /^[0-9A-Za-z-_\.]+$/;
            htVar.aReservedWords = [".", "..", ".git"];
        }

        /**
         * initialize element
         */
        function _initElement(htOptions){
            htElement.welForm = $(htOptions.sFormId);
            htElement.welInputProjectName = $("#project-name");
            htElement.welInputProjectOwner = $("#project-owner");
            htElement.welInputGitRepoURL = $("#url");

            htElement.vcsSelect = $("#vcs");
            htElement.svnWarning = $("#svn");
            htElement.welProtected = $("#opt-protected");

            htElement.welRepoAuthCheck = $("#useRepoAuth");
            htElement.welRepoAuthWrap = $("#repoAuth");
            htElement.waRepoAuthInput = htElement.welRepoAuthWrap.find("input");
        }

        /**
         * attach event handler
         */
        function _attachEvent(){
            htElement.vcsSelect.on("change", _onChangeVCSItem);
            htElement.welInputProjectOwner.on("change", _onChangeProjectOwner);
            htElement.welForm.on("submit", _validateForm);
            htElement.welRepoAuthCheck.on("change", _onChangeRepoAuthCheck);
        }

        function _onChangeRepoAuthCheck(){
            $("input").popover("destroy");
            htElement.welRepoAuthWrap.toggle("slide");
            htElement.waRepoAuthInput.attr("disabled", !htElement.welRepoAuthCheck.is(":checked"));
        }

        function _onChangeVCSItem(evt){
            if(evt.val.toUpperCase() === "SUBVERSION"){
                htElement.svnWarning.show();
                /**
                 * We don't know whether the user want to check this or not
                 * because this checkbox will be hidden. So we let it be true
                 * forcely. It may be misguessing of the user's choice but it
                 * prevents the possibiltiy that the user never knows the
                 * existence of PullRequest feature when the user changes the
                 * project setting to use Git.
                 */
                $('#menuSettingPullRequest')
                    .prop('checked', true)
                    .parent('label').hide();
            } else {
                htElement.svnWarning.hide();
                $('#menuSettingPullRequest')
                    .prop('checked', true)
                    .parent('label').show();
            }
        }

        function _onChangeProjectOwner() {
            var sType = $("#project-owner option:selected").data("type");

            if (sType == "user") {
                if ($("#protected").is(":checked")) {
                    $("#public").prop("checked", true);
                }
                htElement.welProtected.hide();
            } else {
                htElement.welProtected.show();
            }
        }

        function _focusOnFirstField(){
            if(htElement.welRepoAuthCheck.is(":checked")){
                htElement.waRepoAuthInput.get(0).focus();
            } else if(htElement.welInputGitRepoURL.length > 0){
                htElement.welInputGitRepoURL.focus();
            } else {
                htElement.welInputProjectName.focus();
            }
        }

        /**
         * Validate form on submit
         *
         * @private
         */
        function _validateForm(evt){
            var error = {};
            var projectName = htElement.welInputProjectName.val();

            if(projectName.length === 0){
                error.name = error.name || [];
                error.name.push(Messages("project.name.alert"));
            }

            if(!htVar.rxPrjName.test(projectName)){
                error.name = error.name || [];
                error.name.push(Messages("project.name.alert"));
            }

            if(htVar.aReservedWords.indexOf(projectName) > -1){
                error.name = error.name || [];
                error.name.push(Messages("project.name.reserved.alert"));
            }

            if(htElement.welInputGitRepoURL.length > 0 &&
               htElement.welInputGitRepoURL.val().trim().length === 0 ){
                error.url = error.url || [];
                error.url.push(Messages("project.import.error.empty.url"));
            }

            if(!$.isEmptyObject(error)){
                _showErrors(error);
                evt.preventDefault();
                return false;
            }

            yobi.ui.Spinner.show();
        }

        /**
         * Show error message on target element with $.popover
         *
         * @param error
         * @private
         */
        function _showErrors(error){
            if(!error){
                return;
            }

            var targetElement;

            for(var target in error){
                targetElement = htElement.welForm.find("[name=" + target + "]");

                if(targetElement.length > 0) {
                    targetElement.popover({
                        "trigger"  : "manual",
                        "placement": "left",
                        "content"  : error[target].shift()
                    }).popover("show");
                }
            }
        }

        _init(htOptions || {});
    };

})("yobi.project.New");
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = function (env) {
  return {
    debug: env !== 'prod',
    entry: {
      main: abspath('src', 'app', 'main.ts'),
      vendor: abspath('src', 'app', 'vendor.ts')
    },
    output: {
      path: abspath('dist'),
      filename: path.join('app', '[name].bundle.js'),
      sourceMapFilename: '[file].map'
    },
    resolve: {
      extensions: ['', '.ts', '.js']
    },
    module: {
      loaders: [
        {test: /\.html$/, loader: 'html'},
        {test: /\.jade$/, loader: 'html!jade?+static'},
        {test: /\.json$/, loader: 'json'},
        {test: /\.styl$/, loader: ExtractTextPlugin.extract('style', 'css?sourceMap!stylus')},
        {test: /\.ts$/, loader: 'ts'}
      ],
      noParse: [
        path.join(__dirname, 'node_modules', 'angular2', 'bundles')
      ]
    },
    plugins: [
      new webpack.optimize.OccurenceOrderPlugin(true),
      new webpack.optimize.CommonsChunkPlugin('vendor', path.join('app', 'vendor.bundle.js')),
      new ExtractTextPlugin(path.join('app', 'main.bundle.css')),
      new HtmlWebpackPlugin({
        template: abspath('src', 'index.jade'),
        inject: 'body'
      })
    ]
  }
};

function abspath() {
  var args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}
<commit_msg>コードを整理<commit_after>var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = function (env) {
  return {
    debug: env !== 'prod',
    entry: {
      main: path.join(__dirname, 'src', 'app', 'main.ts'),
      vendor: path.join(__dirname, 'src', 'app', 'vendor.ts')
    },
    output: {
      path: path.join(__dirname, 'dist'),
      filename: path.join('app', '[name].bundle.js'),
      sourceMapFilename: '[file].map'
    },
    resolve: {
      extensions: ['', '.ts', '.js']
    },
    module: {
      loaders: [
        {test: /\.html$/, loader: 'html'},
        {test: /\.jade$/, loader: 'html!jade?+static'},
        {test: /\.json$/, loader: 'json'},
        {test: /\.styl$/, loader: ExtractTextPlugin.extract('style', 'css?sourceMap!stylus')},
        {test: /\.ts$/, loader: 'ts'}
      ],
      noParse: [
        path.join(__dirname, 'node_modules', 'angular2', 'bundles')
      ]
    },
    plugins: [
      new webpack.optimize.OccurenceOrderPlugin(true),
      new webpack.optimize.CommonsChunkPlugin('vendor', path.join('app', 'vendor.bundle.js')),
      new ExtractTextPlugin(path.join('app', 'main.bundle.css')),
      new HtmlWebpackPlugin({
        template: path.join(__dirname, 'src', 'index.jade'),
        inject: 'body'
      })
    ]
  }
};
<|endoftext|>


<commit_before>const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const TimerPlugin = require('./timer-plugin');
const path = require('path');

const BUILD_PREFIX = '.sambell';
const getBuildDir = scope => path.join(BUILD_PREFIX, scope);

module.exports = (target = 'web', env = 'dev') => {
  const IS_NODE = target === 'node';
  const IS_WEB = target === 'web';

  const IS_PROD = env === 'prod';
  const IS_DEV = env === 'dev';
  process.env.NODE_ENV = IS_PROD ? 'production' : 'development';

  const SERVER_ENTRY = 'server';
  const CLIENT_ENTRY = 'client';
  const scope = IS_NODE ? SERVER_ENTRY : CLIENT_ENTRY;

  const buildDir = getBuildDir(scope);

  let config = {
    target: target,
    context: process.cwd(),
    entry: {
      run: [
        require.resolve('babel-polyfill'),
        require.resolve(`isomorphic-fetch/fetch-npm-${IS_NODE ? 'node' : 'browserify'}`),
        IS_NODE ? 'source-map-support/register' : null,
        scope,
      ].filter(x => x),
    },

    output: {
      path: path.resolve(process.cwd(), buildDir),
      publicPath: '/static/webpack/',
      filename: `${IS_WEB && IS_PROD ? '[hash].' : ''}[name].js`,
      chunkFilename: `${IS_WEB && IS_PROD ? '[chunkhash].' : ''}[id].[name].js`,
    },

    resolve: {
      modules: [
        process.cwd(),
        path.resolve(process.cwd(), 'node_modules'),
      ],
    },

    module: {
      rules: [
        {
          test: /\.js$/,
          loader: require.resolve('babel-loader'),
          options: {
            babelrc: false,
            presets: [
              require.resolve('babel-preset-es2015'),
              require.resolve('babel-preset-stage-1'),
              require.resolve('babel-preset-react'),
            ],
            plugins: [
              require.resolve('styled-jsx/babel'),
              [
                require.resolve('babel-plugin-module-resolver'),
                {
                  alias: {
                    'sambell/env': path.resolve(__dirname, 'sambell-env'),
                  },
                },
              ],
            ],
          },
        },
      ],

      exprContextCritical: false,
    },

    plugins: [
      IS_WEB ? new webpack.DefinePlugin({
        "process.env": {
          NODE_ENV: JSON.stringify(process.env.NODE_ENV)
        },
      }) : null,

      IS_WEB && IS_PROD ? new webpack.optimize.UglifyJsPlugin({
        compress: { screw_ie8: true, warnings: false },
        mangle: { screw_ie8: true },
        output: { comments: false, screw_ie8: true },
        sourceMap: false
      }) : null,

      IS_WEB && IS_PROD ? new webpack.optimize.AggressiveMergingPlugin() : null,
    ].filter(a => a),

    performance: { hints: false },
    devtool: IS_DEV ? 'cheap-module-source-map' :
      IS_NODE ? 'cheap-source-map' : false,
  };

  if (IS_NODE) {
    config.externals = [nodeExternals()];
    config.node = { console: true, __filename: true, __dirname: true };
  } else {
    config.node = { fs: 'empty', net: 'empty', tls: 'empty' };
  }

  let gerty = {};
  try { gerty = require(path.resolve(process.cwd(), 'gerty')); } catch (e) {}
  if (gerty.webpack) config = gerty.webpack(config, { node: IS_NODE, dev: IS_DEV }, webpack);

  config.plugins = [
    ...config.plugins,
    new TimerPlugin(),
    new webpack.DefinePlugin({
      SAMBELL_CLIENT_OUTPUT_DIR: JSON.stringify(getBuildDir(CLIENT_ENTRY)),
      SAMBELL_PUBLIC_PATH: JSON.stringify(config.output.publicPath),
    }),
  ];

  return config;
};
<commit_msg>require resolve<commit_after>const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const TimerPlugin = require('./timer-plugin');
const path = require('path');

const BUILD_PREFIX = '.sambell';
const getBuildDir = scope => path.join(BUILD_PREFIX, scope);

module.exports = (target = 'web', env = 'dev') => {
  const IS_NODE = target === 'node';
  const IS_WEB = target === 'web';

  const IS_PROD = env === 'prod';
  const IS_DEV = env === 'dev';
  process.env.NODE_ENV = IS_PROD ? 'production' : 'development';

  const SERVER_ENTRY = 'server';
  const CLIENT_ENTRY = 'client';
  const scope = IS_NODE ? SERVER_ENTRY : CLIENT_ENTRY;

  const buildDir = getBuildDir(scope);

  let config = {
    target: target,
    context: process.cwd(),
    entry: {
      run: [
        require.resolve('babel-polyfill'),
        require.resolve(`isomorphic-fetch/fetch-npm-${IS_NODE ? 'node' : 'browserify'}`),
        IS_NODE ? require.resolve('source-map-support/register') : null,
        scope,
      ].filter(x => x),
    },

    output: {
      path: path.resolve(process.cwd(), buildDir),
      publicPath: '/static/webpack/',
      filename: `${IS_WEB && IS_PROD ? '[hash].' : ''}[name].js`,
      chunkFilename: `${IS_WEB && IS_PROD ? '[chunkhash].' : ''}[id].[name].js`,
    },

    resolve: {
      modules: [
        process.cwd(),
        path.resolve(process.cwd(), 'node_modules'),
      ],
    },

    module: {
      rules: [
        {
          test: /\.js$/,
          loader: require.resolve('babel-loader'),
          options: {
            babelrc: false,
            presets: [
              require.resolve('babel-preset-es2015'),
              require.resolve('babel-preset-stage-1'),
              require.resolve('babel-preset-react'),
            ],
            plugins: [
              require.resolve('styled-jsx/babel'),
              [
                require.resolve('babel-plugin-module-resolver'),
                {
                  alias: {
                    'sambell/env': path.resolve(__dirname, 'sambell-env'),
                  },
                },
              ],
            ],
          },
        },
      ],

      exprContextCritical: false,
    },

    plugins: [
      IS_WEB ? new webpack.DefinePlugin({
        "process.env": {
          NODE_ENV: JSON.stringify(process.env.NODE_ENV)
        },
      }) : null,

      IS_WEB && IS_PROD ? new webpack.optimize.UglifyJsPlugin({
        compress: { screw_ie8: true, warnings: false },
        mangle: { screw_ie8: true },
        output: { comments: false, screw_ie8: true },
        sourceMap: false
      }) : null,

      IS_WEB && IS_PROD ? new webpack.optimize.AggressiveMergingPlugin() : null,
    ].filter(a => a),

    performance: { hints: false },
    devtool: IS_DEV ? 'cheap-module-source-map' :
      IS_NODE ? 'cheap-source-map' : false,
  };

  if (IS_NODE) {
    config.externals = [nodeExternals()];
    config.node = { console: true, __filename: true, __dirname: true };
  } else {
    config.node = { fs: 'empty', net: 'empty', tls: 'empty' };
  }

  let gerty = {};
  try { gerty = require(path.resolve(process.cwd(), 'gerty')); } catch (e) {}
  if (gerty.webpack) config = gerty.webpack(config, { node: IS_NODE, dev: IS_DEV }, webpack);

  config.plugins = [
    ...config.plugins,
    new TimerPlugin(),
    new webpack.DefinePlugin({
      SAMBELL_CLIENT_OUTPUT_DIR: JSON.stringify(getBuildDir(CLIENT_ENTRY)),
      SAMBELL_PUBLIC_PATH: JSON.stringify(config.output.publicPath),
    }),
  ];

  return config;
};
<|endoftext|>


<commit_before>
var socket;
var measurement_data = [];
var start, end, time;
var startTime = new Date();
var wattSum = 0;
var totalCost = 0;

function connect(source){
	console.log("Tjena boys");
	start = new Date().getTime();
	socket = io.connect(source);
	socket.on('connect', function () {
	    socket.on('mqtt', function (msg) {
			check(msg);
			getDaily(msg);
	    });
	});
	socket.emit('subscribe',{topic:'/some/sensor/data'});
}

function measurement_storage(msg, date){

	measurement_data.push(
		{"buildingwatt": msg.payload, "date": date}
		);
}

function check(msg){
	if(msg.topic == 'buildingWatt'){

		end = new Date().getTime();
		time = end-start;
		start = end;
		wattSum += msg.payload;

		//setTotalCost(money_converter(wattSum));
		console.log(" KWH: " + (wattSum*((new Date()).getTime() - startTime.getTime())/(3600 * 1000))/1000);
		//measurement_storage(msg, new Date());
		//console.log(msg.topic+' '+msg.payload+', time elapsed:'+time+', Date:'+new Date());
		//console.log("size: " + measurement_data.length + " buildingwatt: " + measurement_data[measurement_data.length-1]["buildingwatt"] + " Date: " + measurement_data[measurement_data.length-1]["date"] + " KWH: " + wattSum/1000);
	}
}

function getDaily(msg){
	if(msg.topic == 'Daily')
		console.log("Topic: " + msg.topic + " Payload: " + msg.payload);
}

//Sets the cost amount. It also checks weather of not the new cost has become greater that the previous total,
//And starts the drop coins.
function setTotalCost(cost){
	if(Math.floor(totalCost) < Math.floor(cost)){
		dropCoins(Math.floor(cost)-Math.floor(totalCost));
	}

	totalCost = cost;
	//Do code Set the cost of the HTML element...
}

//Make The coins in the movie fall down. starts and pauses the video at the right places.
function dropCoins(amount){
	//Do the drop coins code.
	var video = document.getElementById("video");
	var nextPause = 100;
	video.start();
	video.addEventListener("timeupdate", function(){
	    if(this.currentTime >=  nextPause) {
	        this.pause();
	    }
	});
}

//Takes the total amount of watt and converts it to the amount of money it costs.
function money_converter(totalwatt){

	var priceKWH = document.getElementById("price").value;
	var cost = 0;
	console.log("THe price: " + priceKWH);
	if(priceKWH > 0){
		cost = (totalwatt / (1000*900)) * priceKWH;//Vet inte om denna conversion är rätt men lägg en kik.
	}else{
		alert("Type in your price for kwh in the settings section, down to the left under the video.");
	}
	return cost;
}

<commit_msg>in connection.js<commit_after>
var socket;
var measurement_data = [];
var start, end, time;
var startTime = new Date();
var wattSum = 0;
var totalCost = 0;

function connect(source){
	console.log("Tjena boys");
	start = new Date().getTime();
	socket = io.connect(source);
	socket.on('connect', function () {
	    socket.on('mqtt', function (msg) {
			check(msg);
			getDaily(msg);
	    });
	});
	socket.emit('subscribe',{topic:'/some/sensor/data'});
}

function measurement_storage(msg, date){

	measurement_data.push(
		{"buildingwatt": msg.payload, "date": date}
		);
}

function check(msg){
	if(msg.topic == 'buildingWatt'){

		end = new Date().getTime();
		time = end-start;
		start = end;
		wattSum += msg.payload;

		//setTotalCost(money_converter(wattSum));
		console.log(" KWH: " + (wattSum*((new Date()).getTime() - startTime.getTime())/(3600 * 1000))/1000);
		//measurement_storage(msg, new Date());
		//console.log(msg.topic+' '+msg.payload+', time elapsed:'+time+', Date:'+new Date());
		//console.log("size: " + measurement_data.length + " buildingwatt: " + measurement_data[measurement_data.length-1]["buildingwatt"] + " Date: " + measurement_data[measurement_data.length-1]["date"] + " KWH: " + wattSum/1000);
	}
}

function getDaily(msg){
	if(msg.topic == 'VideoFeedbackDaily')
		console.log("Topic: " + msg.topic + " Payload: " + msg.payload);
}

//Sets the cost amount. It also checks weather of not the new cost has become greater that the previous total,
//And starts the drop coins.
function setTotalCost(cost){
	if(Math.floor(totalCost) < Math.floor(cost)){
		dropCoins(Math.floor(cost)-Math.floor(totalCost));
	}

	totalCost = cost;
	//Do code Set the cost of the HTML element...
}

//Make The coins in the movie fall down. starts and pauses the video at the right places.
function dropCoins(amount){
	//Do the drop coins code.
	var video = document.getElementById("video");
	var nextPause = 100;
	video.start();
	video.addEventListener("timeupdate", function(){
	    if(this.currentTime >=  nextPause) {
	        this.pause();
	    }
	});
}

//Takes the total amount of watt and converts it to the amount of money it costs.
function money_converter(totalwatt){

	var priceKWH = document.getElementById("price").value;
	var cost = 0;
	console.log("THe price: " + priceKWH);
	if(priceKWH > 0){
		cost = (totalwatt / (1000*900)) * priceKWH;//Vet inte om denna conversion är rätt men lägg en kik.
	}else{
		alert("Type in your price for kwh in the settings section, down to the left under the video.");
	}
	return cost;
}

<|endoftext|>


<commit_before>import GL from '@luma.gl/constants';
import {log} from '@luma.gl/gltools';
import Accessor from './accessor';
import Buffer from './buffer';
import VertexArrayObject from './vertex-array-object';
import {assert, stubRemovedMethods} from '../utils';

const ERR_ATTRIBUTE_TYPE =
  'VertexArray: attributes must be Buffers or constants (i.e. typed array)';

// This is done to support mat type attributes.
// See section "Notes about setting mat type attributes"
// in vertex-array.md
const MULTI_LOCATION_ATTRIBUTE_REGEXP = /^(.+)__LOCATION_([0-9]+)$/;

const DEPRECATIONS_V6 = [
  'setBuffers',
  'setGeneric',
  'clearBindings',
  'setLocations',
  'setGenericValues',
  'setDivisor',
  'enable',
  'disable'
];

export default class VertexArray {
  constructor(gl, opts = {}) {
    // Use program's id if program is supplied but no id is supplied
    const id = opts.id || (opts.program && opts.program.id);
    // super(gl, Object.assign({}, opts, {id}));

    this.id = id;
    this.gl = gl;
    this.configuration = null;

    // Extracted information
    this.elements = null;
    this.elementsAccessor = null;
    this.values = null;
    this.accessors = null;
    this.unused = null;
    this.drawParams = null;
    this.buffer = null; // For attribute 0 on desktops, and created when unbinding buffers

    this.attributes = {};

    this.vertexArrayObject = new VertexArrayObject(gl);

    // Issue errors when using removed methods
    stubRemovedMethods(this, 'VertexArray', 'v6.0', DEPRECATIONS_V6);

    this.initialize(opts);
    Object.seal(this);
  }

  delete() {
    if (this.buffer) {
      this.buffer.delete();
    }
  }

  initialize(props = {}) {
    this.reset();
    this.configuration = null;
    this.bindOnUse = false;
    return this.setProps(props);
  }

  // Resets all attributes (to default valued constants)
  reset() {
    // this.vertexArrayObject.reset();

    this.elements = null;
    this.elementsAccessor = null;
    const {MAX_ATTRIBUTES} = this.vertexArrayObject;
    this.values = new Array(MAX_ATTRIBUTES).fill(null);
    this.accessors = new Array(MAX_ATTRIBUTES).fill(null);
    this.unused = {};

    // Auto detects draw params
    this.drawParams = null;

    return this;
  }

  setProps(props) {
    if ('program' in props) {
      this.configuration = props.program && props.program.configuration;
    }
    if ('configuration' in props) {
      this.configuration = props.configuration;
    }
    if ('attributes' in props) {
      this.setAttributes(props.attributes);
    }
    if ('elements' in props) {
      this.setElementBuffer(props.elements);
    }
    if ('bindOnUse' in props) {
      props = props.bindOnUse;
    }
    return this;
  }

  // Automatically called if buffers changed through VertexArray API
  clearDrawParams() {
    this.drawParams = null;
  }

  getDrawParams() {
    // Auto deduced draw parameters
    this.drawParams = this.drawParams || this._updateDrawParams();

    return this.drawParams;
  }

  // Set (bind) an array or map of vertex array buffers, either in numbered or named locations.
  // For names that are not present in `location`, the supplied buffers will be ignored.
  // if a single buffer of type GL.ELEMENT_ARRAY_BUFFER is present, it will be set as elements
  //   Signatures:
  //     {attributeName: buffer}
  //     {attributeName: [buffer, accessor]}
  //     {attributeName: (typed) array} => constant
  setAttributes(attributes) {
    Object.assign(this.attributes, attributes);
    this.vertexArrayObject.bind(() => {
      for (const locationOrName in attributes) {
        const value = attributes[locationOrName];
        this._setAttribute(locationOrName, value);
      }
      // Make sure we don't leave any bindings
      this.gl.bindBuffer(GL.ARRAY_BUFFER, null);
    });

    return this;
  }

  // Set (bind) an elements buffer, for indexed rendering.
  // Must be a Buffer bound to GL.ELEMENT_ARRAY_BUFFER. Constants not supported
  setElementBuffer(elementBuffer = null, accessor = {}) {
    this.elements = elementBuffer; // Save value for debugging
    this.elementsAccessor = accessor;
    this.clearDrawParams();
    this.vertexArrayObject.setElementBuffer(elementBuffer, accessor);

    return this;
  }

  // Set a location in vertex attributes array to a buffer
  setBuffer(locationOrName, buffer, appAccessor = {}) {
    // Check target
    if (buffer.target === GL.ELEMENT_ARRAY_BUFFER) {
      return this.setElementBuffer(buffer, appAccessor);
    }

    const {location, accessor} = this._resolveLocationAndAccessor(
      locationOrName,
      buffer,
      buffer.accessor,
      appAccessor
    );

    if (location >= 0) {
      this.values[location] = buffer;
      this.accessors[location] = accessor;
      this.clearDrawParams();
      this.vertexArrayObject.setBuffer(location, buffer, accessor);
    }

    return this;
  }

  // Set attribute to constant value (small typed array corresponding to one vertex' worth of data)
  setConstant(locationOrName, arrayValue, appAccessor = {}) {
    const {location, accessor} = this._resolveLocationAndAccessor(
      locationOrName,
      arrayValue,
      // Ensure that size isn't taken from program for multi-column
      // attributes
      Object.assign({size: arrayValue.length}, appAccessor)
    );

    if (location >= 0) {
      arrayValue = this.vertexArrayObject._normalizeConstantArrayValue(arrayValue, accessor);

      this.values[location] = arrayValue;
      this.accessors[location] = accessor;
      this.clearDrawParams();

      // NOTE: We set the actual constant value later on bind. We can't set the value now since
      // constants are global and affect all other VertexArrays that have disabled attributes
      // in the same location.
      // We do disable the attribute which makes it use the global constant value at that location
      this.vertexArrayObject.enable(location, false);
    }

    return this;
  }

  // Workaround for Chrome TransformFeedback binding issue
  // If required, unbind temporarily to avoid conflicting with TransformFeedback
  unbindBuffers() {
    this.vertexArrayObject.bind(() => {
      if (this.elements) {
        this.vertexArrayObject.setElementBuffer(null);
      }

      // Chrome does not like buffers that are bound to several binding points,
      // so we need to offer and unbind facility
      // WebGL offers disabling, but no clear way to set a VertexArray buffer to `null`
      // So we just bind all the attributes to the dummy "attribute zero" buffer
      this.buffer = this.buffer || new Buffer(this.gl, {accessor: {size: 4}});

      for (let location = 0; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {
        if (this.values[location] instanceof Buffer) {
          this.gl.disableVertexAttribArray(location);
          this.gl.bindBuffer(GL.ARRAY_BUFFER, this.buffer.handle);
          this.gl.vertexAttribPointer(location, 1, GL.FLOAT, false, 0, 0);
        }
      }
    });
    return this;
  }

  // Workaround for Chrome TransformFeedback binding issue
  // If required, rebind rebind after temporary unbind
  bindBuffers() {
    this.vertexArrayObject.bind(() => {
      if (this.elements) {
        this.setElementBuffer(this.elements);
      }

      for (let location = 0; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {
        const buffer = this.values[location];
        if (buffer instanceof Buffer) {
          this.setBuffer(location, buffer);
        }
      }
    });
    return this;
  }

  // Bind for use
  // When a vertex array is about to be used, we must:
  // - Set constant attributes (since these are stored on the context and reset on bind)
  // - Check if we need to initialize the buffer
  bindForDraw(vertexCount, instanceCount, func) {
    let value;

    this.vertexArrayObject.bind(() => {
      // Make sure that any constant attributes are updated (stored on the context, not the VAO)
      // Also handles attribute 0
      this._setConstantAttributes(vertexCount, instanceCount);

      value = func();
    });

    return value;
  }

  // PRIVATE

  // Resolve locations and accessors
  _resolveLocationAndAccessor(locationOrName, value, valueAccessor, appAccessor) {
    const {location, name} = this._getAttributeIndex(locationOrName);
    if (!Number.isFinite(location) || location < 0) {
      this.unused[locationOrName] = value;
      log.once(3, () => `unused value ${locationOrName} in ${this.id}`)();
      return this;
    }

    const accessInfo = this._getAttributeInfo(name || location);

    // Attribute location wasn't directly found.
    // Likely due to multi-location attributes (e.g. matrix)
    if (!accessInfo) {
      return {
        location: -1,
        accessor: null
      };
    }

    // Resolve the partial accessors into a final accessor
    const currentAccessor = this.accessors[location] || {};
    const accessor = Accessor.resolve(
      accessInfo.accessor,
      currentAccessor,
      valueAccessor,
      appAccessor
    );

    const {size, type} = accessor;
    assert(Number.isFinite(size) && Number.isFinite(type));

    return {location, accessor};
  }

  _getAttributeInfo(attributeName) {
    return this.configuration && this.configuration.getAttributeInfo(attributeName);
  }

  _getAttributeIndex(locationOrName) {
    const location = Number(locationOrName);
    if (Number.isFinite(location)) {
      return {location};
    }

    const multiLocation = MULTI_LOCATION_ATTRIBUTE_REGEXP.exec(locationOrName);
    const name = multiLocation ? multiLocation[1] : locationOrName;
    const locationOffset = multiLocation ? Number(multiLocation[2]) : 0;

    if (this.configuration) {
      return {
        location: this.configuration.getAttributeLocation(name) + locationOffset,
        name
      };
    }

    return {location: -1};
  }

  _setAttribute(locationOrName, value) {
    if (value instanceof Buffer) {
      //  Signature: {attributeName: Buffer}
      this.setBuffer(locationOrName, value);
    } else if (Array.isArray(value) && value.length && value[0] instanceof Buffer) {
      // Signature: {attributeName: [buffer, accessor]}
      const buffer = value[0];
      const accessor = value[1];
      this.setBuffer(locationOrName, buffer, accessor);
    } else if (ArrayBuffer.isView(value) || Array.isArray(value)) {
      // Signature: {attributeName: constant}, constant == short (typed) array
      const constant = value;
      this.setConstant(locationOrName, constant);
    } else if (value.buffer instanceof Buffer) {
      // luma.gl v7: Support accessor objects with 'buffer' field
      // for interleaved data
      // Signature: {attributeName: {...accessor, buffer}}
      const accessor = value;
      this.setBuffer(locationOrName, accessor.buffer, accessor);
    } else {
      throw new Error(ERR_ATTRIBUTE_TYPE);
    }
  }

  // Updates all constant attribute values (constants are used when vertex attributes are disabled).
  // This needs to be done repeatedly since in contrast to buffer bindings,
  // constants are stored on the WebGL context, not the VAO
  _setConstantAttributes(vertexCount, instanceCount) {
    // TODO - use accessor to determine what length to use
    const elementCount = Math.max(vertexCount | 0, instanceCount | 0);
    let constant = this.values[0];
    if (ArrayBuffer.isView(constant)) {
      this._setConstantAttributeZero(constant, elementCount);
    }

    for (let location = 1; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {
      constant = this.values[location];
      if (ArrayBuffer.isView(constant)) {
        this._setConstantAttribute(location, constant);
      }
    }
  }

  _setConstantAttributeZero(constant, elementCount) {
    if (VertexArrayObject.isSupported(this.gl, {constantAttributeZero: true})) {
      this._setConstantAttribute(0, constant);
      return;
    }

    // Get a dummy buffer populated with repeated constants
    const buffer = this.vertexArrayObject.getConstantBuffer(elementCount, constant);

    // Set the buffer on location 0
    this.vertexArrayObject.setBuffer(0, buffer, this.accessors[0]);
  }

  _setConstantAttribute(location, constant) {
    VertexArrayObject.setConstant(this.gl, location, constant);
  }

  // Walks the buffers and updates draw parameters
  _updateDrawParams() {
    const drawParams = {
      isIndexed: false,
      isInstanced: false,
      indexCount: Infinity,
      vertexCount: Infinity,
      instanceCount: Infinity
    };

    for (let location = 0; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {
      this._updateDrawParamsForLocation(drawParams, location);
    }

    if (this.elements) {
      // indexing is autodetected - buffer with target GL.ELEMENT_ARRAY_BUFFER
      // index type is saved for drawElement calls
      drawParams.elementCount = this.elements.getElementCount(this.elements.accessor);
      drawParams.isIndexed = true;
      drawParams.indexType = this.elementsAccessor.type || this.elements.accessor.type;
      drawParams.indexOffset = this.elementsAccessor.offset || 0;
    }

    // Post-calculation checks
    if (drawParams.indexCount === Infinity) {
      drawParams.indexCount = 0;
    }
    if (drawParams.vertexCount === Infinity) {
      drawParams.vertexCount = 0;
    }
    if (drawParams.instanceCount === Infinity) {
      drawParams.instanceCount = 0;
    }

    return drawParams;
  }

  _updateDrawParamsForLocation(drawParams, location) {
    const value = this.values[location];
    const accessor = this.accessors[location];

    if (!value) {
      return;
    }

    // Check if instanced (whether buffer or constant)
    const {divisor} = accessor;
    const isInstanced = divisor > 0;
    drawParams.isInstanced = drawParams.isInstanced || isInstanced;

    if (value instanceof Buffer) {
      const buffer = value;

      if (isInstanced) {
        // instance attribute
        const instanceCount = buffer.getVertexCount(accessor);
        drawParams.instanceCount = Math.min(drawParams.instanceCount, instanceCount);
      } else {
        // normal attribute
        const vertexCount = buffer.getVertexCount(accessor);
        drawParams.vertexCount = Math.min(drawParams.vertexCount, vertexCount);
      }
    }
  }

  // DEPRECATED in v6.x - but not warnings not properly implemented

  setElements(elementBuffer = null, accessor = {}) {
    log.deprecated('setElements', 'setElementBuffer')();
    return this.setElementBuffer(elementBuffer, accessor);
  }
}
<commit_msg>Delete VAO when vertex array is deleted (#1353)<commit_after>import GL from '@luma.gl/constants';
import {log} from '@luma.gl/gltools';
import Accessor from './accessor';
import Buffer from './buffer';
import VertexArrayObject from './vertex-array-object';
import {assert, stubRemovedMethods} from '../utils';

const ERR_ATTRIBUTE_TYPE =
  'VertexArray: attributes must be Buffers or constants (i.e. typed array)';

// This is done to support mat type attributes.
// See section "Notes about setting mat type attributes"
// in vertex-array.md
const MULTI_LOCATION_ATTRIBUTE_REGEXP = /^(.+)__LOCATION_([0-9]+)$/;

const DEPRECATIONS_V6 = [
  'setBuffers',
  'setGeneric',
  'clearBindings',
  'setLocations',
  'setGenericValues',
  'setDivisor',
  'enable',
  'disable'
];

export default class VertexArray {
  constructor(gl, opts = {}) {
    // Use program's id if program is supplied but no id is supplied
    const id = opts.id || (opts.program && opts.program.id);
    // super(gl, Object.assign({}, opts, {id}));

    this.id = id;
    this.gl = gl;
    this.configuration = null;

    // Extracted information
    this.elements = null;
    this.elementsAccessor = null;
    this.values = null;
    this.accessors = null;
    this.unused = null;
    this.drawParams = null;
    this.buffer = null; // For attribute 0 on desktops, and created when unbinding buffers

    this.attributes = {};

    this.vertexArrayObject = new VertexArrayObject(gl);

    // Issue errors when using removed methods
    stubRemovedMethods(this, 'VertexArray', 'v6.0', DEPRECATIONS_V6);

    this.initialize(opts);
    Object.seal(this);
  }

  delete() {
    if (this.buffer) {
      this.buffer.delete();
    }

    this.vertexArrayObject.delete();
  }

  initialize(props = {}) {
    this.reset();
    this.configuration = null;
    this.bindOnUse = false;
    return this.setProps(props);
  }

  // Resets all attributes (to default valued constants)
  reset() {
    // this.vertexArrayObject.reset();

    this.elements = null;
    this.elementsAccessor = null;
    const {MAX_ATTRIBUTES} = this.vertexArrayObject;
    this.values = new Array(MAX_ATTRIBUTES).fill(null);
    this.accessors = new Array(MAX_ATTRIBUTES).fill(null);
    this.unused = {};

    // Auto detects draw params
    this.drawParams = null;

    return this;
  }

  setProps(props) {
    if ('program' in props) {
      this.configuration = props.program && props.program.configuration;
    }
    if ('configuration' in props) {
      this.configuration = props.configuration;
    }
    if ('attributes' in props) {
      this.setAttributes(props.attributes);
    }
    if ('elements' in props) {
      this.setElementBuffer(props.elements);
    }
    if ('bindOnUse' in props) {
      props = props.bindOnUse;
    }
    return this;
  }

  // Automatically called if buffers changed through VertexArray API
  clearDrawParams() {
    this.drawParams = null;
  }

  getDrawParams() {
    // Auto deduced draw parameters
    this.drawParams = this.drawParams || this._updateDrawParams();

    return this.drawParams;
  }

  // Set (bind) an array or map of vertex array buffers, either in numbered or named locations.
  // For names that are not present in `location`, the supplied buffers will be ignored.
  // if a single buffer of type GL.ELEMENT_ARRAY_BUFFER is present, it will be set as elements
  //   Signatures:
  //     {attributeName: buffer}
  //     {attributeName: [buffer, accessor]}
  //     {attributeName: (typed) array} => constant
  setAttributes(attributes) {
    Object.assign(this.attributes, attributes);
    this.vertexArrayObject.bind(() => {
      for (const locationOrName in attributes) {
        const value = attributes[locationOrName];
        this._setAttribute(locationOrName, value);
      }
      // Make sure we don't leave any bindings
      this.gl.bindBuffer(GL.ARRAY_BUFFER, null);
    });

    return this;
  }

  // Set (bind) an elements buffer, for indexed rendering.
  // Must be a Buffer bound to GL.ELEMENT_ARRAY_BUFFER. Constants not supported
  setElementBuffer(elementBuffer = null, accessor = {}) {
    this.elements = elementBuffer; // Save value for debugging
    this.elementsAccessor = accessor;
    this.clearDrawParams();
    this.vertexArrayObject.setElementBuffer(elementBuffer, accessor);

    return this;
  }

  // Set a location in vertex attributes array to a buffer
  setBuffer(locationOrName, buffer, appAccessor = {}) {
    // Check target
    if (buffer.target === GL.ELEMENT_ARRAY_BUFFER) {
      return this.setElementBuffer(buffer, appAccessor);
    }

    const {location, accessor} = this._resolveLocationAndAccessor(
      locationOrName,
      buffer,
      buffer.accessor,
      appAccessor
    );

    if (location >= 0) {
      this.values[location] = buffer;
      this.accessors[location] = accessor;
      this.clearDrawParams();
      this.vertexArrayObject.setBuffer(location, buffer, accessor);
    }

    return this;
  }

  // Set attribute to constant value (small typed array corresponding to one vertex' worth of data)
  setConstant(locationOrName, arrayValue, appAccessor = {}) {
    const {location, accessor} = this._resolveLocationAndAccessor(
      locationOrName,
      arrayValue,
      // Ensure that size isn't taken from program for multi-column
      // attributes
      Object.assign({size: arrayValue.length}, appAccessor)
    );

    if (location >= 0) {
      arrayValue = this.vertexArrayObject._normalizeConstantArrayValue(arrayValue, accessor);

      this.values[location] = arrayValue;
      this.accessors[location] = accessor;
      this.clearDrawParams();

      // NOTE: We set the actual constant value later on bind. We can't set the value now since
      // constants are global and affect all other VertexArrays that have disabled attributes
      // in the same location.
      // We do disable the attribute which makes it use the global constant value at that location
      this.vertexArrayObject.enable(location, false);
    }

    return this;
  }

  // Workaround for Chrome TransformFeedback binding issue
  // If required, unbind temporarily to avoid conflicting with TransformFeedback
  unbindBuffers() {
    this.vertexArrayObject.bind(() => {
      if (this.elements) {
        this.vertexArrayObject.setElementBuffer(null);
      }

      // Chrome does not like buffers that are bound to several binding points,
      // so we need to offer and unbind facility
      // WebGL offers disabling, but no clear way to set a VertexArray buffer to `null`
      // So we just bind all the attributes to the dummy "attribute zero" buffer
      this.buffer = this.buffer || new Buffer(this.gl, {accessor: {size: 4}});

      for (let location = 0; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {
        if (this.values[location] instanceof Buffer) {
          this.gl.disableVertexAttribArray(location);
          this.gl.bindBuffer(GL.ARRAY_BUFFER, this.buffer.handle);
          this.gl.vertexAttribPointer(location, 1, GL.FLOAT, false, 0, 0);
        }
      }
    });
    return this;
  }

  // Workaround for Chrome TransformFeedback binding issue
  // If required, rebind rebind after temporary unbind
  bindBuffers() {
    this.vertexArrayObject.bind(() => {
      if (this.elements) {
        this.setElementBuffer(this.elements);
      }

      for (let location = 0; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {
        const buffer = this.values[location];
        if (buffer instanceof Buffer) {
          this.setBuffer(location, buffer);
        }
      }
    });
    return this;
  }

  // Bind for use
  // When a vertex array is about to be used, we must:
  // - Set constant attributes (since these are stored on the context and reset on bind)
  // - Check if we need to initialize the buffer
  bindForDraw(vertexCount, instanceCount, func) {
    let value;

    this.vertexArrayObject.bind(() => {
      // Make sure that any constant attributes are updated (stored on the context, not the VAO)
      // Also handles attribute 0
      this._setConstantAttributes(vertexCount, instanceCount);

      value = func();
    });

    return value;
  }

  // PRIVATE

  // Resolve locations and accessors
  _resolveLocationAndAccessor(locationOrName, value, valueAccessor, appAccessor) {
    const {location, name} = this._getAttributeIndex(locationOrName);
    if (!Number.isFinite(location) || location < 0) {
      this.unused[locationOrName] = value;
      log.once(3, () => `unused value ${locationOrName} in ${this.id}`)();
      return this;
    }

    const accessInfo = this._getAttributeInfo(name || location);

    // Attribute location wasn't directly found.
    // Likely due to multi-location attributes (e.g. matrix)
    if (!accessInfo) {
      return {
        location: -1,
        accessor: null
      };
    }

    // Resolve the partial accessors into a final accessor
    const currentAccessor = this.accessors[location] || {};
    const accessor = Accessor.resolve(
      accessInfo.accessor,
      currentAccessor,
      valueAccessor,
      appAccessor
    );

    const {size, type} = accessor;
    assert(Number.isFinite(size) && Number.isFinite(type));

    return {location, accessor};
  }

  _getAttributeInfo(attributeName) {
    return this.configuration && this.configuration.getAttributeInfo(attributeName);
  }

  _getAttributeIndex(locationOrName) {
    const location = Number(locationOrName);
    if (Number.isFinite(location)) {
      return {location};
    }

    const multiLocation = MULTI_LOCATION_ATTRIBUTE_REGEXP.exec(locationOrName);
    const name = multiLocation ? multiLocation[1] : locationOrName;
    const locationOffset = multiLocation ? Number(multiLocation[2]) : 0;

    if (this.configuration) {
      return {
        location: this.configuration.getAttributeLocation(name) + locationOffset,
        name
      };
    }

    return {location: -1};
  }

  _setAttribute(locationOrName, value) {
    if (value instanceof Buffer) {
      //  Signature: {attributeName: Buffer}
      this.setBuffer(locationOrName, value);
    } else if (Array.isArray(value) && value.length && value[0] instanceof Buffer) {
      // Signature: {attributeName: [buffer, accessor]}
      const buffer = value[0];
      const accessor = value[1];
      this.setBuffer(locationOrName, buffer, accessor);
    } else if (ArrayBuffer.isView(value) || Array.isArray(value)) {
      // Signature: {attributeName: constant}, constant == short (typed) array
      const constant = value;
      this.setConstant(locationOrName, constant);
    } else if (value.buffer instanceof Buffer) {
      // luma.gl v7: Support accessor objects with 'buffer' field
      // for interleaved data
      // Signature: {attributeName: {...accessor, buffer}}
      const accessor = value;
      this.setBuffer(locationOrName, accessor.buffer, accessor);
    } else {
      throw new Error(ERR_ATTRIBUTE_TYPE);
    }
  }

  // Updates all constant attribute values (constants are used when vertex attributes are disabled).
  // This needs to be done repeatedly since in contrast to buffer bindings,
  // constants are stored on the WebGL context, not the VAO
  _setConstantAttributes(vertexCount, instanceCount) {
    // TODO - use accessor to determine what length to use
    const elementCount = Math.max(vertexCount | 0, instanceCount | 0);
    let constant = this.values[0];
    if (ArrayBuffer.isView(constant)) {
      this._setConstantAttributeZero(constant, elementCount);
    }

    for (let location = 1; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {
      constant = this.values[location];
      if (ArrayBuffer.isView(constant)) {
        this._setConstantAttribute(location, constant);
      }
    }
  }

  _setConstantAttributeZero(constant, elementCount) {
    if (VertexArrayObject.isSupported(this.gl, {constantAttributeZero: true})) {
      this._setConstantAttribute(0, constant);
      return;
    }

    // Get a dummy buffer populated with repeated constants
    const buffer = this.vertexArrayObject.getConstantBuffer(elementCount, constant);

    // Set the buffer on location 0
    this.vertexArrayObject.setBuffer(0, buffer, this.accessors[0]);
  }

  _setConstantAttribute(location, constant) {
    VertexArrayObject.setConstant(this.gl, location, constant);
  }

  // Walks the buffers and updates draw parameters
  _updateDrawParams() {
    const drawParams = {
      isIndexed: false,
      isInstanced: false,
      indexCount: Infinity,
      vertexCount: Infinity,
      instanceCount: Infinity
    };

    for (let location = 0; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {
      this._updateDrawParamsForLocation(drawParams, location);
    }

    if (this.elements) {
      // indexing is autodetected - buffer with target GL.ELEMENT_ARRAY_BUFFER
      // index type is saved for drawElement calls
      drawParams.elementCount = this.elements.getElementCount(this.elements.accessor);
      drawParams.isIndexed = true;
      drawParams.indexType = this.elementsAccessor.type || this.elements.accessor.type;
      drawParams.indexOffset = this.elementsAccessor.offset || 0;
    }

    // Post-calculation checks
    if (drawParams.indexCount === Infinity) {
      drawParams.indexCount = 0;
    }
    if (drawParams.vertexCount === Infinity) {
      drawParams.vertexCount = 0;
    }
    if (drawParams.instanceCount === Infinity) {
      drawParams.instanceCount = 0;
    }

    return drawParams;
  }

  _updateDrawParamsForLocation(drawParams, location) {
    const value = this.values[location];
    const accessor = this.accessors[location];

    if (!value) {
      return;
    }

    // Check if instanced (whether buffer or constant)
    const {divisor} = accessor;
    const isInstanced = divisor > 0;
    drawParams.isInstanced = drawParams.isInstanced || isInstanced;

    if (value instanceof Buffer) {
      const buffer = value;

      if (isInstanced) {
        // instance attribute
        const instanceCount = buffer.getVertexCount(accessor);
        drawParams.instanceCount = Math.min(drawParams.instanceCount, instanceCount);
      } else {
        // normal attribute
        const vertexCount = buffer.getVertexCount(accessor);
        drawParams.vertexCount = Math.min(drawParams.vertexCount, vertexCount);
      }
    }
  }

  // DEPRECATED in v6.x - but not warnings not properly implemented

  setElements(elementBuffer = null, accessor = {}) {
    log.deprecated('setElements', 'setElementBuffer')();
    return this.setElementBuffer(elementBuffer, accessor);
  }
}
<|endoftext|>


<commit_before>/**
 * @copyright   2016, Miles Johnson
 * @license     https://opensource.org/licenses/MIT
 * @flow
 */

import React from 'react';
import Matcher from '../Matcher';
import Emoji from '../components/Emoji';
import { SHORTNAME_TO_UNICODE, EMOJI_PATTERN, EMOJI_SHORTNAME_PATTERN } from '../data/emoji';

import type { MatchResponse, EmojiProps, EmojiOptions } from '../types';

const EMOJI_REGEX = new RegExp(EMOJI_PATTERN);
const EMOJI_SHORTNAME_REGEX = new RegExp(EMOJI_SHORTNAME_PATTERN, 'i');

export default class EmojiMatcher extends Matcher<EmojiOptions> {
  options: EmojiOptions;

  /**
   * {@inheritDoc}
   */
  factory(match: string, props: Object = {}): React.Element<EmojiProps> {
    if (this.options.renderUnicode) {
      return props.unicode;
    }

    return (
      <Emoji {...props} />
    );
  }

  /**
   * @{inheritDoc}
   */
  getTagName(): string {
    return 'span';
  }

  /**
   * {@inheritDoc}
   */
  match(string: string): ?MatchResponse {
    let response = null;

    // Should we convert shortnames to unicode?
    if (this.options.convertShortName && string.indexOf(':') >= 0) {
      response = this.doMatch(string, EMOJI_SHORTNAME_REGEX, matches => ({
        shortName: matches[0].toLowerCase(),
      }));

      if (response) {
        const unicode = SHORTNAME_TO_UNICODE[response.shortName];

        // Invalid shortname
        if (!unicode) {
          response = null;

        // We want to render using the unicode value
        } else {
          response.unicode = unicode;
        }
      }
    }

    // Should we convert unicode to SVG/PNG?
    if (this.options.convertUnicode && !response) {
      response = this.doMatch(string, EMOJI_REGEX, matches => ({
        unicode: matches[0],
      }));
    }

    return response;
  }
}
<commit_msg>Updated EmojiMatcher to verify the unicode character is legit.<commit_after>/**
 * @copyright   2016, Miles Johnson
 * @license     https://opensource.org/licenses/MIT
 * @flow
 */

import React from 'react';
import Matcher from '../Matcher';
import Emoji from '../components/Emoji';
import {
  EMOJI_PATTERN,
  EMOJI_SHORTNAME_PATTERN,
  SHORTNAME_TO_UNICODE,
  UNICODE_TO_SHORTNAME,
} from '../data/emoji';

import type { MatchResponse, EmojiProps, EmojiOptions } from '../types';

const EMOJI_REGEX = new RegExp(EMOJI_PATTERN);
const EMOJI_SHORTNAME_REGEX = new RegExp(EMOJI_SHORTNAME_PATTERN, 'i');

export default class EmojiMatcher extends Matcher<EmojiOptions> {
  options: EmojiOptions;

  /**
   * {@inheritDoc}
   */
  factory(match: string, props: Object = {}): React.Element<EmojiProps> {
    if (this.options.renderUnicode) {
      return props.unicode;
    }

    return (
      <Emoji {...props} />
    );
  }

  /**
   * @{inheritDoc}
   */
  getTagName(): string {
    return 'span';
  }

  /**
   * {@inheritDoc}
   */
  match(string: string): ?MatchResponse {
    let response = null;

    // Should we convert shortnames to unicode?
    if (this.options.convertShortName && string.indexOf(':') >= 0) {
      response = this.doMatch(string, EMOJI_SHORTNAME_REGEX, matches => ({
        shortName: matches[0].toLowerCase(),
      }));

      if (response) {
        const unicode = SHORTNAME_TO_UNICODE[response.shortName];

        // Invalid shortname
        if (!unicode) {
          response = null;

        // We want to render using the unicode value
        } else {
          response.unicode = unicode;
        }
      }
    }

    // Should we convert unicode to SVG/PNG?
    if (this.options.convertUnicode && !response) {
      response = this.doMatch(string, EMOJI_REGEX, matches => ({
        unicode: matches[0],
      }));

      if (response && !UNICODE_TO_SHORTNAME[response.unicode]) {
        return null;
      }
    }

    return response;
  }
}
<|endoftext|>