<commit_before>import Margin from './margin';
import Class from '../mixin/class';
import {addClass, children, css, height as getHeight, hasClass, scrolledOver, sortBy, toFloat, toggleClass, Transition} from 'uikit-util';

export default {

    extends: Margin,

    mixins: [Class],

    name: 'grid',

    props: {
        masonry: Boolean,
        parallax: Number
    },

    data: {
        margin: 'uk-grid-margin',
        clsStack: 'uk-grid-stack',
        masonry: false,
        parallax: 0
    },

    connected() {
        this.masonry && addClass(this.$el, 'uk-flex-top uk-flex-wrap-top');
    },

    update: [

        {

            write({columns}) {
                toggleClass(this.$el, this.clsStack, columns.length < 2);
            },

            events: ['resize']

        },

        {

            read({columns, rows}) {

                const nodes = children(this.$el);

                if (!nodes.length || !this.masonry && !this.parallax) {
                    return false;
                }

                const transitionInProgress = nodes.some(Transition.inProgress);
                let translates = false;
                let elHeight = '';
                let padding = Math.abs(this.parallax);

                if (this.masonry) {

                    columns = columns.map(column => sortBy(column, 'offsetTop'));

                    const columnHeights = getColumnHeights(columns);
                    const margin = getMarginTop(nodes, this.margin) * (rows.length - 1);

                    translates = getTranslates(rows, columns);
                    elHeight = Math.max(...columnHeights) + margin;

                    if (padding) {
                        padding = columnHeights.reduce((newPadding, hgt, i) =>
                            Math.max(newPadding, hgt + margin + (i % 2 ? padding : padding / 8) - elHeight)
                        , 0);
                    }

                }

                return {padding, columns, translates, height: !transitionInProgress ? elHeight : false};

            },

            write({height, padding}) {

                css(this.$el, 'paddingBottom', padding || '');
                height !== false && css(this.$el, 'height', height);

            },

            events: ['resize']

        },

        {

            read({height}) {
                return {
                    scrolled: this.parallax
                        ? scrolledOver(this.$el, height ? height - getHeight(this.$el) : 0) * Math.abs(this.parallax)
                        : false
                };
            },

            write({columns, scrolled, translates}) {

                if (scrolled === false && !translates) {
                    return;
                }

                columns.forEach((column, i) =>
                    column.forEach((el, j) =>
                        css(el, 'transform', !scrolled && !translates ? '' : `translateY(${
                            (translates && -translates[i][j]) + (scrolled ? i % 2 ? scrolled : scrolled / 8 : 0)
                        }px)`)
                    )
                );

            },

            events: ['scroll', 'resize']

        }

    ]

};

function getTranslates(rows, columns) {

    const rowHeights = rows.map(row =>
        Math.max(...row.map(el => el.offsetHeight))
    );

    return columns.map(elements => {

        let prev = 0;
        return elements.map((element, row) =>
            prev += row
                ? rowHeights[row - 1] - elements[row - 1].offsetHeight
                : 0
        );

    });
}

function getMarginTop(nodes, cls) {

    const [node] = nodes.filter(el => hasClass(el, cls));

    return toFloat(node
        ? css(node, 'marginTop')
        : css(nodes[0], 'paddingLeft'));
}

function getColumnHeights(columns) {
    return columns.map(column =>
        column.reduce((sum, el) => sum + el.offsetHeight, 0)
    );
}
<commit_msg>cleanup<commit_after>import Margin from './margin';
import Class from '../mixin/class';
import {addClass, children, css, height as getHeight, hasClass, scrolledOver, sortBy, toFloat, toggleClass, Transition} from 'uikit-util';

export default {

    extends: Margin,

    mixins: [Class],

    name: 'grid',

    props: {
        masonry: Boolean,
        parallax: Number
    },

    data: {
        margin: 'uk-grid-margin',
        clsStack: 'uk-grid-stack',
        masonry: false,
        parallax: 0
    },

    connected() {
        this.masonry && addClass(this.$el, 'uk-flex-top uk-flex-wrap-top');
    },

    update: [

        {

            write({columns}) {
                toggleClass(this.$el, this.clsStack, columns.length < 2);
            },

            events: ['resize']

        },

        {

            read({columns, rows}) {

                const nodes = children(this.$el);

                if (!nodes.length || !this.masonry && !this.parallax) {
                    return false;
                }

                const transitionInProgress = nodes.some(Transition.inProgress);
                let translates = false;
                let elHeight = '';
                let padding = Math.abs(this.parallax);

                if (this.masonry) {

                    columns = columns.map(column => sortBy(column, 'offsetTop'));

                    const columnHeights = getColumnHeights(columns);
                    const margin = getMarginTop(nodes, this.margin) * (rows.length - 1);

                    translates = getTranslates(rows, columns);
                    elHeight = Math.max(...columnHeights) + margin;

                    if (padding) {
                        padding = columnHeights.reduce((newPadding, hgt, i) =>
                            Math.max(newPadding, hgt + margin + (i % 2 ? padding : padding / 8) - elHeight)
                        , 0);
                    }

                }

                return {padding, columns, translates, height: !transitionInProgress ? elHeight : false};

            },

            write({height, padding}) {

                css(this.$el, 'paddingBottom', padding || '');
                height !== false && css(this.$el, 'height', height);

            },

            events: ['resize']

        },

        {

            read({height}) {
                return {
                    scrolled: this.parallax
                        ? scrolledOver(this.$el, height ? height - getHeight(this.$el) : 0) * Math.abs(this.parallax)
                        : false
                };
            },

            write({columns, scrolled, translates}) {

                if (scrolled === false && !translates) {
                    return;
                }

                columns.forEach((column, i) =>
                    column.forEach((el, j) =>
                        css(el, 'transform', !scrolled && !translates ? '' : `translateY(${
                            (translates && -translates[i][j]) + (scrolled ? i % 2 ? scrolled : scrolled / 8 : 0)
                        }px)`)
                    )
                );

            },

            events: ['scroll', 'resize']

        }

    ]

};

function getTranslates(rows, columns) {

    const rowHeights = rows.map(row =>
        Math.max(...row.map(el => el.offsetHeight))
    );

    return columns.map(elements => {
        let prev = 0;
        return elements.map((element, row) =>
            prev += row
                ? rowHeights[row - 1] - elements[row - 1].offsetHeight
                : 0
        );
    });
}

function getMarginTop(nodes, cls) {

    const [node] = nodes.filter(el => hasClass(el, cls));

    return toFloat(node
        ? css(node, 'marginTop')
        : css(nodes[0], 'paddingLeft'));
}

function getColumnHeights(columns) {
    return columns.map(column =>
        column.reduce((sum, el) => sum + el.offsetHeight, 0)
    );
}
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var util = require('./util')
  , transports = require('./transports')
  , debug = require('debug')('engine-client:socket')
  , EventEmitter = require('./event-emitter')

/**
 * Module exports.
 */

module.exports = Socket;

/**
 * Socket constructor.
 *
 * @param {Object} options
 * @api public
 */

function Socket (opts) {
  if ('string' == typeof opts) {
    var uri = util.parseUri(opts);
    opts = arguments[1] || {};
    opts.host = uri.host;
    opts.secure = uri.scheme == 'https' || uri.scheme == 'wss';
    opts.port = uri.port || (opts.secure ? 443 : 80);
  }

  opts = opts || {};
  this.secure = opts.secure || false;
  this.host = opts.host || opts.hostname || 'localhost';
  this.port = opts.port || 80;
  this.query = opts.query || {};
  this.query.uid = rnd();
  this.upgrade = false !== opts.upgrade;
  this.resource = opts.resource || 'default';
  this.path = (opts.path || '/engine.io').replace(/\/$/, '');
  this.path += '/' + this.resource + '/';
  this.forceJSONP = !!opts.forceJSONP;
  this.flashPath = opts.flashPath || '';
  this.transports = opts.transports || ['polling', 'websocket', 'flashsocket'];
  this.readyState = '';
  this.writeBuffer = [];
  this.policyPort = opts.policyPort;
  this.open();
};

/**
 * Inherits from EventEmitter.
 */

util.inherits(Socket, EventEmitter);

/**
 * Creates transport of the given type.
 *
 * @param {String} transport name
 * @return {Transport}
 * @api private
 */

Socket.prototype.createTransport = function (name) {
  debug('creating transport "%s"', name);
  var query = clone(this.query)
  query.transport = name;

  if (this.id) {
    query.sid = this.id;
  }

  var transport = new transports[name]({
      host: this.host
    , port: this.port
    , secure: this.secure
    , path: this.path
    , query: query
    , forceJSONP: this.forceJSONP
    , flashPath: this.flashPath
    , policyPort: this.policyPort
  });

  return transport;
};

function clone (obj) {
  var o = {};
  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      o[i] = obj[i];
    }
  }
  return o;
}

/**
 * Initializes transport to use and starts probe.
 *
 * @api private
 */

Socket.prototype.open = function () {
  this.readyState = 'opening';
  var transport = this.createTransport(this.transports[0]);
  transport.open();
  this.setTransport(transport);
};

/**
 * Sets the current transport. Disables the existing one (if any).
 *
 * @api private
 */

Socket.prototype.setTransport = function (transport) {
  var self = this;

  if (this.transport) {
    debug('clearing existing transport');
    this.transport.removeAllListeners();
  }

  // set up transport
  this.transport = transport;

  // set up transport listeners
  transport
    .on('drain', function () {
      self.flush();
    })
    .on('packet', function (packet) {
      self.onPacket(packet);
    })
    .on('error', function (e) {
      self.onError(e);
    })
    .on('close', function () {
      self.onClose('transport close');
    })
};

/**
 * Probes a transport.
 *
 * @param {String} transport name
 * @api private
 */

Socket.prototype.probe = function (name) {
  debug('probing transport "%s"', name);
  var transport = this.createTransport(name, { probe: 1 })
    , self = this

  transport.once('open', function () {
    debug('probe transport "%s" opened', name);
    transport.send([{ type: 'ping', data: 'probe' }]);
    transport.once('packet', function (msg) {
      if ('pong' == msg.type && 'probe' == msg.data) {
        debug('probe transport "%s" pong', name);
        self.upgrading = true;
        self.emit('upgrading', transport);

        debug('pausing current transport "%s"', self.transport.name);
        self.transport.pause(function () {
          if ('closed' == self.readyState || 'closing' == self.readyState) return;
          debug('changing transport and sending upgrade packet');
          self.emit('upgrade', transport);
          self.setTransport(transport);
          transport.send([{ type: 'upgrade' }]);
          transport = null;
          self.upgrading = false;
          self.flush();
        });
      } else {
        debug('probe transport "%s" failed', name);
        var err = new Error('probe error');
        err.transport = transport.name;
        self.emit('error', err);
      }
    });
  });

  transport.open();

  this.once('close', function () {
    if (transport) {
      debug('socket closed prematurely - aborting probe');
      transport.close();
      transport = null;
    }
  });

  this.once('upgrading', function (to) {
    if (transport && to.name != transport.name) {
      debug('"%s" works - aborting "%s"', to.name, transport.name);
      transport.close();
      transport = null;
    }
  });
};

/**
 * Called when connection is deemed open.
 *
 * @api public
 */

Socket.prototype.onOpen = function () {
  debug('socket open');
  this.readyState = 'open';
  this.emit('open');
  this.onopen && this.onopen.call(this);
  this.flush();

  if (this.upgrade && this.transport.pause) {
    debug('starting upgrade probes');
    for (var i = 0, l = this.upgrades.length; i < l; i++) {
      this.probe(this.upgrades[i]);
    }
  }
};

/**
 * Handles a packet.
 *
 * @api private
 */

Socket.prototype.onPacket = function (packet) {
  if ('opening' == this.readyState || 'open' == this.readyState) {
    debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
    switch (packet.type) {
      case 'open':
        this.onHandshake(util.parseJSON(packet.data));
        break;

      case 'ping':
        this.sendPacket('pong');
        this.setPingTimeout();
        break;

      case 'error':
        var err = new Error('server error');
        err.code = packet.data;
        this.emit('error', err);
        break;

      case 'message':
        this.emit('message', packet.data);
        this.onmessage && this.onmessage.call(this, { data: packet.data });
        break;
    }
  } else {
    debug('packet received with socket readyState "%s"', this.readyState);
  }
};

/**
 * Called upon handshake completion.
 *
 * @param {Object} handshake obj
 * @api private
 */

Socket.prototype.onHandshake = function (data) {
  this.emit('handshake', data);
  this.id = data.sid;
  this.transport.query.sid = data.sid;
  this.upgrades = data.upgrades;
  this.pingTimeout = data.pingTimeout;
  this.onOpen();
  this.setPingTimeout();
};

/**
 * Clears and sets a ping timeout based on the expected ping interval.
 *
 * @api private
 */

Socket.prototype.setPingTimeout = function () {
  clearTimeout(this.pingTimeoutTimer);
  var self = this;
  this.pingTimeoutTimer = setTimeout(function () {
    self.onClose('ping timeout');
  }, this.pingTimeout);
};

/**
 * Flush write buffers.
 *
 * @api private
 */

Socket.prototype.flush = function () {
  if ('closed' != this.readyState && this.transport.writable
    && !this.upgrading && this.writeBuffer.length) {
    debug('flushing %d packets in socket', this.writeBuffer.length);
    this.transport.send(this.writeBuffer);
    this.writeBuffer = [];
  }
};

/**
 * Sends a message.
 *
 * @param {String} message.
 * @return {Socket} for chaining.
 * @api public
 */

Socket.prototype.send = function (msg) {
  this.sendPacket('message', msg);
  return this;
};

/**
 * Sends a packet.
 *
 * @param {String} packet type.
 * @param {String} data.
 * @api private
 */

Socket.prototype.sendPacket = function (type, data) {
  var packet = { type: type, data: data };
  this.writeBuffer.push(packet);
  this.flush();
};

/**
 * Closes the connection.
 *
 * @api private
 */

Socket.prototype.close = function () {
  if ('opening' == this.readyState || 'open' == this.readyState) {
    this.onClose('forced close');
    debug('socket closing - telling transport to close');
    this.transport.close();
  }

  return this;
};

/**
 * Called upon transport error
 *
 * @api private
 */

Socket.prototype.onError = function (err) {
  this.emit('error', err);
  this.onClose('transport error', err);
};

/**
 * Called upon transport close.
 *
 * @api private
 */

Socket.prototype.onClose = function (reason, desc) {
  if ('closed' != this.readyState) {
    debug('socket close with reason: "%s"', reason);
    this.readyState = 'closed';
    this.emit('close', reason, desc);
    this.onclose && this.onclose.call(this);
  }
};

/**
 * Generates a random uid.
 *
 * @api private
 */

function rnd () {
  return String(Math.random()).substr(5) + String(Math.random()).substr(5);
}
<commit_msg>socket: added `toString` to fake event sent to `onmessage`<commit_after>/**
 * Module dependencies.
 */

var util = require('./util')
  , transports = require('./transports')
  , debug = require('debug')('engine-client:socket')
  , EventEmitter = require('./event-emitter')

/**
 * Module exports.
 */

module.exports = Socket;

/**
 * Socket constructor.
 *
 * @param {Object} options
 * @api public
 */

function Socket (opts) {
  if ('string' == typeof opts) {
    var uri = util.parseUri(opts);
    opts = arguments[1] || {};
    opts.host = uri.host;
    opts.secure = uri.scheme == 'https' || uri.scheme == 'wss';
    opts.port = uri.port || (opts.secure ? 443 : 80);
  }

  opts = opts || {};
  this.secure = opts.secure || false;
  this.host = opts.host || opts.hostname || 'localhost';
  this.port = opts.port || 80;
  this.query = opts.query || {};
  this.query.uid = rnd();
  this.upgrade = false !== opts.upgrade;
  this.resource = opts.resource || 'default';
  this.path = (opts.path || '/engine.io').replace(/\/$/, '');
  this.path += '/' + this.resource + '/';
  this.forceJSONP = !!opts.forceJSONP;
  this.flashPath = opts.flashPath || '';
  this.transports = opts.transports || ['polling', 'websocket', 'flashsocket'];
  this.readyState = '';
  this.writeBuffer = [];
  this.policyPort = opts.policyPort;
  this.open();
};

/**
 * Inherits from EventEmitter.
 */

util.inherits(Socket, EventEmitter);

/**
 * Creates transport of the given type.
 *
 * @param {String} transport name
 * @return {Transport}
 * @api private
 */

Socket.prototype.createTransport = function (name) {
  debug('creating transport "%s"', name);
  var query = clone(this.query)
  query.transport = name;

  if (this.id) {
    query.sid = this.id;
  }

  var transport = new transports[name]({
      host: this.host
    , port: this.port
    , secure: this.secure
    , path: this.path
    , query: query
    , forceJSONP: this.forceJSONP
    , flashPath: this.flashPath
    , policyPort: this.policyPort
  });

  return transport;
};

function clone (obj) {
  var o = {};
  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      o[i] = obj[i];
    }
  }
  return o;
}

/**
 * Initializes transport to use and starts probe.
 *
 * @api private
 */

Socket.prototype.open = function () {
  this.readyState = 'opening';
  var transport = this.createTransport(this.transports[0]);
  transport.open();
  this.setTransport(transport);
};

/**
 * Sets the current transport. Disables the existing one (if any).
 *
 * @api private
 */

Socket.prototype.setTransport = function (transport) {
  var self = this;

  if (this.transport) {
    debug('clearing existing transport');
    this.transport.removeAllListeners();
  }

  // set up transport
  this.transport = transport;

  // set up transport listeners
  transport
    .on('drain', function () {
      self.flush();
    })
    .on('packet', function (packet) {
      self.onPacket(packet);
    })
    .on('error', function (e) {
      self.onError(e);
    })
    .on('close', function () {
      self.onClose('transport close');
    })
};

/**
 * Probes a transport.
 *
 * @param {String} transport name
 * @api private
 */

Socket.prototype.probe = function (name) {
  debug('probing transport "%s"', name);
  var transport = this.createTransport(name, { probe: 1 })
    , self = this

  transport.once('open', function () {
    debug('probe transport "%s" opened', name);
    transport.send([{ type: 'ping', data: 'probe' }]);
    transport.once('packet', function (msg) {
      if ('pong' == msg.type && 'probe' == msg.data) {
        debug('probe transport "%s" pong', name);
        self.upgrading = true;
        self.emit('upgrading', transport);

        debug('pausing current transport "%s"', self.transport.name);
        self.transport.pause(function () {
          if ('closed' == self.readyState || 'closing' == self.readyState) return;
          debug('changing transport and sending upgrade packet');
          self.emit('upgrade', transport);
          self.setTransport(transport);
          transport.send([{ type: 'upgrade' }]);
          transport = null;
          self.upgrading = false;
          self.flush();
        });
      } else {
        debug('probe transport "%s" failed', name);
        var err = new Error('probe error');
        err.transport = transport.name;
        self.emit('error', err);
      }
    });
  });

  transport.open();

  this.once('close', function () {
    if (transport) {
      debug('socket closed prematurely - aborting probe');
      transport.close();
      transport = null;
    }
  });

  this.once('upgrading', function (to) {
    if (transport && to.name != transport.name) {
      debug('"%s" works - aborting "%s"', to.name, transport.name);
      transport.close();
      transport = null;
    }
  });
};

/**
 * Called when connection is deemed open.
 *
 * @api public
 */

Socket.prototype.onOpen = function () {
  debug('socket open');
  this.readyState = 'open';
  this.emit('open');
  this.onopen && this.onopen.call(this);
  this.flush();

  if (this.upgrade && this.transport.pause) {
    debug('starting upgrade probes');
    for (var i = 0, l = this.upgrades.length; i < l; i++) {
      this.probe(this.upgrades[i]);
    }
  }
};

/**
 * Handles a packet.
 *
 * @api private
 */

Socket.prototype.onPacket = function (packet) {
  if ('opening' == this.readyState || 'open' == this.readyState) {
    debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
    switch (packet.type) {
      case 'open':
        this.onHandshake(util.parseJSON(packet.data));
        break;

      case 'ping':
        this.sendPacket('pong');
        this.setPingTimeout();
        break;

      case 'error':
        var err = new Error('server error');
        err.code = packet.data;
        this.emit('error', err);
        break;

      case 'message':
        this.emit('message', packet.data);
        var event = { data: packet.data };
        event.toString = function () {
          return packet.data;
        }
        this.onmessage && this.onmessage.call(this, event);
        break;
    }
  } else {
    debug('packet received with socket readyState "%s"', this.readyState);
  }
};

/**
 * Called upon handshake completion.
 *
 * @param {Object} handshake obj
 * @api private
 */

Socket.prototype.onHandshake = function (data) {
  this.emit('handshake', data);
  this.id = data.sid;
  this.transport.query.sid = data.sid;
  this.upgrades = data.upgrades;
  this.pingTimeout = data.pingTimeout;
  this.onOpen();
  this.setPingTimeout();
};

/**
 * Clears and sets a ping timeout based on the expected ping interval.
 *
 * @api private
 */

Socket.prototype.setPingTimeout = function () {
  clearTimeout(this.pingTimeoutTimer);
  var self = this;
  this.pingTimeoutTimer = setTimeout(function () {
    self.onClose('ping timeout');
  }, this.pingTimeout);
};

/**
 * Flush write buffers.
 *
 * @api private
 */

Socket.prototype.flush = function () {
  if ('closed' != this.readyState && this.transport.writable
    && !this.upgrading && this.writeBuffer.length) {
    debug('flushing %d packets in socket', this.writeBuffer.length);
    this.transport.send(this.writeBuffer);
    this.writeBuffer = [];
  }
};

/**
 * Sends a message.
 *
 * @param {String} message.
 * @return {Socket} for chaining.
 * @api public
 */

Socket.prototype.send = function (msg) {
  this.sendPacket('message', msg);
  return this;
};

/**
 * Sends a packet.
 *
 * @param {String} packet type.
 * @param {String} data.
 * @api private
 */

Socket.prototype.sendPacket = function (type, data) {
  var packet = { type: type, data: data };
  this.writeBuffer.push(packet);
  this.flush();
};

/**
 * Closes the connection.
 *
 * @api private
 */

Socket.prototype.close = function () {
  if ('opening' == this.readyState || 'open' == this.readyState) {
    this.onClose('forced close');
    debug('socket closing - telling transport to close');
    this.transport.close();
  }

  return this;
};

/**
 * Called upon transport error
 *
 * @api private
 */

Socket.prototype.onError = function (err) {
  this.emit('error', err);
  this.onClose('transport error', err);
};

/**
 * Called upon transport close.
 *
 * @api private
 */

Socket.prototype.onClose = function (reason, desc) {
  if ('closed' != this.readyState) {
    debug('socket close with reason: "%s"', reason);
    this.readyState = 'closed';
    this.emit('close', reason, desc);
    this.onclose && this.onclose.call(this);
  }
};

/**
 * Generates a random uid.
 *
 * @api private
 */

function rnd () {
  return String(Math.random()).substr(5) + String(Math.random()).substr(5);
}
<|endoftext|>


<commit_before>const path = require('path'),
    webpack = require('webpack'),
    CopyWebpackPlugin = require('copy-webpack-plugin'),
    MiniCssExtractPlugin = require('mini-css-extract-plugin'),
    ManifestPlugin = require('webpack-manifest-plugin'),
    glob = require("glob"),
    UglifyJsPlugin = require('uglifyjs-webpack-plugin'),
    MonacoEditorWebpackPlugin = require('monaco-editor-webpack-plugin');

const isDev = process.env.NODE_ENV === "DEV";

const outputPathRelative = 'dist/';
const staticRelative = 'static/';
const staticPath = path.resolve(__dirname, staticRelative);
const distPath = path.join(staticPath, outputPathRelative);
const vsPath = path.join(staticPath, 'vs/');
const assetPath = path.join(staticPath, "assets");
const manifestPath = 'manifest.json';  //if you change this, you also need to update it in the app.js
const outputname = isDev ? 'main.js' : 'bundle.[hash].js';
const cssName = isDev ? '[name].css' : "[name].[contenthash].css";
const publicPath = isDev ? '/dist/' : 'dist/';
const manifestPlugin = new ManifestPlugin({
    fileName: manifestPath,
    publicPath: './'
});

const assetEntries = glob.sync(`${assetPath}/**/*.*`).reduce((obj, p) => {
    const key = path.basename(p);
    obj[key] = p;
    return obj;
}, {});

let plugins = [
    new MonacoEditorWebpackPlugin({
        output: vsPath,
        languages: ['cpp', 'go', 'rust', 'swift']
    }),
    new CopyWebpackPlugin([
        {
            from: path.join(staticPath, "favicon.ico"),
            to: distPath
        },
        {
            from: 'node_modules/es6-shim/es6-shim.min.js',
            to: distPath
        }
    ]),
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    }),
    new MiniCssExtractPlugin({
        filename: cssName

    }),
    manifestPlugin
];

module.exports = [
    //if you change the order of this, make sure to update the config variable in app.js
    //server side stuff
    // currently we just want to shove a cache path onto the static assets so we can get the hash onto the filename
    //this means we can set the cache for eternity
    {
        mode: isDev ? 'development' : 'production',
        entry: assetEntries,
        output: {
            path: path.join(distPath, 'assets'),
            filename: '.[name].ignoreme'
        },
        module: {
            rules: [
                {
                    test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: '[name].[hash].[ext]'
                        }
                    }]
                }
            ]
        },
        plugins: [
            manifestPlugin
        ]
    },
    //this is the client side
    {
        mode: isDev ? 'development' : 'production',
        entry: './static/main.js',
        output: {
            filename: outputname,
            path: distPath,
            publicPath: publicPath
        },
        resolve: {
            modules: ['./static', "./node_modules"],
            alias: {
                //is this safe?
                goldenlayout: path.resolve(__dirname, 'node_modules/golden-layout/'),
                lzstring: path.resolve(__dirname, 'node_modules/lz-string/'),
                filesaver: path.resolve(__dirname, 'node_modules/file-saver/')
            }
        },
        stats: "normal",
        devtool: 'source-map',
        optimization: {
            minimize: !isDev,
            minimizer: [new UglifyJsPlugin({
                exclude: /\/vs/,
                parallel: true,
                uglifyOptions: {
                    output: {
                        comments: false,
                        beautify: false
                    }
                }
            })]
        },
        module: {
            rules: [
                {
                    test: /\.css$/,
                    exclude: path.resolve(__dirname, 'static/themes/'),
                    use: [
                        {
                            loader: MiniCssExtractPlugin.loader,
                            options: {
                                publicPath: './',
                                hmr: isDev
                            }
                        },
                        'css-loader'
                    ]
                },
                {
                    test: /\.css$/,
                    include: path.resolve(__dirname, 'static/themes/'),
                    use: ['css-loader']
                },
                {
                    test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                    loader: 'url-loader?limit=8192'
                },
                {
                    test: /\.(html)$/,
                    loader: 'html-loader',
                    options: {
                        minimize: !isDev
                    }
                }
            ]
        },
        plugins: plugins
    }

];
<commit_msg>Fix monaco editor web plugin output path<commit_after>const path = require('path'),
    webpack = require('webpack'),
    CopyWebpackPlugin = require('copy-webpack-plugin'),
    MiniCssExtractPlugin = require('mini-css-extract-plugin'),
    ManifestPlugin = require('webpack-manifest-plugin'),
    glob = require("glob"),
    UglifyJsPlugin = require('uglifyjs-webpack-plugin'),
    MonacoEditorWebpackPlugin = require('monaco-editor-webpack-plugin');

const isDev = process.env.NODE_ENV === "DEV";

const outputPathRelative = 'dist/';
const staticRelative = 'static/';
const staticPath = path.resolve(__dirname, staticRelative);
const distPath = path.join(staticPath, outputPathRelative);
const vsPath = path.join(staticPath, 'vs/');
const assetPath = path.join(staticPath, "assets");
const manifestPath = 'manifest.json';  //if you change this, you also need to update it in the app.js
const outputname = isDev ? 'main.js' : 'bundle.[hash].js';
const cssName = isDev ? '[name].css' : "[name].[contenthash].css";
const publicPath = isDev ? '/dist/' : 'dist/';
const manifestPlugin = new ManifestPlugin({
    fileName: manifestPath,
    publicPath: './'
});

const assetEntries = glob.sync(`${assetPath}/**/*.*`).reduce((obj, p) => {
    const key = path.basename(p);
    obj[key] = p;
    return obj;
}, {});

let plugins = [
    new MonacoEditorWebpackPlugin({
        languages: ['cpp', 'go', 'rust', 'swift']
    }),
    new CopyWebpackPlugin([
        {
            from: path.join(staticPath, "favicon.ico"),
            to: distPath
        },
        {
            from: 'node_modules/es6-shim/es6-shim.min.js',
            to: distPath
        }
    ]),
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    }),
    new MiniCssExtractPlugin({
        filename: cssName

    }),
    manifestPlugin
];

module.exports = [
    //if you change the order of this, make sure to update the config variable in app.js
    //server side stuff
    // currently we just want to shove a cache path onto the static assets so we can get the hash onto the filename
    //this means we can set the cache for eternity
    {
        mode: isDev ? 'development' : 'production',
        entry: assetEntries,
        output: {
            path: path.join(distPath, 'assets'),
            filename: '.[name].ignoreme'
        },
        module: {
            rules: [
                {
                    test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: '[name].[hash].[ext]'
                        }
                    }]
                }
            ]
        },
        plugins: [
            manifestPlugin
        ]
    },
    //this is the client side
    {
        mode: isDev ? 'development' : 'production',
        entry: './static/main.js',
        output: {
            filename: outputname,
            path: distPath,
            publicPath: publicPath
        },
        resolve: {
            modules: ['./static', "./node_modules"],
            alias: {
                //is this safe?
                goldenlayout: path.resolve(__dirname, 'node_modules/golden-layout/'),
                lzstring: path.resolve(__dirname, 'node_modules/lz-string/'),
                filesaver: path.resolve(__dirname, 'node_modules/file-saver/')
            }
        },
        stats: "normal",
        devtool: 'source-map',
        optimization: {
            minimize: !isDev,
            minimizer: [new UglifyJsPlugin({
                exclude: /\/vs/,
                parallel: true,
                uglifyOptions: {
                    output: {
                        comments: false,
                        beautify: false
                    }
                }
            })]
        },
        module: {
            rules: [
                {
                    test: /\.css$/,
                    exclude: path.resolve(__dirname, 'static/themes/'),
                    use: [
                        {
                            loader: MiniCssExtractPlugin.loader,
                            options: {
                                publicPath: './',
                                hmr: isDev
                            }
                        },
                        'css-loader'
                    ]
                },
                {
                    test: /\.css$/,
                    include: path.resolve(__dirname, 'static/themes/'),
                    use: ['css-loader']
                },
                {
                    test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                    loader: 'url-loader?limit=8192'
                },
                {
                    test: /\.(html)$/,
                    loader: 'html-loader',
                    options: {
                        minimize: !isDev
                    }
                }
            ]
        },
        plugins: plugins
    }

];
<|endoftext|>


<commit_before>import marginMixin from '../mixin/margin';

export default function (UIkit) {

    UIkit.component('grid', {

        mixins: [marginMixin],

        defaults: {
            margin: 'uk-grid-margin',
            rowFirst: 'uk-grid-first'
        }

    });

}
<commit_msg>renamed "margin" class param to "cls"<commit_after>import marginMixin from '../mixin/margin';

export default function (UIkit) {

    UIkit.component('grid', {

        mixins: [marginMixin],

        defaults: {
            cls: 'uk-grid-margin',
            rowFirst: 'uk-grid-first'
        }

    });

}
<|endoftext|>


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

module.exports = {
  entry: {
    app: './src/main.js'
  },

  output: {
    path: path.join(__dirname, 'build'),
    filename: 'dist/bundle.js'
  },
  resolveLoader: {
    root: path.join(__dirname, 'node_modules'),
  },
  module: {
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.html$/,
        loader: 'vue-html'
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  devServer: {
    historyApiFallback: false,
    hot: true
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vuejs.github.io/vue-loader/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new webpack.optimize.OccurenceOrderPlugin()
  ])
}
<commit_msg>move bundle to public<commit_after>var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: {
    app: './src/main.js'
  },

  output: {
    path: path.join(__dirname, 'public/dist'),
    filename: 'bundle.js'
  },
  resolveLoader: {
    root: path.join(__dirname, 'node_modules'),
  },
  module: {
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.html$/,
        loader: 'vue-html'
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  devServer: {
    historyApiFallback: false,
    hot: true
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vuejs.github.io/vue-loader/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new webpack.optimize.OccurenceOrderPlugin()
  ])
}
<|endoftext|>


<commit_before>import { REPLMachine } from './REPLMachine';
import { DOMSerializer } from './domserializer';

import * as htmlmodule from './htmlmodule';
import { main, section, iframe, button, details, summary, script } from './htmlmodule';
import { codebox, markupbox } from './codemirror';

import './replsite.css';

const START_INDEX = 0;

const serializer = new DOMSerializer;

let es2016support = false;
try {
    new Function('({test}) => test');
    es2016support = true;
}
const BABEL_STANDALONE_URL = 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.14.0/babel.min.js';

window.Babel = { transform : code => ({ code }) };

const babel = (input) => {
    const Babel = window.Babel;
    const res = Babel.transform(input, { presets: ['es2015'] });
    return res.code.replace(/^'use\sstrict';\n\n/, '');
}

export class REPLSite {
    constructor(data) {
        this.data = data;
        this.replmachine = new REPLMachine({
            input : this,
            output : this
        });
        this.node = this.assemble();
        window.onresize = () => this.refresh();
    }
    get value() {
        return babel(this.inputcode.value);
    }
    set value(value) {
        const { markupview, outputcode } = this;
        const { body } = this.outputwin.contentDocument;
        body.innerHTML = '';
        if(markupview.open) outputcode.value = '';
        if(value instanceof Error) {
            body.textContent = value;
        } else {
            try {
                const resultnode = typeof value === 'function'?
                    value(htmlmodule) :
                    value;
                if(resultnode) {
                    body.appendChild(resultnode);
                    outputcode.value = serializer.serializeToString(resultnode);
                }
            }
            catch(error) {
                body.textContent = error;
            }
        }
    }
    assemble() {
        return main({
            className : 'replsite',
            children : [
                section([
                    this.inputcode = codebox({
                        className : 'inputcode',
                        value : this.data[this.index]
                    }),
                    this.prevbutton = button({
                        id : 'replbuttonprev',
                        className : 'prevbutton',
                        onclick : () => this.prev(),
                        children : 'prev'
                    }),
                    this.nextbutton = button({
                        id : 'replbuttonnext',
                        className : 'nextbutton',
                        onclick : () => this.next(),
                        children : 'next'
                    })
                ]),
                section([
                    this.outputwin = iframe({
                        className : 'outputwin',
                        onload : () => this.onready()
                    }),
                    this.markupview = details({
                        className : 'markupview',
                        ontoggle : () => this.refresh(),
                        children : [
                            summary({
                                id : 'markuptoggle',
                                className : 'markuptoggle',
                                children : 'markup'
                            }),
                            this.outputcode = markupbox({
                                className : 'outputcode'
                            })
                        ]
                    })
                ])
            ]
        });
    }
    onready() {
        if(es2016support) this.start();
        else {
            document.body.append(script({
                onload : () => this.start(),
                src : BABEL_STANDALONE_URL
            }));
        }
    }
    start() {
        this.inputcode.onchange = () => this.replmachine.loop();
        window.onkeydown = ({ target, keyCode }) => {
            if(target.tagName !== 'TEXTAREA') {
                if(keyCode === 37) this.prev();
                if(keyCode === 39) this.next();
                if(keyCode === 38) this.markupview.open = true;
                if(keyCode === 40) this.markupview.open = false;
            }
        }
        this.refresh();
    }
    refresh() {
        const outputcode = this.outputcode;
        const innerHeight = window.innerHeight;
        this.outputwin.height = this.markupview.open?
            (innerHeight - outputcode.height) + 'px' :
            innerHeight + 'px';
        this.inputcode.refresh();
        this.replmachine.loop();
    }
    prev() {
        const data = this.data;
        this.index--;
        if(this.index < 0) this.index = data.length - 1;
        this.inputcode.value = data[this.index];
    }
    next() {
        const data = this.data;
        this.index++;
        if(this.index === data.length) this.index = 0;
        this.inputcode.value = data[this.index];
    }
}

Object.defineProperties(REPLSite.prototype, {
    data : { writable : true, value : [] },
    node : { writable : true, value : null },
    index :  { writable : true, value : START_INDEX },
});
<commit_msg>fix try catch<commit_after>import { REPLMachine } from './REPLMachine';
import { DOMSerializer } from './domserializer';

import * as htmlmodule from './htmlmodule';
import { main, section, iframe, button, details, summary, script } from './htmlmodule';
import { codebox, markupbox } from './codemirror';

import './replsite.css';

const START_INDEX = 0;

const serializer = new DOMSerializer;

let es2016support;
try {
    new Function('({test}) => test');
    es2016support = true;
}
catch(error) {
    es2016support = false;
}
const BABEL_STANDALONE_URL = 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.14.0/babel.min.js';

window.Babel = { transform : code => ({ code }) };

const babel = (input) => {
    const Babel = window.Babel;
    const res = Babel.transform(input, { presets: ['es2015'] });
    return res.code.replace(/^'use\sstrict';\n\n/, '');
}

export class REPLSite {
    constructor(data) {
        this.data = data;
        this.replmachine = new REPLMachine({
            input : this,
            output : this
        });
        this.node = this.assemble();
        window.onresize = () => this.refresh();
    }
    get value() {
        return babel(this.inputcode.value);
    }
    set value(value) {
        const { markupview, outputcode } = this;
        const { body } = this.outputwin.contentDocument;
        body.innerHTML = '';
        if(markupview.open) outputcode.value = '';
        if(value instanceof Error) {
            body.textContent = value;
        } else {
            try {
                const resultnode = typeof value === 'function'?
                    value(htmlmodule) :
                    value;
                if(resultnode) {
                    body.appendChild(resultnode);
                    outputcode.value = serializer.serializeToString(resultnode);
                }
            }
            catch(error) {
                body.textContent = error;
            }
        }
    }
    assemble() {
        return main({
            className : 'replsite',
            children : [
                section([
                    this.inputcode = codebox({
                        className : 'inputcode',
                        value : this.data[this.index]
                    }),
                    this.prevbutton = button({
                        id : 'replbuttonprev',
                        className : 'prevbutton',
                        onclick : () => this.prev(),
                        children : 'prev'
                    }),
                    this.nextbutton = button({
                        id : 'replbuttonnext',
                        className : 'nextbutton',
                        onclick : () => this.next(),
                        children : 'next'
                    })
                ]),
                section([
                    this.outputwin = iframe({
                        className : 'outputwin',
                        onload : () => this.onready()
                    }),
                    this.markupview = details({
                        className : 'markupview',
                        ontoggle : () => this.refresh(),
                        children : [
                            summary({
                                id : 'markuptoggle',
                                className : 'markuptoggle',
                                children : 'markup'
                            }),
                            this.outputcode = markupbox({
                                className : 'outputcode'
                            })
                        ]
                    })
                ])
            ]
        });
    }
    onready() {
        if(es2016support) this.start();
        else {
            document.body.append(script({
                onload : () => this.start(),
                src : BABEL_STANDALONE_URL
            }));
        }
    }
    start() {
        this.inputcode.onchange = () => this.replmachine.loop();
        window.onkeydown = ({ target, keyCode }) => {
            if(target.tagName !== 'TEXTAREA') {
                if(keyCode === 37) this.prev();
                if(keyCode === 39) this.next();
                if(keyCode === 38) this.markupview.open = true;
                if(keyCode === 40) this.markupview.open = false;
            }
        }
        this.refresh();
    }
    refresh() {
        const outputcode = this.outputcode;
        const innerHeight = window.innerHeight;
        this.outputwin.height = this.markupview.open?
            (innerHeight - outputcode.height) + 'px' :
            innerHeight + 'px';
        this.inputcode.refresh();
        this.replmachine.loop();
    }
    prev() {
        const data = this.data;
        this.index--;
        if(this.index < 0) this.index = data.length - 1;
        this.inputcode.value = data[this.index];
    }
    next() {
        const data = this.data;
        this.index++;
        if(this.index === data.length) this.index = 0;
        this.inputcode.value = data[this.index];
    }
}

Object.defineProperties(REPLSite.prototype, {
    data : { writable : true, value : [] },
    node : { writable : true, value : null },
    index :  { writable : true, value : START_INDEX },
});
<|endoftext|>


<commit_before>///////////
// Webpack.config.js
//
// Uses Webpack to build our javascript assets. Creates source maps
// as well.
//
// All considerit servers serve javascript compiled through this
// script, both dev and production.
//
// In development, you can have Webpack watch for changes so that the
// compilation is automatic:
//    > node_modules/webpack/bin/webpack.js --progress --colors --watch
//    (shortcut:   >  bin/webpack )
//
// To compile for production, set the environment variable
//      BUILD_PRODUCTION
//
// In production, if we're using a non-local asset host like Cloudfront,
// this will also upload the built javascript (and images) to the configured
// host.
//
// This process replaces Rails' asset pipeline.

///////////////////////
// Input
//
// These variables are pulled out because they're most likely to be configured
// as part of writing an application.

/////
// Global variables
// These variables will be made global on Window for use in all js files
global_variables = {
  '_': "vendor/underscore",
  $: "vendor/jquery",
  jQuery: "vendor/jquery",
  React: "vendor/react"
}

/////
// Entry points
// These are the different entry points to the application that will be
// compiled. All required files starting from the entry point will be compiled
// into the respective build.
entry_points = {
  franklin: './@client/franklin.coffee',
  saas_landing_page: './@client/saas_landing_page.coffee'
}

////////////////////////////////////////
// Innards

var webpack = require('webpack'),
    path = require('path'),
    is_dev = !JSON.parse(process.env.BUILD_PRODUCTION || 'false');

config = {

  debug : is_dev,
  displayErrorDetails : true,
  outputPathinfo : true,
  devtool : is_dev ? 'eval' : 'sourcemap',

  entry: entry_points,

  // We output build javascript to public/build.
  // A cache-busting digest is appended when we're in production
  output: {
    path: './public/build',
    filename: is_dev ? "[name].js" : "[name].[chunkhash].js"
  },

  module: {

    // Enables compilation of coffee into java
    loaders: [
      { test: /\.coffee$/, loader: 'coffee-loader' },
    ],

    // Files that have already been compiled with webpack
    // or something like browserify can be skipped. If they're
    // not, they can sometimes cause Webpack problems...
    noParse: [
      /react\.js$/,
      /jquery\.js$/,
      /quill\.js$/
    ]
  },

  resolve: {
    root: [__dirname, '@client'].join('/'),
    extensions: ['', '.js', '.json', '.coffee']
           // don't have to specify .js etc in requires statements
  },

  plugins: [

    ///////////////
    // DefinePlugin
    //
    // Each instance of a key will be replaced with the
    // value in the build.
    new webpack.DefinePlugin({
      __DEV__: is_dev,
      __PRODUCTION__: !is_dev
    }),

    ///////////////
    // ProvidePlugin
    //
    // Makes these variables global across all javascript files
    new webpack.ProvidePlugin(global_variables),

    ////////////
    // Creates a public/build/manifest.json file that maps from
    // each entry point to the compiled version of it. Useful in
    // particular when the compiled filename includes a digest
    function() {
      this.plugin("done", function(stats) {
        manifest = {}

        for (var prop in config.entry){
          if(prop){
            file = stats.toJson().assetsByChunkName[prop]
            if (typeof file !== 'string')
              file = file[0]

            manifest[prop] = path.join("build", file)
          }
        }
        require("fs").writeFileSync(
          path.join(__dirname, "public", "build", "manifest.json"),
          JSON.stringify(manifest));
      });
    }
  ]
}

/////
// Additional work when we're compiling for production
if(!is_dev){

  var s3 = require('s3'),
      YAML = require('yamljs'),
      CompressionPlugin = require("compression-webpack-plugin")

  config.plugins.push(

    //////
    // Uglify
    // Further compression. Unexpectedly cuts gzipped main js file size in half.
    // This is the slowest part of the process of building.
    new webpack.optimize.UglifyJsPlugin(),

    new webpack.optimize.OccurenceOrderPlugin(),

    //////
    // Compression
    // Gzip the js/sourcemaps coming through the pipeline. Note that the file
    // extension doesn't change. Web servers need to have Content-Encoding gzip
    // set for these files.
    new CompressionPlugin({
        asset: "{file}",
        algorithm: "gzip"
    }),

    /////////
    // Upload to s3 (and as a consequence, Cloudfront)
    //
    // Finally we'll upload these compiled js/source maps to s3, along with
    // syncing the public/images directory.
    function() {
      this.plugin("done", function(stats) {

        local = YAML.load('config/local_environment.yml').default
        if (!local.aws) return // do nothing if aws isn't configured

        var s3_client = s3.createClient({
            s3Options : {
              accessKeyId: local.aws.access_key_id,
              secretAccessKey: local.aws.secret_access_key,
            }})

        // Syncs a directory from this host to s3.
        // set is_gzipped if you want to set the Content-Encoding to gzip for all
        // files in this directory.
        var uploadDir = function(src, dest, is_gzipped) {

          s3_params = {
            Bucket: local.aws.s3_bucket,
            Prefix: dest,
            Expires: new Date(new Date().setYear(new Date().getFullYear() + 1)),
            CacheControl: 'public, max-age=31557600'
          }

          if (is_gzipped)
            s3_params.ContentEncoding = 'gzip'

          var uploader = s3_client.uploadDir({
            localDir: src,
            deleteRemoved: false, // remove s3 objects that lack
                                  // a corresponding local file.
            s3Params: s3_params
          })

          uploader.on('error', function(err) {
            console.error("unable to sync:", err.stack)
          })
          uploader.on('end', function() {
            console.log("done uploading")
          })
          uploader.on('fileUploadEnd', function(path, key) {
            console.log("UPLOADED ", path)
          })
        }

        // sync js
        uploadDir( 'public/build', 'build', true)

        // sync images
        uploadDir( 'public/images', 'images')

      })
    }
  )
}

console.log("BUILDING FOR " + (is_dev ? "DEVELOPMENT" : "PRODUCTION"))

module.exports = config<commit_msg>prevent error<commit_after>///////////
// Webpack.config.js
//
// Uses Webpack to build our javascript assets. Creates source maps
// as well.
//
// All considerit servers serve javascript compiled through this
// script, both dev and production.
//
// In development, you can have Webpack watch for changes so that the
// compilation is automatic:
//    > node_modules/webpack/bin/webpack.js --progress --colors --watch
//    (shortcut:   >  bin/webpack )
//
// To compile for production, set the environment variable
//      BUILD_PRODUCTION
//
// In production, if we're using a non-local asset host like Cloudfront,
// this will also upload the built javascript (and images) to the configured
// host.
//
// This process replaces Rails' asset pipeline.

///////////////////////
// Input
//
// These variables are pulled out because they're most likely to be configured
// as part of writing an application.

/////
// Global variables
// These variables will be made global on Window for use in all js files
global_variables = {
  '_': "vendor/underscore",
  $: "vendor/jquery",
  jQuery: "vendor/jquery",
  React: "vendor/react"
}

/////
// Entry points
// These are the different entry points to the application that will be
// compiled. All required files starting from the entry point will be compiled
// into the respective build.
entry_points = {
  franklin: './@client/franklin.coffee',
  saas_landing_page: './@client/saas_landing_page.coffee'
}

////////////////////////////////////////
// Innards

var webpack = require('webpack'),
    path = require('path'),
    is_dev = !JSON.parse(process.env.BUILD_PRODUCTION || 'false');

config = {

  debug : is_dev,
  displayErrorDetails : true,
  outputPathinfo : true,
  devtool : is_dev ? 'eval' : 'sourcemap',

  entry: entry_points,

  // We output build javascript to public/build.
  // A cache-busting digest is appended when we're in production
  output: {
    path: './public/build',
    filename: is_dev ? "[name].js" : "[name].[chunkhash].js"
  },

  module: {

    // Enables compilation of coffee into java
    loaders: [
      { test: /\.coffee$/, loader: 'coffee-loader' },
    ],

    // Files that have already been compiled with webpack
    // or something like browserify can be skipped. If they're
    // not, they can sometimes cause Webpack problems...
    noParse: [
      /react\.js$/,
      /jquery\.js$/,
      /quill\.js$/
    ]
  },

  resolve: {
    root: [__dirname, '@client'].join('/'),
    extensions: ['', '.js', '.json', '.coffee']
           // don't have to specify .js etc in requires statements
  },

  plugins: [

    ///////////////
    // DefinePlugin
    //
    // Each instance of a key will be replaced with the
    // value in the build.
    new webpack.DefinePlugin({
      __DEV__: is_dev,
      __PRODUCTION__: !is_dev
    }),

    ///////////////
    // ProvidePlugin
    //
    // Makes these variables global across all javascript files
    new webpack.ProvidePlugin(global_variables),

    ////////////
    // Creates a public/build/manifest.json file that maps from
    // each entry point to the compiled version of it. Useful in
    // particular when the compiled filename includes a digest
    function() {
      this.plugin("done", function(stats) {
        manifest = {}

        for (var prop in config.entry){
          if(prop){
            file = stats.toJson().assetsByChunkName[prop]
            if (file && typeof file !== 'string')
              file = file[0]

            manifest[prop] = path.join("build", file)
          }
        }
        require("fs").writeFileSync(
          path.join(__dirname, "public", "build", "manifest.json"),
          JSON.stringify(manifest));
      });
    }
  ]
}

/////
// Additional work when we're compiling for production
if(!is_dev){

  var s3 = require('s3'),
      YAML = require('yamljs'),
      CompressionPlugin = require("compression-webpack-plugin")

  config.plugins.push(

    //////
    // Uglify
    // Further compression. Unexpectedly cuts gzipped main js file size in half.
    // This is the slowest part of the process of building.
    new webpack.optimize.UglifyJsPlugin(),

    new webpack.optimize.OccurenceOrderPlugin(),

    //////
    // Compression
    // Gzip the js/sourcemaps coming through the pipeline. Note that the file
    // extension doesn't change. Web servers need to have Content-Encoding gzip
    // set for these files.
    new CompressionPlugin({
        asset: "{file}",
        algorithm: "gzip"
    }),

    /////////
    // Upload to s3 (and as a consequence, Cloudfront)
    //
    // Finally we'll upload these compiled js/source maps to s3, along with
    // syncing the public/images directory.
    function() {
      this.plugin("done", function(stats) {

        local = YAML.load('config/local_environment.yml').default
        if (!local.aws) return // do nothing if aws isn't configured

        var s3_client = s3.createClient({
            s3Options : {
              accessKeyId: local.aws.access_key_id,
              secretAccessKey: local.aws.secret_access_key,
            }})

        // Syncs a directory from this host to s3.
        // set is_gzipped if you want to set the Content-Encoding to gzip for all
        // files in this directory.
        var uploadDir = function(src, dest, is_gzipped) {

          s3_params = {
            Bucket: local.aws.s3_bucket,
            Prefix: dest,
            Expires: new Date(new Date().setYear(new Date().getFullYear() + 1)),
            CacheControl: 'public, max-age=31557600'
          }

          if (is_gzipped)
            s3_params.ContentEncoding = 'gzip'

          var uploader = s3_client.uploadDir({
            localDir: src,
            deleteRemoved: false, // remove s3 objects that lack
                                  // a corresponding local file.
            s3Params: s3_params
          })

          uploader.on('error', function(err) {
            console.error("unable to sync:", err.stack)
          })
          uploader.on('end', function() {
            console.log("done uploading")
          })
          uploader.on('fileUploadEnd', function(path, key) {
            console.log("UPLOADED ", path)
          })
        }

        // sync js
        uploadDir( 'public/build', 'build', true)

        // sync images
        uploadDir( 'public/images', 'images')

      })
    }
  )
}

console.log("BUILDING FOR " + (is_dev ? "DEVELOPMENT" : "PRODUCTION"))

module.exports = config<|endoftext|>


<commit_before>let Firebase = require('firebase');
let html = require('./html-escaping');
require('./welcome')();
let base = new Firebase('https://scorching-inferno-1467.firebaseio.com/');

let auth = base.getAuth();

const setTitle = () => {
  document.getElementById('company-name').innerHTML = JSON.parse(localStorage.punchtime).company.name;
};

// if the localstorage hasn't been set, go to settings
if (!localStorage.punchtime) {
  location.href = 'settings.html';
}

if (auth) {
  console.log('logged in with: ' + auth.uid);
  setTitle();
} else {
  console.warn('not logged in');
  location.href = '/login/';
}

let pulses = []; // the graph is made from this object

const addEmployee = (employee) => {
  let employeePulses = [];
  for (let pulse in employee.pulses) {
    if (employee.pulses.hasOwnProperty(pulse)) {
      base.child('pulses').child(pulse).once('value', (snap) => {
        try {
          let name = employee.name,
            checkin = new Date(parseInt(snap.val().checkin)),
            note = snap.val().note,
            address = snap.val().addressStreet,
            checkout;
          if (snap.val().checkout && snap.val().checkout !== 0) {
            checkout = new Date(parseInt(snap.val().checkout));
          } else {
            checkout = new Date();
          }
          pulses.push([name, address, checkin, checkout]);
          employeePulses.push({
            id: snap.key(),
            latitude: snap.val().latitude,
            longitude: snap.val().longitude,
            checkin: new Date(parseInt(snap.val().checkin)),
            checkout: new Date(parseInt(snap.val().checkout)),
            address: snap.val().addressStreet,
            note: snap.val().note,
            confirmed: parseBool(snap.val().confirmed)
          });
          drawChart();
        } catch (e) {
          console.log(`/pulses/${snap.key()} in /users/${employee.name} has a problem.`);
        }
      });
    }
  }

  let image = employee.image || '/src/img/icons/empty.svg',
    name = employee.name,
    status = 'good';

  let empl = document.createElement('div');
  empl.classList.add('employee');
  // empl.dataset.id = id;
  empl.innerHTML = html `

${name}

${status}`;
  document.querySelector('.employee-container').appendChild(empl);

  empl.addEventListener('click', () => {
    addOverview(employeePulses,employee);
  });

  let flexfix = document.createElement('div');
  flexfix.classList.add('👻');
  document.querySelector('.employee-container').appendChild(flexfix);
};

let addOverview = (pulses,employee) => {
  let overview = document.createElement('div');
  overview.classList.add('overview');
  let overviewContent = document.createElement('div');
  overviewContent.classList.add('overview--content');
  overviewContent.innerHTML = html `<h2 class="overview--title">${employee.name}</h2>`;
  let timeline = document.createElement('div');
  timeline.classList.add('timeline');
  // todo: take day in account
//   timeline.innerHTML = html `
//

//
Thursay, 28 April

//
`;

  for (let i in pulses) {
    addToTimeline(pulses[i],pulses[i-1],timeline);
  }

  overviewContent.appendChild(timeline);
  overview.appendChild(overviewContent);

  document.body.insertBefore(overview, document.querySelector('.employees'));
  overview.addEventListener('click', (e) => {
    if (e.target.classList.contains('overview')) {
      e.target.parentNode.removeChild(e.target);
    } else if (e.target.parentNode.classList.contains('timeline--item__still')) {
      toggleStatus(e.target.parentNode);
    } else if (e.target.classList.contains('timeline--item__still')) {
      toggleStatus(e.target);
    }
  });
};

let parseBool = (string) => {
  if (string === 'true' || string === true) {
    return true;
  } else {
    return false;
  }
};

let addToTimeline = (current, previous, timeline) => {
  if (previous) {
    let diff = new Date(current.checkin - previous.checkout);
    timeline.innerHTML += html `

${diff.getHours() - 1}h ${diff.getMinutes() + Math.round(diff.getSeconds() / 60)}m

`;
  }
  timeline.innerHTML += html `

${current.address}

${current.note}

    <time datetime="${current.checkin.toISOString()}">${current.checkin.getHours()}:${current.checkin.getMinutes() < 10 ? 0 : ''}${current.checkin.getMinutes()}</time>→
    <time datetime="${current.checkout.toISOString()}">${current.checkout.getHours()}:${current.checkout.getMinutes() < 10 ? 0 : ''}${current.checkout.getMinutes()}</time>

`;
};

let toggleStatus = (element) => {
  if (element.classList.contains('timeline--item__unconfirmed')) {
    element.classList.remove('timeline--item__unconfirmed');
    element.classList.add('timeline--item__confirmed');
    base.child('pulses')
      .child(element.dataset.pulse)
      .child('confirmed')
      .set('true');
  } else if (element.classList.contains('timeline--item__confirmed')) {
    element.classList.remove('timeline--item__confirmed');
    element.classList.add('timeline--item__unconfirmed');
    base.child('pulses')
      .child(element.dataset.pulse)
      .child('confirmed')
      .set('false');
  }
};

let getEmployees = (id, callback) => {
  base.child('companies').child(id).child('employees').on('child_added', (snapshot) => {
    base.child('users').child(snapshot.key()).once('value', (snap) => {
      callback(snap.val());
    });
  });
};

getEmployees(JSON.parse(localStorage.punchtime).company.id, addEmployee);

const drawChart = () => {
  let chart = new google.visualization.Timeline(document.getElementById('timeline'));
  let dataTable = new google.visualization.DataTable();

  dataTable.addColumn({
    type: 'string',
    id: 'employee'
  });
  dataTable.addColumn({
    type: 'string',
    id: 'note'
  });
  dataTable.addColumn({
    type: 'date',
    id: 'Start'
  });
  dataTable.addColumn({
    type: 'date',
    id: 'End'
  });
  dataTable.addRows(pulses);

  chart.draw(dataTable, {
    timeline: {
      singleColor: '#3B4358'
    }
  });
};
google.charts.load('current', {
  'packages': ['timeline']
});
google.charts.setOnLoadCallback(drawChart);

/*
 * listener on resize to reload graph
 * Will refresh the graph if there is 250 ms after a resize event
 */
var resizeTimer;
window.addEventListener('resize', () => {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(() => {
    drawChart();
  }, 250);
});
<commit_msg>improvements to timeline<commit_after>let Firebase = require('firebase');
let html = require('./html-escaping');
require('./welcome')();
let base = new Firebase('https://scorching-inferno-1467.firebaseio.com/');

let auth = base.getAuth();

const setTitle = () => {
  document.getElementById('company-name').innerHTML = JSON.parse(localStorage.punchtime).company.name;
};

// if the localstorage hasn't been set, go to settings
if (!localStorage.punchtime) {
  location.href = 'settings.html';
}

if (auth) {
  console.log('logged in with: ' + auth.uid);
  setTitle();
} else {
  console.warn('not logged in');
  location.href = '/login/';
}

let pulses = []; // the graph is made from this object

const addEmployee = (employee) => {
  let employeePulses = [];
  for (let pulse in employee.pulses) {
    if (employee.pulses.hasOwnProperty(pulse)) {
      base.child('pulses').child(pulse).once('value', (snap) => {
        try {
          let name = employee.name,
            checkin = new Date(parseInt(snap.val().checkin)),
            note = snap.val().note,
            address = snap.val().addressStreet,
            checkout;
          if (snap.val().checkout && snap.val().checkout !== 0) {
            checkout = new Date(parseInt(snap.val().checkout));
          } else {
            checkout = new Date();
          }
          pulses.push([name, address, checkin, checkout]);
          employeePulses.push({
            id: snap.key(),
            latitude: snap.val().latitude,
            longitude: snap.val().longitude,
            checkin: new Date(parseInt(snap.val().checkin)),
            checkout: new Date(parseInt(snap.val().checkout)),
            address: snap.val().addressStreet,
            city: snap.val().addressCityCountry,
            note: snap.val().note,
            confirmed: parseBool(snap.val().confirmed)
          });
          drawChart();
        } catch (e) {
          console.log(`/pulses/${snap.key()} in /users/${employee.name} has a problem.`);
        }
      });
    }
  }

  let image = employee.image || '/src/img/icons/empty.svg',
    name = employee.name,
    status = 'good';

  let empl = document.createElement('div');
  empl.classList.add('employee');
  // empl.dataset.id = id;
  empl.innerHTML = html `

${name}

${status}`;
  document.querySelector('.employee-container').appendChild(empl);

  empl.addEventListener('click', () => {
    addOverview(employeePulses,employee);
  });

  let flexfix = document.createElement('div');
  flexfix.classList.add('👻');
  document.querySelector('.employee-container').appendChild(flexfix);
};

let addOverview = (pulses,employee) => {
  let overview = document.createElement('div');
  overview.classList.add('overview');
  let overviewContent = document.createElement('div');
  overviewContent.classList.add('overview--content');
  overviewContent.innerHTML = html `<h2 class="overview--title">${employee.name}</h2>`;
  let timeline = document.createElement('div');
  timeline.classList.add('timeline');
  // todo: take day in account
//   timeline.innerHTML = html `
//

//
Thursay, 28 April

//
`;

  if (pulses.length === 0) {
    timeline.innerHTML += `

No checkins

    `;
  }
  for (let i in pulses) {
    addToTimeline(pulses[i],pulses[i-1],timeline);
  }

  overviewContent.appendChild(timeline);
  overview.appendChild(overviewContent);

  document.body.insertBefore(overview, document.querySelector('.employees'));
  overview.addEventListener('click', (e) => {
    if (e.target.classList.contains('overview')) {
      e.target.parentNode.removeChild(e.target);
    } else if (e.target.parentNode.classList.contains('timeline--item__still')) {
      toggleStatus(e.target.parentNode);
    } else if (e.target.classList.contains('timeline--item__still')) {
      toggleStatus(e.target);
    }
  });
};

let parseBool = (string) => {
  if (string === 'true' || string === true) {
    return true;
  } else {
    return false;
  }
};

let addToTimeline = (current, previous, timeline) => {
  if (previous) {
    let diff = new Date(current.checkin - previous.checkout);
    timeline.innerHTML += html `

${diff.getHours > 0 ? (diff.getHours() - 1)+' h' : ''} ${diff.getMinutes() + Math.round(diff.getSeconds() / 60)} min

`;
  }
  timeline.innerHTML += html `

${current.address}

${current.city}

${current.note}

    <time datetime="${current.checkin.toISOString()}">${current.checkin.getHours()}:${current.checkin.getMinutes() < 10 ? 0 : ''}${current.checkin.getMinutes()}</time>→
    <time datetime="${current.checkout.toISOString()}">${current.checkout.getHours()}:${current.checkout.getMinutes() < 10 ? 0 : ''}${current.checkout.getMinutes()}</time>

`;
};

let toggleStatus = (element) => {
  if (element.classList.contains('timeline--item__unconfirmed')) {
    element.classList.remove('timeline--item__unconfirmed');
    element.classList.add('timeline--item__confirmed');
    base.child('pulses')
      .child(element.dataset.pulse)
      .child('confirmed')
      .set('true');
  } else if (element.classList.contains('timeline--item__confirmed')) {
    element.classList.remove('timeline--item__confirmed');
    element.classList.add('timeline--item__unconfirmed');
    base.child('pulses')
      .child(element.dataset.pulse)
      .child('confirmed')
      .set('false');
  }
};

let getEmployees = (id, callback) => {
  base.child('companies').child(id).child('employees').on('child_added', (snapshot) => {
    base.child('users').child(snapshot.key()).once('value', (snap) => {
      callback(snap.val());
    });
  });
};

getEmployees(JSON.parse(localStorage.punchtime).company.id, addEmployee);

const drawChart = () => {
  let chart = new google.visualization.Timeline(document.getElementById('timeline'));
  let dataTable = new google.visualization.DataTable();

  dataTable.addColumn({
    type: 'string',
    id: 'employee'
  });
  dataTable.addColumn({
    type: 'string',
    id: 'note'
  });
  dataTable.addColumn({
    type: 'date',
    id: 'Start'
  });
  dataTable.addColumn({
    type: 'date',
    id: 'End'
  });
  dataTable.addRows(pulses);

  chart.draw(dataTable, {
    timeline: {
      singleColor: '#3B4358'
    }
  });
};
google.charts.load('current', {
  'packages': ['timeline']
});
google.charts.setOnLoadCallback(drawChart);

/*
 * listener on resize to reload graph
 * Will refresh the graph if there is 250 ms after a resize event
 */
var resizeTimer;
window.addEventListener('resize', () => {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(() => {
    drawChart();
  }, 250);
});
<|endoftext|>


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

var isProduction = process.env.NODE_ENV === 'production';

module.exports = {
  devtool: 'eval',
  entry: isProduction ?
    [ './src/index' ] :
    [
      'webpack-dev-server/client?http://localhost:3000',
      'webpack/hot/only-dev-server',
      './src/index'
    ],
  output: {
    path: path.join(__dirname, 'static'),
    filename: 'bundle.js',
    publicPath: isProduction ? 'static/' : '/static/'
  },
  plugins:  isProduction ?
    [new webpack.NoErrorsPlugin()] :
    [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin()
    ],
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loaders: isProduction ? ['babel'] : ['react-hot', 'babel'],
      include: path.join(__dirname, 'src'),
      exclude: path.join(__dirname, 'src', 'demo', 'FormattedText.jsx')
    }, {
      test: /intl-messageformat\/dist\/locale-data\/.*/,
      loaders: ['imports?IntlMessageFormat=intl-messageformat']
    }]
  }
};
<commit_msg>fix index path<commit_after>var path = require('path');
var webpack = require('webpack');

var isProduction = process.env.NODE_ENV === 'production';

module.exports = {
  devtool: 'eval',
  entry: isProduction ?
    [ './src/demo/index' ] :
    [
      'webpack-dev-server/client?http://localhost:3000',
      'webpack/hot/only-dev-server',
      './src/demo/index'
    ],
  output: {
    path: path.join(__dirname, 'static'),
    filename: 'bundle.js',
    publicPath: isProduction ? 'static/' : '/static/'
  },
  plugins:  isProduction ?
    [new webpack.NoErrorsPlugin()] :
    [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin()
    ],
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loaders: isProduction ? ['babel'] : ['react-hot', 'babel'],
      include: path.join(__dirname, 'src'),
      exclude: path.join(__dirname, 'src', 'demo', 'FormattedText.jsx')
    }, {
      test: /intl-messageformat\/dist\/locale-data\/.*/,
      loaders: ['imports?IntlMessageFormat=intl-messageformat']
    }]
  }
};
<|endoftext|>


<commit_before>/**
 * AngularJS wrapper for Drupal
 *
 * @author Hein Bekker <hein@netbek.co.za>
 * @copyright (c) 2015 Hein Bekker
 * @license http://www.gnu.org/licenses/agpl-3.0.txt AGPLv3
 */

(function (window, angular, undefined) {
	'use strict';

	angular
		.module('nb.drupal', [])
		.factory('Drupal', ['$window', function Drupal ($window) {
				return $window.Drupal;
			}])
		.run(runBlock);

	// Invoke at runtime to allow factory to delete global reference.
	runBlock.$inject = ['Drupal'];
	function runBlock (Drupal) {
	}
})(window, window.angular);<commit_msg>Fix for IE8<commit_after>/**
 * AngularJS wrapper for Drupal
 *
 * @author Hein Bekker <hein@netbek.co.za>
 * @copyright (c) 2015 Hein Bekker
 * @license http://www.gnu.org/licenses/agpl-3.0.txt AGPLv3
 */

(function (window, angular, undefined) {
	'use strict';

	angular
		.module('nb.drupal', [])
		.factory('Drupal', ['$window', function ($window) {
				return $window.Drupal;
			}]);
})(window, window.angular);<|endoftext|>


<commit_before>"use strict";
var webpack = require('webpack');
var path = require('path');
var loaders = require('./webpack.loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
var FaviconsWebpackPlugin = require('favicons-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

const HOST = process.env.HOST || "127.0.0.1";
const PORT = process.env.PORT || "8888";

loaders.push({
	test: /\.scss$/,
	loader: ExtractTextPlugin.extract('style', 'css?sourceMap&localIdentName=[local]___[hash:base64:5]!sass?outputStyle=expanded'),
	exclude: ['node_modules']
});

module.exports = {
	entry: [
		'react-hot-loader/patch',
		'./src/index.jsx', // your app's entry point
		'./styles/index.scss'
	],
	devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
	output: {
		publicPath: '/',
		path: path.join(__dirname, 'public'),
		filename: 'bundle.js'
	},
	resolve: {
		extensions: ['', '.js', '.jsx']
	},
	module: {
		loaders
	},
	devServer: {
		contentBase: "./public",
		// do not print bundle build stats
		noInfo: true,
		// enable HMR
		hot: true,
		// embed the webpack-dev-server runtime into the bundle
		inline: true,
		// serve index.html in place of 404 responses to allow HTML5 history
		historyApiFallback: true,
		port: PORT,
		host: HOST
	},
	plugins: [
		new webpack.NoErrorsPlugin(),
		new webpack.HotModuleReplacementPlugin(),
	    new ExtractTextPlugin("style.css", {
		      allChunks: true
		}),
		new DashboardPlugin(),
		new HtmlWebpackPlugin({
			template: './src/template.html',
			files: {
				css: ['public/bundle.js']
			}
		}),
		new FaviconsWebpackPlugin('./src/img/favicon.png'),
	]
};
<commit_msg>config digitalocean<commit_after>"use strict";
var webpack = require('webpack');
var path = require('path');
var loaders = require('./webpack.loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
var FaviconsWebpackPlugin = require('favicons-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

const HOST = process.env.HOST || "138.197.93.234";
const PORT = process.env.PORT || "5000";

loaders.push({
	test: /\.scss$/,
	loader: ExtractTextPlugin.extract('style', 'css?sourceMap&localIdentName=[local]___[hash:base64:5]!sass?outputStyle=expanded'),
	exclude: ['node_modules']
});

module.exports = {
	entry: [
		'react-hot-loader/patch',
		'./src/index.jsx', // your app's entry point
		'./styles/index.scss'
	],
	devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
	output: {
		publicPath: '/',
		path: path.join(__dirname, 'public'),
		filename: 'bundle.js'
	},
	resolve: {
		extensions: ['', '.js', '.jsx']
	},
	module: {
		loaders
	},
	devServer: {
		contentBase: "./public",
		// do not print bundle build stats
		noInfo: true,
		// enable HMR
		hot: true,
		// embed the webpack-dev-server runtime into the bundle
		inline: true,
		// serve index.html in place of 404 responses to allow HTML5 history
		historyApiFallback: true,
		port: PORT,
		host: HOST
	},
	plugins: [
		new webpack.NoErrorsPlugin(),
		new webpack.HotModuleReplacementPlugin(),
	    new ExtractTextPlugin("style.css", {
		      allChunks: true
		}),
		new DashboardPlugin(),
		new HtmlWebpackPlugin({
			template: './src/template.html',
			files: {
				css: ['public/bundle.js']
			}
		}),
		new FaviconsWebpackPlugin('./src/img/favicon.png'),
	]
};
<|endoftext|>


<commit_before>(function(global) {
    'use strict';
    // rule-based url building is based on werkzeug.contrib.jsrouting

    function BuildError(message) {
        var args = [];
        var arg_str;
        if (arguments.length > 1) {
            arg_str = JSON.stringify(Array.prototype.slice.call(arguments, 1));
            arg_str = arg_str.substring(1, arg_str.length - 1);
        }
        this.name = 'BuildError';
        this.message = message + (arg_str ? ': ' + arg_str : '');
        // remove the following when http://code.google.com/p/chromium/issues/detail?id=228909 is fixed
        var err = new Error(this.message);
        err.name = this.name;
        return err;
    }
    BuildError.prototype = new Error();
    BuildError.prototype.constructor = BuildError;

    var converter_functions = {
        // Put any converter functions for custom URL converters here. The key is the converter's python class name.
        // If there is no function, encodeURIComponent is used - so there's no need to put default converters here!
        ListConverter: function(value) {
            if (_.isArray(value)) {
                value = value.join('-');
            }
            return encodeURIComponent(value);
        }
    };

    function split_obj(obj) {
        // Splits an object into keys and values (and the object itself for convenience)
        var names = [];
        var values = [];
        for (var name in obj) {
            names.push(name);
            values.push(obj[name]);
        }
        return { names: names, values: values, original: obj };
    }

    function suitable(rule, args) {
        // Checks if a rule is suitable for the given arguments
        var default_args = split_obj(rule.defaults || {});
        var diff_arg_names = _.difference(rule.args, default_args.names);
        var i;

        // If a rule arg that has no default value is missing, the rule is not suitable
        for (i = 0; i < diff_arg_names.length; i++) {
            if (!~_.indexOf(args.names, diff_arg_names[i])) {
                return false;
            }
        }

        if (_.difference(rule.args, args.names).length == 0) {
            if (!rule.defaults) {
                return true;
            }
            // If a default argument is provided with a different value, the rule is not suitable
            for (i = 0; i < default_args.names.length; i++) {
                var key = default_args.names[i];
                var value = default_args.values[i];
                if (value != args.original[key]) {
                    return false;
                }
            }
        }

        return true;
    }

    function build(rule, args) {
        var tmp = [];
        var processed = rule.args.slice();
        for (var i = 0; i < rule.trace.length; i++) {
            var part = rule.trace[i];
            if (part.is_dynamic) {
                var converter = converter_functions[rule.converters[part.data]] || encodeURIComponent;
                var value = converter(args.original[part.data]);
                if (value === null) {
                    return null;
                }
                tmp.push(value);
                processed.push(part.name);
            }
            else {
                tmp.push(part.data);
            }
        }
        tmp = tmp.join('');
        var pipe = tmp.indexOf('|');
        // if we had subdomain routes, the subdomain would come before the pipe
        var url = tmp.substring(pipe + 1);
        var unprocessed = _.difference(args.names, processed);
        return { url: url, unprocessed: unprocessed };
    }

    function fix_params(params) {
        var clean_params = {};
        for (var key in params) {
            var value = params[key];
            if (value === '') {
                continue;
            }
            if (value === undefined || value === null) {
                // convert them to a string
                value = '' + value
            }
            if (!_.isObject(value) || _.isArray(value)) {
                clean_params[key] = value;
            }
        }
        return clean_params;
    }

    function build_url(template, params, fragment) {
        var qsParams, url;

        params = fix_params(params);

        if (typeof template == 'string') {
            url = template;
            qsParams = params || {};
        }
        else if (template.type == 'flask_rules') {
            var args = split_obj(params || {});
            for (var i = 0; i < template.rules.length; i++) {
                var rule = template.rules[i];
                if (suitable(rule, args)) {
                    var res = build(rule, args);
                    if (res === null) {
                        continue;
                    }
                    url = res.url;
                    qsParams = _.pick(params, res.unprocessed);
                    break;
                }
            }

            if (!url) {
                throw new BuildError('Could not build an URL', template.endpoint, params);
            }

            url = Indico.Urls.BasePath + url;
        }
        else {
            throw new BuildError('Invalid URL template', template);
        }

        var qs = $.param(qsParams);
        if (qs) {
            url += (~url.indexOf('?') ? '&' : '?') + qs;
        }
        if (fragment) {
            url += '#' + fragment.replace(/^#/, '');
        }
        return url;
    }

    global.BuildError = BuildError;
    global.build_url = build_url;
})(window);
<commit_msg>Also process URL generated via Javascript<commit_after>(function(global) {
    'use strict';
    // rule-based url building is based on werkzeug.contrib.jsrouting

    function BuildError(message) {
        var args = [];
        var arg_str;
        if (arguments.length > 1) {
            arg_str = JSON.stringify(Array.prototype.slice.call(arguments, 1));
            arg_str = arg_str.substring(1, arg_str.length - 1);
        }
        this.name = 'BuildError';
        this.message = message + (arg_str ? ': ' + arg_str : '');
        // remove the following when http://code.google.com/p/chromium/issues/detail?id=228909 is fixed
        var err = new Error(this.message);
        err.name = this.name;
        return err;
    }
    BuildError.prototype = new Error();
    BuildError.prototype.constructor = BuildError;

    var converter_functions = {
        // Put any converter functions for custom URL converters here. The key is the converter's python class name.
        // If there is no function, encodeURIComponent is used - so there's no need to put default converters here!
        ListConverter: function(value) {
            if (_.isArray(value)) {
                value = value.join('-');
            }
            return encodeURIComponent(value);
        }
    };

    function split_obj(obj) {
        // Splits an object into keys and values (and the object itself for convenience)
        var names = [];
        var values = [];
        for (var name in obj) {
            names.push(name);
            values.push(obj[name]);
        }
        return { names: names, values: values, original: obj };
    }

    function suitable(rule, args) {
        // Checks if a rule is suitable for the given arguments
        var default_args = split_obj(rule.defaults || {});
        var diff_arg_names = _.difference(rule.args, default_args.names);
        var i;

        // If a rule arg that has no default value is missing, the rule is not suitable
        for (i = 0; i < diff_arg_names.length; i++) {
            if (!~_.indexOf(args.names, diff_arg_names[i])) {
                return false;
            }
        }

        if (_.difference(rule.args, args.names).length == 0) {
            if (!rule.defaults) {
                return true;
            }
            // If a default argument is provided with a different value, the rule is not suitable
            for (i = 0; i < default_args.names.length; i++) {
                var key = default_args.names[i];
                var value = default_args.values[i];
                if (value != args.original[key]) {
                    return false;
                }
            }
        }

        return true;
    }

    function build(rule, args) {
        var tmp = [];
        var processed = rule.args.slice();
        for (var i = 0; i < rule.trace.length; i++) {
            var part = rule.trace[i];
            if (part.is_dynamic) {
                var converter = converter_functions[rule.converters[part.data]] || encodeURIComponent;
                var value = converter(args.original[part.data]);
                if (value === null) {
                    return null;
                }
                tmp.push(value);
                processed.push(part.name);
            }
            else {
                tmp.push(part.data);
            }
        }
        tmp = tmp.join('');
        var pipe = tmp.indexOf('|');
        // if we had subdomain routes, the subdomain would come before the pipe
        var url = tmp.substring(pipe + 1);
        var unprocessed = _.difference(args.names, processed);
        return { url: url, unprocessed: unprocessed };
    }

    function fix_params(params) {
        var clean_params = {};
        for (var key in params) {
            var value = params[key];
            if (value === '') {
                continue;
            }
            if (value === undefined || value === null) {
                // convert them to a string
                value = '' + value
            }
            if (!_.isObject(value) || _.isArray(value)) {
                clean_params[key] = value;
            }
        }
        return clean_params;
    }

    function build_url(template, params, fragment) {
        var qsParams, url;

        params = fix_params(params);

        if (typeof template == 'string') {
            url = template;
            qsParams = params || {};
        }
        else if (template.type == 'flask_rules') {
            var args = split_obj(params || {});
            for (var i = 0; i < template.rules.length; i++) {
                var rule = template.rules[i];
                if (suitable(rule, args)) {
                    var res = build(rule, args);
                    if (res === null) {
                        continue;
                    }
                    url = res.url;
                    qsParams = _.pick(params, res.unprocessed);
                    break;
                }
            }

            if (!url) {
                throw new BuildError('Could not build an URL', template.endpoint, params);
            }

            if (window.indicoOfflineSite) {
                // See url_to_static_filename() in modules/events/static/util.py
                url = url.replace(/^\/event\/\d+/, '');
                if (url.indexOf('static/') == 0) {
                    url = url.substring(7);
                }
                url = url.replace(/^\/+/, '').replace(/\/$/, '').replace(/\//g, '--');
                if (!url.match(/.*\.([^\/]+)$/)) {
                    url += '.html';
                }
            } else {
                url = Indico.Urls.BasePath + url;
            }
        }
        else {
            throw new BuildError('Invalid URL template', template);
        }

        if (!window.indicoOfflineSite) {
            var qs = $.param(qsParams);
            if (qs) {
                url += (~url.indexOf('?') ? '&' : '?') + qs;
            }
            if (fragment) {
                url += '#' + fragment.replace(/^#/, '');
            }
        }
        return url;
    }

    global.BuildError = BuildError;
    global.build_url = build_url;
})(window);
<|endoftext|>


<commit_before>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin');
const merge = require('webpack-merge');

const parts = require('./webpack.parts');

const PATHS = {
  app: path.join(__dirname, 'app'),
  style: [
    path.join(__dirname, 'node_modules', 'purecss'),
    path.join(__dirname, 'app', 'main.css')
  ],
  build: path.join(__dirname, 'build')
};

const common = {
  entry: {
    style: PATHS.style,
    app: PATHS.app
  },
  output: {
    path: PATHS.build,
    filename: '[name].js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Webpack demo',
      template: './index.ejs'
    })
  ]
};

module.exports = function(env) {
  if (env === 'production') {
    return merge(
      common,
      {
        devtool: 'source-map',
        output: {
          path: PATHS.build,
          filename: '[name].[chunkhash].js',
          // This is used for code splitting. The setup
          // will work without but this is useful to set.
          chunkFilename: '[chunkhash].js',
          // Tweak this to match your GitHub project name
          publicPath: '/webpack-demo/'
        },
        plugins: [
          new InlineManifestWebpackPlugin({
            name: 'webpackManifest'
          })
        ]
      },
      parts.clean(PATHS.build),
      parts.setFreeVariable(
        'process.env.NODE_ENV',
        'production'
      ),
      parts.extractBundle({
        name: 'vendor',
        entries: ['react']
      }),
      parts.extractBundle({
        name: 'manifest'
      }),
      parts.minify(),
      parts.extractCSS(PATHS.style),
      parts.purifyCSS([PATHS.app])
    );
  }

  return merge(
    common,
    {
      devtool: 'eval-source-map',
      // Disable performance hints during development
      performance: {
        hints: false
      }
    },
    parts.setupCSS(PATHS.style),
    parts.devServer({
      // Customize host/port here if needed
      host: process.env.HOST,
      port: process.env.PORT
    })
  );
};
<commit_msg>Set up better module ids<commit_after>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin');
const merge = require('webpack-merge');

const parts = require('./webpack.parts');

const PATHS = {
  app: path.join(__dirname, 'app'),
  style: [
    path.join(__dirname, 'node_modules', 'purecss'),
    path.join(__dirname, 'app', 'main.css')
  ],
  build: path.join(__dirname, 'build')
};

const common = {
  entry: {
    style: PATHS.style,
    app: PATHS.app
  },
  output: {
    path: PATHS.build,
    filename: '[name].js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Webpack demo',
      template: './index.ejs'
    })
  ]
};

module.exports = function(env) {
  if (env === 'production') {
    return merge(
      common,
      {
        devtool: 'source-map',
        output: {
          path: PATHS.build,
          filename: '[name].[chunkhash].js',
          // This is used for code splitting. The setup
          // will work without but this is useful to set.
          chunkFilename: '[chunkhash].js',
          // Tweak this to match your GitHub project name
          publicPath: '/webpack-demo/'
        },
        plugins: [
          new webpack.HashedModuleIdsPlugin(),
          new InlineManifestWebpackPlugin({
            name: 'webpackManifest'
          })
        ]
      },
      parts.clean(PATHS.build),
      parts.setFreeVariable(
        'process.env.NODE_ENV',
        'production'
      ),
      parts.extractBundle({
        name: 'vendor',
        entries: ['react']
      }),
      parts.extractBundle({
        name: 'manifest'
      }),
      parts.minify(),
      parts.extractCSS(PATHS.style),
      parts.purifyCSS([PATHS.app])
    );
  }

  return merge(
    common,
    {
      devtool: 'eval-source-map',
      // Disable performance hints during development
      performance: {
        hints: false
      },
      plugins: [
        new webpack.NamedModulesPlugin()
      ]
    },
    parts.setupCSS(PATHS.style),
    parts.devServer({
      // Customize host/port here if needed
      host: process.env.HOST,
      port: process.env.PORT
    })
  );
};
<|endoftext|>


<commit_before>/* global require, module, __dirname */

const path = require( 'path' );

module.exports = {
	entry: {
		'./assets/js/amp-blocks-compiled': './blocks/index.js',
		'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle',
		'./assets/js/amp-validation-detail-toggle-compiled': './assets/src/amp-validation-detail-toggle',
		'./assets/js/amp-validation-tooltips-compiled': './assets/src/amp-validation-tooltips',
		'./assets/js/amp-validation-single-error-url-details-compiled': './assets/src/amp-validation-single-error-url-details'
	},
	output: {
		path: path.resolve( __dirname ),
		filename: '[name].js'
	},
	externals: {
		// Make localized data importable.
		'amp-validation-i18n': 'ampValidationI18n'
	},
	devtool: 'cheap-eval-source-map',
	module: {
		rules: [
			{
				test: /\.js$/,
				exclude: /(node_modules)/,
				use: {
					loader: 'babel-loader'
				}
			}
		]
	}
};
<commit_msg>Polyfill wp-i18n and wp-dom-ready for non-Gutenberg 4.9 installs<commit_after>/* global require, module, __dirname */

const path = require( 'path' );

module.exports = {
	entry: {
		'./assets/js/amp-blocks-compiled': './blocks/index.js',
		'./assets/js/wp-i18n-compiled': './assets/js/wp-i18n',
		'./assets/js/wp-dom-ready-compiled': './assets/js/wp-dom-ready',
		'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle',
		'./assets/js/amp-validation-detail-toggle-compiled': './assets/src/amp-validation-detail-toggle',
		'./assets/js/amp-validation-tooltips-compiled': './assets/src/amp-validation-tooltips',
		'./assets/js/amp-validation-single-error-url-details-compiled': './assets/src/amp-validation-single-error-url-details'
	},
	output: {
		path: path.resolve( __dirname ),
		filename: '[name].js'
	},
	externals: {
		// Make localized data importable.
		'amp-validation-i18n': 'ampValidationI18n'
	},
	devtool: 'cheap-eval-source-map',
	module: {
		rules: [
			{
				test: /\.js$/,
				exclude: /(node_modules)/,
				use: {
					loader: 'babel-loader'
				}
			}
		]
	}
};
<|endoftext|>