<commit_before>
module.exports = function(RED) {
    "use strict";

    function SenseEvent(n) {
        RED.nodes.createNode(this,n);
        var senseId = n.senseid,
            eventType = n.eventtype,
            eventName = n.eventname,
            node = this;

        RED.comms.subscribe(senseId, function(data) {
            try {
                var event;
                if (typeof data === 'string') {
                    event = JSON.parse(data);
                } else {
                    event = data;
                }

                if (event.eventType === eventType && event.eventName === eventName) {
                    node.send({
                        payload: event.message
                    });
                }
            } catch (e) {
                node.error('Error: '+e);
            }
        });
    }
    RED.nodes.registerType("sense event", SenseEvent);

    function SenseCommand(n) {
        RED.nodes.createNode(this,n);
        var senseId = n.senseid,
            commandType = n.commandtype,
            commandName = n.commandname,
            node = this;

        node.on('input', function(msg) {
            if (!msg.payload) {
                node.error('Missing property: msg.payload');
                return;
            }

            var message = {
                header: {
                    type: 'modules'
                },
                payload: {
                    commandType: commandType,
                    commandName: commandName,
                    commandData: msg.payload
                }
            };
            RED.comms.publish(senseId, message, true);
        });
    }
    RED.nodes.registerType("sense command", SenseCommand);
};
<commit_msg>unsubscribe event after node has been modified<commit_after>
module.exports = function(RED) {
    "use strict";

    function SenseEvent(n) {
        RED.nodes.createNode(this,n);
        var node = this,
            senseId = n.senseid,
            eventType = n.eventtype,
            eventName = n.eventname;

        var eventHandler = function(data) {
            try {
                var event;
                if (typeof data === 'string') {
                    event = JSON.parse(data);
                } else {
                    event = data;
                }

                if (event.eventType === eventType && event.eventName === eventName) {
                    node.send({
                        payload: event.message
                    });
                }
            } catch (e) {
                node.error('Error: '+e);
            }
        };

        RED.comms.subscribe(senseId, eventHandler);

        node.on('close', function() {
            RED.comms.unsubscribe(senseId, eventHandler);
        });
    }
    RED.nodes.registerType("sense event", SenseEvent);

    function SenseCommand(n) {
        RED.nodes.createNode(this,n);
        var senseId = n.senseid,
            commandType = n.commandtype,
            commandName = n.commandname,
            node = this;

        node.on('input', function(msg) {
            if (!msg.payload) {
                node.error('Missing property: msg.payload');
                return;
            }

            var message = {
                header: {
                    type: 'modules'
                },
                payload: {
                    commandType: commandType,
                    commandName: commandName,
                    commandData: msg.payload
                }
            };
            RED.comms.publish(senseId, message, true);
        });
    }
    RED.nodes.registerType("sense command", SenseCommand);
};
<|endoftext|>


<commit_before>class FormWizard {
    static create(params) {
        console.log('FormWizard.create', params);
        switch (params.model.database.getClassName()) {
            case 'MySqlDatabase'     : return new MySqlFormWizard(params);
            case 'PostgreSqlDatabase': return new PostgreSqlFormWizard(params);
            default: throw new Error(`unknown database class: ${params.model.database.getClassName()}`);
        }
    }

    constructor(params) {
        console.log('FormWizard.constructor', params);
        this.params        = params;
        this.model         = params.model;
        this.databaseName  = params.model.database.getName();
        this.tableName     = params.model.getName();
        this.tableColumns  = Object.keys(params.model.data.columns).map(name => params.model.data.columns[name]['@attributes']);
    }

    getDataSources() {
        return {
            default: {
                class     : 'SqlDataSource',
                name      : 'default',
                database  : this.databaseName,
                table     : this.tableName,
                limit     : this.params.className === 'TableForm' ? '100' : '',
                countQuery   : this.getCountQuery(),
                singleQuery  : this.getSingleQuery(),
                multipleQuery: this.getMultipleQuery()
            }
        };
    }

    getFieldClass(column) {
        if (column.type === 'date') return 'DatePickerField';
        if (column.type === 'boolean') return 'CheckBoxField';
        if (this.params.className === 'RowForm') {
            if (column.dbType === 'text') {
                return 'TextAreaField';
            }
            if (column.dbType === 'json') {
                return 'TextAreaField';
            }
        }
        return 'TextBoxField';
    }

    getField(column) {
        // console.log('FormWizard.getField', column);
        let field = {
            class: this.getFieldClass(column),
            name : column.name
        };
        if (column.caption) {
            field.caption = column.caption;
        }
        if (column.key === 'true') {
            if (column.auto === 'false') {
                field.notNull = 'true';
            }
        } else {
            if (column.nullable === 'false') {
                field.notNull = 'true';
                field.readOnly = 'false';
            }
        }
        if (column.auto === 'true') {
            field.readOnly = 'true';
        }
        return field;
    }

    getFields() {
        let fields = {};
        this.getColumns().forEach(column => {
            fields[column.name] = this.getField(column);
        });
        /*for (let i = 0; i < this.tableColumns.length; i++) {
            const column = this.tableColumns[i];
            fields[column.name] = this.getField(column);
        }*/
        return fields;
    }

    getColumns() {
        return this.tableColumns.filter(column => {
            if (this.params.className === 'TableForm') {
                if (column.dbType === 'text') return false;
                if (column.dbType === 'bytea') return false;
            }
            return true;
        });
    }

    getFormParams() {
        return {
            name       : this.params.formName,
            caption    : this.params.formCaption,
            class      : this.params.className,
            dataSources: this.getDataSources(),
            fields     : this.getFields()
        };
    }
}
<commit_msg>caption from name<commit_after>class FormWizard {
    static create(params) {
        console.log('FormWizard.create', params);
        switch (params.model.database.getClassName()) {
            case 'MySqlDatabase'     : return new MySqlFormWizard(params);
            case 'PostgreSqlDatabase': return new PostgreSqlFormWizard(params);
            default: throw new Error(`unknown database class: ${params.model.database.getClassName()}`);
        }
    }

    constructor(params) {
        console.log('FormWizard.constructor', params);
        this.params        = params;
        this.model         = params.model;
        this.databaseName  = params.model.database.getName();
        this.tableName     = params.model.getName();
        this.tableColumns  = Object.keys(params.model.data.columns).map(name => params.model.data.columns[name]['@attributes']);
    }

    getDataSources() {
        return {
            default: {
                class     : 'SqlDataSource',
                name      : 'default',
                database  : this.databaseName,
                table     : this.tableName,
                limit     : this.params.className === 'TableForm' ? '100' : '',
                countQuery   : this.getCountQuery(),
                singleQuery  : this.getSingleQuery(),
                multipleQuery: this.getMultipleQuery()
            }
        };
    }

    getFieldClass(column) {
        if (column.type === 'date') return 'DatePickerField';
        if (column.type === 'boolean') return 'CheckBoxField';
        if (this.params.className === 'RowForm') {
            if (column.dbType === 'text') {
                return 'TextAreaField';
            }
            if (column.dbType === 'json') {
                return 'TextAreaField';
            }
        }
        return 'TextBoxField';
    }

    getField(column) {
        // console.log('FormWizard.getField', column);
        let field = {
            class: this.getFieldClass(column),
            name : column.name,
            caption: column.caption || column.name
        };
        if (column.key === 'true') {
            if (column.auto === 'false') {
                field.notNull = 'true';
            }
        } else {
            if (column.nullable === 'false') {
                field.notNull = 'true';
                field.readOnly = 'false';
            }
        }
        if (column.auto === 'true') {
            field.readOnly = 'true';
        }
        return field;
    }

    getFields() {
        let fields = {};
        this.getColumns().forEach(column => {
            fields[column.name] = this.getField(column);
        });
        /*for (let i = 0; i < this.tableColumns.length; i++) {
            const column = this.tableColumns[i];
            fields[column.name] = this.getField(column);
        }*/
        return fields;
    }

    getColumns() {
        return this.tableColumns.filter(column => {
            if (this.params.className === 'TableForm') {
                if (column.dbType === 'text') return false;
                if (column.dbType === 'bytea') return false;
            }
            return true;
        });
    }

    getFormParams() {
        return {
            name       : this.params.formName,
            caption    : this.params.formCaption,
            class      : this.params.className,
            dataSources: this.getDataSources(),
            fields     : this.getFields()
        };
    }
}
<|endoftext|>


<commit_before>'use strict';

require('./map.less');

var _ = require('lodash');
var L = require('leaflet');
var MQ = require('mq-map');
var React = require('react');

var Route = require('common/route');

class Map extends React.Component {
  componentDidMount() {
    this.initMap();
    this.initLayers();
    this.initRouting();
    this.updateWaypoints();
  }

  componentDidUpdate() {
    this.updateWaypoints();
  }

  render() {
    return (

    );
  }

  initMap() {
    this.map = new L.Map(React.findDOMNode(this));
    this.map.setView(this.props.center, this.props.zoom);

    this.map.on('moveend', () => {
      this.props.onChangeCenter(this.map.getCenter());
    });
    this.map.on('zoomend', () => {
      this.props.onChangeZoom(this.map.getZoom());
    });
    this.map.on('click', (e) => {
      this.props.onClick(e.latlng);
    });
  }

  initLayers() {
    this.map.attributionControl.addAttribution('data © OpenStreetMap contributors');

    var thunderforestOutdoorsLayer = new L.TileLayer('http://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png', {
      maxZoom: 18,
      attribution: 'tiles © Thunderforest ' +
        '(CC-BY-SA 2.0)'
    });

    var thunderforestLandscapeLayer = new L.TileLayer('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png', {
      maxZoom: 18,
      attribution: 'tiles © Thunderforest ' +
        '(CC-BY-SA 2.0)'
    });

    var openCycleMapLayer = new L.TileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: 'tiles © OpenStreetMap contributors'
    });

    var openStreetMapLayer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: 'tiles © OpenStreetMap contributors'
    });

    var waymarkedTrailsLayer = new L.TileLayer('http://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png', {
      maxZoom: 19,
      opacity: 0.5,
      attribution: 'overlay © Waymarked Trails ' +
        '(CC-BY-SA 3.0 DE)'
    });

    var layersControl = new L.Control.Layers({
      'Thunderforest Outdoors': thunderforestOutdoorsLayer,
      'Thunderforest Landscape': thunderforestLandscapeLayer,
      'OpenCycleMap': openCycleMapLayer,
      'OpenStreetMap': openStreetMapLayer,
    }, {
      'Waymarked Trails': waymarkedTrailsLayer,
    });

    this.map.addLayer(thunderforestOutdoorsLayer);
    this.map.addLayer(waymarkedTrailsLayer);
    this.map.addControl(layersControl);
  }

  initRouting() {
    this.routing = MQ.routing.directions();
    this.routing.on('success', (data) => {
      var route = data.route;

      if (!route.sessionId) {
        return;
      }

      Route.getStats(route.sessionId).then((data) => {
        route.elevationProfile = data.elevationProfile;
        route.stats = data.stats;

        this.props.onRoutingStop(route);
      });
    });
    this.routing.on('error', (e) => {
      console.error(e);
      this.props.onRoutingStop();
    });

    this.routingLayer = MQ.routing.routeLayer({
      directions: this.routing,
      fitBounds: true,
    });
    this.routingLayer.getAttribution = function() {
      return 'routing &copy MapQuest';
    };
    this.map.addLayer(this.routingLayer);
  }

  updateWaypoints() {
    var newWaypoints = this.props.waypoints.waypoints.filter(x => x.latLng).map(x => _.pick(x , 'latLng')); // filter empty waypoints

    // check if waypoints have been updated
    if (_.isEqual(this.waypoints, newWaypoints)) {
      return;
    }

    // clear previous route
    this.routingLayer.setRouteData();
    this.waypoints = newWaypoints;

    // check if there are at least two waypoints
    if (newWaypoints.length < 2) {
      return;
    }

    var routingWaypoints = _.cloneDeep(newWaypoints);
    for (var i = 1; i < routingWaypoints.length - 1; i++) {
      routingWaypoints[i].type = 'v';
    }

    // run!
    this.routing.route({
      locations: routingWaypoints,
      options: {
        unit: 'k',
        routeType: 'pedestrian',
        reverseGeocoding: false,
      }
    });

    this.props.onRoutingStart();
  }
}

module.exports = Map;
<commit_msg>switch back to default Landscape layer<commit_after>'use strict';

require('./map.less');

var _ = require('lodash');
var L = require('leaflet');
var MQ = require('mq-map');
var React = require('react');

var Route = require('common/route');

class Map extends React.Component {
  componentDidMount() {
    this.initMap();
    this.initLayers();
    this.initRouting();
    this.updateWaypoints();
  }

  componentDidUpdate() {
    this.updateWaypoints();
  }

  render() {
    return (

    );
  }

  initMap() {
    this.map = new L.Map(React.findDOMNode(this));
    this.map.setView(this.props.center, this.props.zoom);

    this.map.on('moveend', () => {
      this.props.onChangeCenter(this.map.getCenter());
    });
    this.map.on('zoomend', () => {
      this.props.onChangeZoom(this.map.getZoom());
    });
    this.map.on('click', (e) => {
      this.props.onClick(e.latlng);
    });
  }

  initLayers() {
    this.map.attributionControl.addAttribution('data © OpenStreetMap contributors');

    var thunderforestLandscapeLayer = new L.TileLayer('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png', {
      maxZoom: 18,
      attribution: 'tiles © Thunderforest ' +
        '(CC-BY-SA 2.0)'
    });

    var thunderforestOutdoorsLayer = new L.TileLayer('http://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png', {
      maxZoom: 18,
      attribution: 'tiles © Thunderforest ' +
        '(CC-BY-SA 2.0)'
    });

    var openCycleMapLayer = new L.TileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: 'tiles © OpenStreetMap contributors'
    });

    var openStreetMapLayer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: 'tiles © OpenStreetMap contributors'
    });

    var waymarkedTrailsLayer = new L.TileLayer('http://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png', {
      maxZoom: 19,
      opacity: 0.5,
      attribution: 'overlay © Waymarked Trails ' +
        '(CC-BY-SA 3.0 DE)'
    });

    var layersControl = new L.Control.Layers({
      'Thunderforest Landscape': thunderforestLandscapeLayer,
      'Thunderforest Outdoors': thunderforestOutdoorsLayer,
      'OpenCycleMap': openCycleMapLayer,
      'OpenStreetMap': openStreetMapLayer,
    }, {
      'Waymarked Trails': waymarkedTrailsLayer,
    });

    this.map.addLayer(thunderforestLandscapeLayer);
    this.map.addLayer(waymarkedTrailsLayer);
    this.map.addControl(layersControl);
  }

  initRouting() {
    this.routing = MQ.routing.directions();
    this.routing.on('success', (data) => {
      var route = data.route;

      if (!route.sessionId) {
        return;
      }

      Route.getStats(route.sessionId).then((data) => {
        route.elevationProfile = data.elevationProfile;
        route.stats = data.stats;

        this.props.onRoutingStop(route);
      });
    });
    this.routing.on('error', (e) => {
      console.error(e);
      this.props.onRoutingStop();
    });

    this.routingLayer = MQ.routing.routeLayer({
      directions: this.routing,
      fitBounds: true,
    });
    this.routingLayer.getAttribution = function() {
      return 'routing &copy MapQuest';
    };
    this.map.addLayer(this.routingLayer);
  }

  updateWaypoints() {
    var newWaypoints = this.props.waypoints.waypoints.filter(x => x.latLng).map(x => _.pick(x , 'latLng')); // filter empty waypoints

    // check if waypoints have been updated
    if (_.isEqual(this.waypoints, newWaypoints)) {
      return;
    }

    // clear previous route
    this.routingLayer.setRouteData();
    this.waypoints = newWaypoints;

    // check if there are at least two waypoints
    if (newWaypoints.length < 2) {
      return;
    }

    var routingWaypoints = _.cloneDeep(newWaypoints);
    for (var i = 1; i < routingWaypoints.length - 1; i++) {
      routingWaypoints[i].type = 'v';
    }

    // run!
    this.routing.route({
      locations: routingWaypoints,
      options: {
        unit: 'k',
        routeType: 'pedestrian',
        reverseGeocoding: false,
      }
    });

    this.props.onRoutingStart();
  }
}

module.exports = Map;
<|endoftext|>


<commit_before>/**
 * Created by ksinger on 19.02.2016.
 */

import won from "../won-es6.js";
import Immutable from "immutable";
import { actionTypes, actionCreators } from "./actions.js";
import {
  fetchOwnedData,
  loadNeedFromRouteParamIfExists,
} from "../won-message-utils.js";
import {
  registerAccount,
  transferPrivateAccount,
  acceptTermsOfService,
  confirmRegistration,
  resendEmailVerification,
  sendAnonymousLinkEmail,
  login,
  logout,
  parseCredentials,
  generatePrivateId,
  checkLoginStatus,
} from "../won-utils.js";
import { setDisclaimerAccepted } from "../won-localstorage.js";
import { stateGoCurrent } from "./cstm-router-actions.js";
import { checkAccessToCurrentRoute } from "../configRouting.js";

import { getIn } from "../utils.js";
import { getOwnedConnectionUris } from "../selectors/connection-selectors.js";
import { loadLatestMessagesOfConnection } from "./connections-actions.js";

/**
 * Makes sure user is either logged in
 * or creates a private-ID account as fallback.
 */
export async function ensureLoggedIn(dispatch, getState) {
  const state = getState();
  if (state.getIn(["account", "loggedIn"])) {
    return;
  }

  const privateId = generatePrivateId();
  try {
    await accountRegister({ privateId })(dispatch, getState);
  } catch (err) {
    console.error(
      `Creating temporary account (${privateId}) has failed due to `,
      err
    );
    dispatch(actionCreators.account__registerFailed({ privateId }));
  }
}

let _loginInProcessFor;
/**
 *
 * @param credentials either {email, password} or {privateId}
 * @param redirectToFeed def. false, whether or not to redirect to the feed after signing in (needs `redirects` to be true)
 * @returns {Function}
 */
export function accountLogin(credentials, redirectToFeed = false) {
  return (dispatch, getState) => {
    const state = getState();

    const { email } = parseCredentials(credentials);

    const isLoggedIn = getIn(state, ["account", "loggedIn"]);
    const processingLoginForEmail =
      getIn(state, ["process", "processingLoginForEmail"]) ||
      _loginInProcessFor;

    if (processingLoginForEmail) {
      console.debug(
        "Already logging in as ",
        processingLoginForEmail,
        ". Canceling redundant attempt."
      );
      return;
    }

    if (isLoggedIn && !state.getIn(["process", "processingInitialLoad"])) {
      const loggedInEmail = state.getIn(["account", "email"]);

      if (credentials.email === loggedInEmail) {
        console.debug(
          "Already loggedIn with (" +
            credentials.email +
            "). Aborting login attempt."
        );
        return;
      }
    }

    return Promise.resolve()
      .then(() => {
        _loginInProcessFor = email;
        return dispatch({
          type: actionTypes.account.loginStarted,
          payload: { email },
        });
      })
      .then(() => {
        if (isLoggedIn) {
          return logout();
        }
      })
      .then(() => login(credentials))
      .then(data =>
        dispatch({
          type: actionTypes.account.store,
          payload: Immutable.fromJS(data),
        })
      )
      .then(() => dispatch({ type: actionTypes.upgradeHttpSession }))
      .then(() => fetchOwnedData(dispatch))
      .then(() => loadNeedFromRouteParamIfExists(dispatch, getState))
      .then(() => dispatch({ type: actionTypes.account.loginFinished }))
      .catch(error =>
        error.response.json().then(loginError => {
          return Promise.resolve()
            .then(() => {
              if (isLoggedIn) {
                return dispatch({ type: actionTypes.account.reset });
              }
            })
            .then(() => {
              if (credentials.privateId) {
                loginError = won.PRIVATEID_NOT_FOUND_ERROR;
              }

              return dispatch(
                actionCreators.account__loginFailed({
                  loginError: Immutable.fromJS(loginError),
                  error,
                  credentials,
                })
              );
            });
        })
      )
      .then(() => {
        if (redirectToFeed) {
          return dispatch(
            actionCreators.router__stateGoResetParams("connections")
          );
        }
        return Promise.resolve();
      })
      .then(() => checkAccessToCurrentRoute(dispatch, getState))
      .then(() => {
        _loginInProcessFor = undefined;
      });
  };
}

let _logoutInProcess;

/**
 * Processes logout
 * @returns {Function}
 */
export function accountLogout() {
  return (dispatch, getState) => {
    const state = getState();

    if (state.getIn(["process", "processingLogout"]) || _logoutInProcess) {
      console.debug("Logout in process. Aborting redundant attempt.");
      return;
    }
    _logoutInProcess = true;

    return Promise.resolve()
      .then(() => dispatch({ type: actionTypes.account.logoutStarted }))
      .then(() => logout())
      .catch(error => {
        //TODO: PRINT ERROR MESSAGE AND CHANGE STATE ACCORDINGLY
        console.error("Error while trying to log out: ", error);
      })
      .then(() => {
        // for the case that we've been logged in to an anonymous account, we need to remove the privateId here.
        if (getIn(state, ["router", "currentParams", "privateId"])) {
          return stateGoCurrent({ privateId: null })(dispatch, getState);
        }
      })
      .then(() => dispatch({ type: actionTypes.downgradeHttpSession }))
      .then(() => dispatch({ type: actionTypes.account.reset }))
      .then(() => won.clearStore())
      .then(() => loadNeedFromRouteParamIfExists(dispatch, getState))
      .then(() => {
        _logoutInProcess = false;
      })
      .then(() => dispatch({ type: actionTypes.account.logoutFinished }))
      .then(() => checkAccessToCurrentRoute(dispatch, getState));
  };
}

/**
 * @param credentials either {email, password} or {privateId}
 * @returns {Function}
 */
export function accountRegister(credentials) {
  return (dispatch, getState) =>
    registerAccount(credentials)
      .then(() => accountLogin(credentials, true)(dispatch, getState))
      .catch(error => {
        //TODO: PRINT MORE SPECIFIC ERROR MESSAGE, already registered/password to short etc.
        const registerError =
          "Registration failed (E-Mail might already be used)";
        console.error(registerError, error);
        dispatch(
          actionCreators.account__registerFailed({ registerError, error })
        );
      });
}

/**
 * @param credentials {email, password, privateId}
 * @returns {Function}
 */
export function accountTransfer(credentials) {
  //FIXME: accountTransfer only works if we have the full privateId which we might not have anymore after the refactoring
  return (dispatch, getState) =>
    transferPrivateAccount(credentials)
      .then(() => {
        credentials.privateId = undefined;
        return accountLogin(credentials, true)(dispatch, getState);
      })
      .catch(error => {
        //TODO: PRINT MORE SPECIFIC ERROR MESSAGE, already registered/password to short etc.
        const registerError = "Account Transfer failed";
        console.error(registerError, error);
        dispatch(
          actionCreators.account__registerFailed({ registerError, error })
        );
      });
}

export function accountAcceptDisclaimer() {
  return dispatch => {
    setDisclaimerAccepted();
    dispatch({ type: actionTypes.account.acceptDisclaimerSuccess });
  };
}

export function accountAcceptTermsOfService() {
  return dispatch => {
    dispatch({ type: actionTypes.account.acceptTermsOfServiceStarted });
    acceptTermsOfService()
      .then(() => {
        dispatch({ type: actionTypes.account.acceptTermsOfServiceSuccess });
      })
      .catch(() => {
        dispatch({ type: actionTypes.account.acceptTermsOfServiceFailed });
      });
  };
}

export function accountVerifyEmailAddress(verificationToken) {
  return dispatch => {
    dispatch({ type: actionTypes.account.verifyEmailAddressStarted });
    confirmRegistration(verificationToken)
      .then(() => {
        dispatch({ type: actionTypes.account.verifyEmailAddressSuccess });
      })
      .catch(error =>
        dispatch({
          type: actionTypes.account.verifyEmailAddressFailed,
          payload: {
            emailVerificationError: Immutable.fromJS(error.jsonResponse),
          },
        })
      );
  };
}

export function accountResendVerificationEmail(email) {
  return dispatch => {
    dispatch({ type: actionTypes.account.resendVerificationEmailStarted });
    resendEmailVerification(email)
      .then(() => {
        dispatch({ type: actionTypes.account.resendVerificationEmailSuccess });
      })
      .catch(error =>
        dispatch({
          type: actionTypes.account.resendVerificationEmailFailed,
          payload: {
            emailVerificationError: Immutable.fromJS(error.jsonResponse),
          },
        })
      );
  };
}

export function accountSendAnonymousLinkEmail(email, privateId) {
  return dispatch => {
    dispatch({ type: actionTypes.account.sendAnonymousLinkEmailStarted });
    sendAnonymousLinkEmail(email, privateId)
      .then(() => {
        dispatch({ type: actionTypes.account.sendAnonymousLinkEmailSuccess });
      })
      .catch(error =>
        dispatch({
          type: actionTypes.account.sendAnonymousLinkEmailFailed,
          payload: {
            anonymousEmailError: Immutable.fromJS(error.jsonResponse),
          },
        })
      );
  };
}

export function reconnect() {
  return async (dispatch, getState) => {
    dispatch({ type: actionTypes.reconnect.start });
    try {
      await checkLoginStatus();
      dispatch({ type: actionTypes.reconnect.success });

      const state = getState();

      /*
       * -- loading latest messages for all connections (we might have missed some during the dc) --
       */
      const connectionUris = getOwnedConnectionUris(state);
      await Promise.all(
        connectionUris.map(async connectionUri => {
          await loadLatestMessagesOfConnection({
            connectionUri,
            numberOfEvents: 10, //TODO magic number :|
            state,
            dispatch,
            actionTypesToDispatch: {
              start: actionTypes.reconnect.startingToLoadConnectionData,
              success: actionTypes.reconnect.receivedConnectionData,
              failure: actionTypes.reconnect.connectionFailedToLoad,
            },
          });
        })
      );
    } catch (e) {
      if (e.message == "Unauthorized") {
        //FIXME: this seems weird and unintentional to me, the actionTypes.account.reset closes the main menu (see view-reducer.js) and the dispatch after opens it again, is this wanted that way?
        dispatch({ type: actionTypes.account.reset });
        dispatch({ type: actionTypes.view.showMainMenu });
      } else {
        dispatch(actionCreators.lostConnection());
      }
      console.warn(e);
    }
  };
}
<commit_msg>Remove await -> function returns a promise anyway<commit_after>/**
 * Created by ksinger on 19.02.2016.
 */

import won from "../won-es6.js";
import Immutable from "immutable";
import { actionTypes, actionCreators } from "./actions.js";
import {
  fetchOwnedData,
  loadNeedFromRouteParamIfExists,
} from "../won-message-utils.js";
import {
  registerAccount,
  transferPrivateAccount,
  acceptTermsOfService,
  confirmRegistration,
  resendEmailVerification,
  sendAnonymousLinkEmail,
  login,
  logout,
  parseCredentials,
  generatePrivateId,
  checkLoginStatus,
} from "../won-utils.js";
import { setDisclaimerAccepted } from "../won-localstorage.js";
import { stateGoCurrent } from "./cstm-router-actions.js";
import { checkAccessToCurrentRoute } from "../configRouting.js";

import { getIn } from "../utils.js";
import { getOwnedConnectionUris } from "../selectors/connection-selectors.js";
import { loadLatestMessagesOfConnection } from "./connections-actions.js";

/**
 * Makes sure user is either logged in
 * or creates a private-ID account as fallback.
 */
export async function ensureLoggedIn(dispatch, getState) {
  const state = getState();
  if (state.getIn(["account", "loggedIn"])) {
    return;
  }

  const privateId = generatePrivateId();
  try {
    await accountRegister({ privateId })(dispatch, getState);
  } catch (err) {
    console.error(
      `Creating temporary account (${privateId}) has failed due to `,
      err
    );
    dispatch(actionCreators.account__registerFailed({ privateId }));
  }
}

let _loginInProcessFor;
/**
 *
 * @param credentials either {email, password} or {privateId}
 * @param redirectToFeed def. false, whether or not to redirect to the feed after signing in (needs `redirects` to be true)
 * @returns {Function}
 */
export function accountLogin(credentials, redirectToFeed = false) {
  return (dispatch, getState) => {
    const state = getState();

    const { email } = parseCredentials(credentials);

    const isLoggedIn = getIn(state, ["account", "loggedIn"]);
    const processingLoginForEmail =
      getIn(state, ["process", "processingLoginForEmail"]) ||
      _loginInProcessFor;

    if (processingLoginForEmail) {
      console.debug(
        "Already logging in as ",
        processingLoginForEmail,
        ". Canceling redundant attempt."
      );
      return;
    }

    if (isLoggedIn && !state.getIn(["process", "processingInitialLoad"])) {
      const loggedInEmail = state.getIn(["account", "email"]);

      if (credentials.email === loggedInEmail) {
        console.debug(
          "Already loggedIn with (" +
            credentials.email +
            "). Aborting login attempt."
        );
        return;
      }
    }

    return Promise.resolve()
      .then(() => {
        _loginInProcessFor = email;
        return dispatch({
          type: actionTypes.account.loginStarted,
          payload: { email },
        });
      })
      .then(() => {
        if (isLoggedIn) {
          return logout();
        }
      })
      .then(() => login(credentials))
      .then(data =>
        dispatch({
          type: actionTypes.account.store,
          payload: Immutable.fromJS(data),
        })
      )
      .then(() => dispatch({ type: actionTypes.upgradeHttpSession }))
      .then(() => fetchOwnedData(dispatch))
      .then(() => loadNeedFromRouteParamIfExists(dispatch, getState))
      .then(() => dispatch({ type: actionTypes.account.loginFinished }))
      .catch(error =>
        error.response.json().then(loginError => {
          return Promise.resolve()
            .then(() => {
              if (isLoggedIn) {
                return dispatch({ type: actionTypes.account.reset });
              }
            })
            .then(() => {
              if (credentials.privateId) {
                loginError = won.PRIVATEID_NOT_FOUND_ERROR;
              }

              return dispatch(
                actionCreators.account__loginFailed({
                  loginError: Immutable.fromJS(loginError),
                  error,
                  credentials,
                })
              );
            });
        })
      )
      .then(() => {
        if (redirectToFeed) {
          return dispatch(
            actionCreators.router__stateGoResetParams("connections")
          );
        }
        return Promise.resolve();
      })
      .then(() => checkAccessToCurrentRoute(dispatch, getState))
      .then(() => {
        _loginInProcessFor = undefined;
      });
  };
}

let _logoutInProcess;

/**
 * Processes logout
 * @returns {Function}
 */
export function accountLogout() {
  return (dispatch, getState) => {
    const state = getState();

    if (state.getIn(["process", "processingLogout"]) || _logoutInProcess) {
      console.debug("Logout in process. Aborting redundant attempt.");
      return;
    }
    _logoutInProcess = true;

    return Promise.resolve()
      .then(() => dispatch({ type: actionTypes.account.logoutStarted }))
      .then(() => logout())
      .catch(error => {
        //TODO: PRINT ERROR MESSAGE AND CHANGE STATE ACCORDINGLY
        console.error("Error while trying to log out: ", error);
      })
      .then(() => {
        // for the case that we've been logged in to an anonymous account, we need to remove the privateId here.
        if (getIn(state, ["router", "currentParams", "privateId"])) {
          return stateGoCurrent({ privateId: null })(dispatch, getState);
        }
      })
      .then(() => dispatch({ type: actionTypes.downgradeHttpSession }))
      .then(() => dispatch({ type: actionTypes.account.reset }))
      .then(() => won.clearStore())
      .then(() => loadNeedFromRouteParamIfExists(dispatch, getState))
      .then(() => {
        _logoutInProcess = false;
      })
      .then(() => dispatch({ type: actionTypes.account.logoutFinished }))
      .then(() => checkAccessToCurrentRoute(dispatch, getState));
  };
}

/**
 * @param credentials either {email, password} or {privateId}
 * @returns {Function}
 */
export function accountRegister(credentials) {
  return (dispatch, getState) =>
    registerAccount(credentials)
      .then(() => accountLogin(credentials, true)(dispatch, getState))
      .catch(error => {
        //TODO: PRINT MORE SPECIFIC ERROR MESSAGE, already registered/password to short etc.
        const registerError =
          "Registration failed (E-Mail might already be used)";
        console.error(registerError, error);
        dispatch(
          actionCreators.account__registerFailed({ registerError, error })
        );
      });
}

/**
 * @param credentials {email, password, privateId}
 * @returns {Function}
 */
export function accountTransfer(credentials) {
  //FIXME: accountTransfer only works if we have the full privateId which we might not have anymore after the refactoring
  return (dispatch, getState) =>
    transferPrivateAccount(credentials)
      .then(() => {
        credentials.privateId = undefined;
        return accountLogin(credentials, true)(dispatch, getState);
      })
      .catch(error => {
        //TODO: PRINT MORE SPECIFIC ERROR MESSAGE, already registered/password to short etc.
        const registerError = "Account Transfer failed";
        console.error(registerError, error);
        dispatch(
          actionCreators.account__registerFailed({ registerError, error })
        );
      });
}

export function accountAcceptDisclaimer() {
  return dispatch => {
    setDisclaimerAccepted();
    dispatch({ type: actionTypes.account.acceptDisclaimerSuccess });
  };
}

export function accountAcceptTermsOfService() {
  return dispatch => {
    dispatch({ type: actionTypes.account.acceptTermsOfServiceStarted });
    acceptTermsOfService()
      .then(() => {
        dispatch({ type: actionTypes.account.acceptTermsOfServiceSuccess });
      })
      .catch(() => {
        dispatch({ type: actionTypes.account.acceptTermsOfServiceFailed });
      });
  };
}

export function accountVerifyEmailAddress(verificationToken) {
  return dispatch => {
    dispatch({ type: actionTypes.account.verifyEmailAddressStarted });
    confirmRegistration(verificationToken)
      .then(() => {
        dispatch({ type: actionTypes.account.verifyEmailAddressSuccess });
      })
      .catch(error =>
        dispatch({
          type: actionTypes.account.verifyEmailAddressFailed,
          payload: {
            emailVerificationError: Immutable.fromJS(error.jsonResponse),
          },
        })
      );
  };
}

export function accountResendVerificationEmail(email) {
  return dispatch => {
    dispatch({ type: actionTypes.account.resendVerificationEmailStarted });
    resendEmailVerification(email)
      .then(() => {
        dispatch({ type: actionTypes.account.resendVerificationEmailSuccess });
      })
      .catch(error =>
        dispatch({
          type: actionTypes.account.resendVerificationEmailFailed,
          payload: {
            emailVerificationError: Immutable.fromJS(error.jsonResponse),
          },
        })
      );
  };
}

export function accountSendAnonymousLinkEmail(email, privateId) {
  return dispatch => {
    dispatch({ type: actionTypes.account.sendAnonymousLinkEmailStarted });
    sendAnonymousLinkEmail(email, privateId)
      .then(() => {
        dispatch({ type: actionTypes.account.sendAnonymousLinkEmailSuccess });
      })
      .catch(error =>
        dispatch({
          type: actionTypes.account.sendAnonymousLinkEmailFailed,
          payload: {
            anonymousEmailError: Immutable.fromJS(error.jsonResponse),
          },
        })
      );
  };
}

export function reconnect() {
  return async (dispatch, getState) => {
    dispatch({ type: actionTypes.reconnect.start });
    try {
      await checkLoginStatus();
      dispatch({ type: actionTypes.reconnect.success });

      const state = getState();

      /*
       * -- loading latest messages for all connections (we might have missed some during the dc) --
       */
      const connectionUris = getOwnedConnectionUris(state);
      await Promise.all(
        connectionUris.map(connectionUri =>
          loadLatestMessagesOfConnection({
            connectionUri,
            numberOfEvents: 10, //TODO magic number :|
            state,
            dispatch,
            actionTypesToDispatch: {
              start: actionTypes.reconnect.startingToLoadConnectionData,
              success: actionTypes.reconnect.receivedConnectionData,
              failure: actionTypes.reconnect.connectionFailedToLoad,
            },
          })
        )
      );
    } catch (e) {
      if (e.message == "Unauthorized") {
        //FIXME: this seems weird and unintentional to me, the actionTypes.account.reset closes the main menu (see view-reducer.js) and the dispatch after opens it again, is this wanted that way?
        dispatch({ type: actionTypes.account.reset });
        dispatch({ type: actionTypes.view.showMainMenu });
      } else {
        dispatch(actionCreators.lostConnection());
      }
      console.warn(e);
    }
  };
}
<|endoftext|>


<commit_before>/**
 * CUSTOMIZED STANDBY WIDGET FOR JQUERY
 *
 * Created by
 * ----------
 * Name 	- SANDEEP KANANGATT
 * Email 	- sandeepsuvit@gmail.com
 * Website 	- www.dotedlabs.com
 * Github	- https://github.com/sandeepsuvit/LoaderWidget-for-jQuery
 *
 * This widget is a customized Standby widget with a loader image. This also
 * helps the user to display text content dynamically when the user wants to
 * show the loader for any particular event.
 *
 * This standby loader can be invoked in the following ways.
 *
 * Note: The loader has been default set to work on the "body" of the html
 * pages.
 *
 * ----------------------------------------------------------------------------
 * How to use this widget:
 * ----------------------------------------------------------------------------
 * 1. standbyLoader.show(); -> Displays the loader with the default text "Please
 * wait...".
 *
 * 2. standbyLoader.show({text: "my message"}); -> Displays the loader with the
 * parameterized string.
 *
 * 3. standbyLoader.hide(); -> Hides the loader and defaults the loader text to
 * "Please wait...".
 *
 */

// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;

// Path for the image to show on the loader
var standbyLoader_image_path = "ajaxLoader.gif";

// Default text to show on the loader
var standbyLoader_default_text = "Please wait...";

// Globally set variables
var standbyLoader = new Object();

// Utility functions for string operations
var StringUtilsFunctions = {
	// Check if the string is empty
	isEmpty : function(param) {
		if (param === undefined) {
			return true;
		} else {
			if (param == null)
				return true;
			if (param.length < 0)
				return true;
			if (param.length == 0)
				return true;
			return false;
		}
	},

	// Capitalizes the first letter of a string
	capitaliseFirstLetter : function(param) {
		return param.charAt(0).toUpperCase() + param.slice(1);
	}
};

$(document).ready(
		function() {

			// Appending the loader widget
			standbyLoader = {

				// Loader text reference
				loaderText : standbyLoader_default_text,

				// Loader image reference
				loaderImage : standbyLoader_image_path,

				// Show the overlay
				show : function(param) {
					// If the overlay is already present, remove it before
					// showing the overlay again.
					if ($("#standbyLoader-overlay").size() > 0) {
						// Remove the overlay
						this.hide();
					}

					// Check if the text parameter is passed
					if (param === undefined) {
						// Set all to its default values
						this.revertToDefaultText();

						// Show the widget
						$(this.getContentToDisplay()).appendTo('body')
								.slideDown();
					} else {
						// Check for loader text
						if (!StringUtilsFunctions.isEmpty(param.text)) {
							this.loaderText = param.text;
							this.changeText(this.loaderText);
						} else {
							this.revertToDefaultText();
						}

						// Show the widget
						$(this.getContentToDisplay()).appendTo('body')
								.slideDown();
					}

				},

				// Remove the overlay
				hide : function() {
					this.revertToDefaultText();

					// Hide the image
					$("#standbyLoader-loading").fadeOut();

					// Hide the text
					$("#standbyLoader-loading-text").fadeOut();

					// Check If the overlay is already presents
					if ($("#standbyLoader-overlay").size() != 0) {
						$("#standbyLoader-overlay").slideUp(function() {
							$("#standbyLoader-overlay").remove();
						});
					}
				},

				// Change the default message to custom message
				changeText : function(param) {
					if (!StringUtilsFunctions.isEmpty(param)) {
						this.loaderText = StringUtilsFunctions
								.capitaliseFirstLetter(param);
					} else {
						this.revertToDefaultText();
					}
				},

				// Revert back the custom message to the default message
				revertToDefaultText : function() {
					this.loaderText = standbyLoader_default_text;
				},

				// Content to display on the loader
				getContentToDisplay : function() {
					// Show the image
					$("#standbyLoader-loading").fadeIn();

					// Show the text
					$("#standbyLoader-loading-text").fadeIn();

					return '
'
							+ ""
							+ "
"
							+ this.loaderText + "
" + '
';
				}
			};

		});
<commit_msg>Update standbyLoader.js<commit_after>/**
 * CUSTOMIZED STANDBY WIDGET FOR JQUERY
 *
 * Created by
 * ----------
 * Name 	- SANDEEP KANANGATT
 * Email 	- sandeepsuvit@gmail.com
 * Website 	- www.dotedlabs.com
 * Github	- https://github.com/sandeepsuvit/LoaderWidget-for-jQuery
 *
 * This widget is a customized Standby widget with a loader image. This also
 * helps the user to display text content dynamically when the user wants to
 * show the loader for any particular event.
 *
 * This standby loader can be invoked in the following ways.
 *
 * Note: The loader has been default set to work on the "body" of the html
 * pages.
 *
 * ----------------------------------------------------------------------------
 * How to use this widget:
 * ----------------------------------------------------------------------------
 * 1. standbyLoader.show(); -> Displays the loader with the default text "Please
 * wait...".
 *
 * 2. standbyLoader.show({text: "my message"}); -> Displays the loader with the
 * parameterized string.
 *
 * 3. standbyLoader.hide(); -> Hides the loader and defaults the loader text to
 * "Please wait...".
 *
 */

// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;

// Path for the image to show on the loader
var standbyLoader_image_path = "ajaxLoader.gif";

// Default text to show on the loader
var standbyLoader_default_text = "Please wait...";

// Globally set variables
var standbyLoader = new Object();

// Utility functions for string operations
var StringUtilsFunctions = {
	// Check if the string is empty
	isEmpty : function(param) {
		if (param === undefined) {
			return true;
		} else {
			if (param == null)
				return true;
			if (param.length < 0)
				return true;
			if (param.length == 0)
				return true;
			return false;
		}
	},

	// Capitalizes the first letter of a string
	capitaliseFirstLetter : function(param) {
		return param.charAt(0).toUpperCase() + param.slice(1);
	}
};

$(document).ready(
		function() {

			// Appending the loader widget
			standbyLoader = {

				// Loader text reference
				loaderText : standbyLoader_default_text,

				// Loader image reference
				loaderImage : standbyLoader_image_path,

				// Show the overlay
				show : function(param) {
					// If the overlay is already present, remove it before
					// showing the overlay again.
					if ($("#standbyLoader-overlay").size() > 0) {
						// Remove the overlay
						this.hide();
					}

					//Disable the scrollbars from the body tag
					$('body').addClass("standbyLoader-hide-scrolls-from-body");

					// Check if the text parameter is passed
					if (param === undefined) {
						// Set all to its default values
						this.revertToDefaultText();

						// Show the widget
						$(this.getContentToDisplay()).appendTo('body')
								.slideDown();
					} else {
						// Check for loader text
						if (!StringUtilsFunctions.isEmpty(param.text)) {
							this.loaderText = param.text;
							this.changeText(this.loaderText);
						} else {
							this.revertToDefaultText();
						}

						// Show the widget
						$(this.getContentToDisplay()).appendTo('body')
								.slideDown();
					}

				},

				// Remove the overlay
				hide : function() {
					this.revertToDefaultText();

					// Hide the image
					$("#standbyLoader-loading").fadeOut();

					// Hide the text
					$("#standbyLoader-loading-text").fadeOut();

					// Check If the overlay is already presents
					if ($("#standbyLoader-overlay").size() != 0) {
						$("#standbyLoader-overlay").slideUp(function() {
							$("#standbyLoader-overlay").remove();
						});
					}

					//Re-Enable the scrollbars from the body tag
					$('body').removeClass("standbyLoader-hide-scrolls-from-body");
				},

				// Change the default message to custom message
				changeText : function(param) {
					if (!StringUtilsFunctions.isEmpty(param)) {
						this.loaderText = StringUtilsFunctions
								.capitaliseFirstLetter(param);
					} else {
						this.revertToDefaultText();
					}
				},

				// Revert back the custom message to the default message
				revertToDefaultText : function() {
					this.loaderText = standbyLoader_default_text;
				},

				// Content to display on the loader
				getContentToDisplay : function() {
					// Show the image
					$("#standbyLoader-loading").fadeIn();

					// Show the text
					$("#standbyLoader-loading-text").fadeIn();

					return '
'
							+ ""
							+ "
"
							+ this.loaderText + "
" + '
';
				}
			};

		});
<|endoftext|>


<commit_before>var gl;
var points_batch;
var rb;
var pointsize, pointweight;
var interactor;

//////////////////////////////////////////////////////////////////////////////

function make_points_batch(x, y, width, height)
{
    var points_model = Facet.model({
        x: x,
        y: y,
        type: "points"
    });
    var pt = Shade.vec(points_model.x, points_model.y);

    rb = Facet.render_buffer({ width: width, height: height, type: gl.FLOAT });
    var rb_batch = rb.make_screen_batch(function(texel_accessor) {
        return Shade.vec(1,1,1,2)
            .sub(Shade.Utils.lerp([Shade.color("white"),
                                   Shade.color("#d29152"),
                                   Shade.color("sienna"),
                                   Shade.color("black")])(texel_accessor().at(0).add(1).log()));
    });

    var batch = Facet.bake(points_model, {
        position: interactor.camera(pt),
        mode: Facet.DrawingMode.additive,
        color: Shade.pointCoord().sub(Shade.vec(0.5, 0.5))
            .norm().pow(2).neg()
            .mul(20)
            .exp()
            .mul(pointweight)
            .mul(interactor.zoom.pow(0.33))
            .mul(Shade.color("white")),
        point_size: interactor.zoom.pow(0.5).mul(pointsize)
    });

    return {
        draw: function() {
            rb.with_bound_buffer(function() {
                gl.clear(gl.COLOR_BUFFER_BIT);
                if (batch)
                    batch.draw();
            });
            rb_batch.draw();
        }
    };
}

function init_gui()
{
    Facet.UI.parameter_slider({ element: "#pointsize",   parameter: pointsize,   min: 0, max: 10 });
    Facet.UI.parameter_slider({ element: "#pointweight", parameter: pointweight, min: 0, max: 1  });

    $("#set_center").click(function() {
        var x = Number($("#realvalue").val()),
            y = Number($("#imagvalue").val());
        if (!isNaN(x) && !isNaN(y)) {
            interactor.transition_to(vec.make([x, y]), interactor.zoom.get(), 3);
            // interactor.center.set();
            // Facet.Scene.invalidate();
        }
    });
    $(window).resize(function(eventObject) {
        if (!rb)
            return;
        var w = window.innerWidth;
        var h = window.innerHeight;
        interactor.resize(w, h);
        gl.resize(w, h);
        rb.resize(w, h);
        Facet.Scene.invalidate();
    });
    $("#greeting").click(function() {
        $("#greeting").fadeOut(500);
    });
    window.setTimeout(function() {
        $("#greeting").fadeOut(500);
    }, 15000);
}

$().ready(function() {
    pointsize = Shade.parameter("float", 2.5);
    pointweight = Shade.parameter("float", 0.5);
    init_gui();

    var canvas = document.getElementById("webgl");
    var width = window.innerWidth, height = window.innerHeight;
    canvas.width = width;
    canvas.height = height;

    interactor = Facet.UI.center_zoom_interactor({
        width: width, height: height, zoom: 2/3
    });

    $("#overview").click(function() { interactor.transition_to(vec.make([0, 0]), 0.8333, 3); });
    $("#fractal1").click(function() { interactor.transition_to(vec.make([-0.4501, -0.5069]), 15, 3); });
    $("#fractal2").click(function() { interactor.transition_to(vec.make([0.6601, -0.1711]), 9, 3); });
    $("#fractal3").click(function() { interactor.transition_to(vec.make([-1.5333, 0.2376]), 6, 3); });
    $("#fractal4").click(function() { interactor.transition_to(vec.make([-0.9129, 1.298]), 4, 3); });
    $("#squares").click(function() { interactor.transition_to(vec.make([0, 0.73]), 7, 3); });
    $("#eye1").click(function() { interactor.transition_to(vec.make([-1, 0]), 7, 3); });
    $("#eye2").click(function() { interactor.transition_to(vec.make([0, -1]), 20, 3); });
    $("#eye3").click(function() { interactor.transition_to(vec.make([-0.5, 0.8666]), 15, 3); });
    $("#eye4").click(function() { interactor.transition_to(vec.make([0.7071, -0.7071]), 15, 3); });

    interactor.center.watch(function(c) {
        $("#current-real").text(Math.round(c[0] * 10000) / 10000);
        $("#current-imag").text(Math.round(c[1] * 10000) / 10000);
        $("#plus-sign").css("display", c[1] >= 0 ? "" : "none");
    });

    // FIXME That hardcoded 240 should be computed based on screen size or something
    gl = Facet.init(canvas, {
        clearDepth: 1.0,
        clearColor: [0,0,0,1],
        interactor: interactor
    });

    Facet.Net.binary(["data/roots_real.raw", "data/roots_imag.raw"], function (obj) {
        var x = Facet.attribute_buffer({ vertex_array: new Float32Array(obj["data/roots_real.raw"]), item_size: 1});
        var y = Facet.attribute_buffer({ vertex_array: new Float32Array(obj["data/roots_imag.raw"]), item_size: 1});
        points_batch = make_points_batch(x, y, width, height);

        $("#loading").fadeOut(500);
        Facet.Scene.add(points_batch);
        Facet.Scene.invalidate();
    });
    Facet.Scene.invalidate();
});
<commit_msg>force low-res backing store for this demo, since it does not make it look nicer<commit_after>var gl;
var points_batch;
var rb;
var pointsize, pointweight;
var interactor;

//////////////////////////////////////////////////////////////////////////////

function make_points_batch(x, y, width, height)
{
    var points_model = Facet.model({
        x: x,
        y: y,
        type: "points"
    });
    var pt = Shade.vec(points_model.x, points_model.y);

    rb = Facet.render_buffer({ width: width, height: height, type: gl.FLOAT });
    var rb_batch = rb.make_screen_batch(function(texel_accessor) {
        return Shade.vec(1,1,1,2)
            .sub(Shade.Utils.lerp([Shade.color("white"),
                                   Shade.color("#d29152"),
                                   Shade.color("sienna"),
                                   Shade.color("black")])(texel_accessor().at(0).add(1).log()));
    });

    var batch = Facet.bake(points_model, {
        position: interactor.camera(pt),
        mode: Facet.DrawingMode.additive,
        color: Shade.pointCoord().sub(Shade.vec(0.5, 0.5))
            .norm().pow(2).neg()
            .mul(20)
            .exp()
            .mul(pointweight)
            .mul(interactor.zoom.pow(0.33))
            .mul(Shade.color("white")),
        point_size: interactor.zoom.pow(0.5).mul(pointsize)
    });

    return {
        draw: function() {
            rb.with_bound_buffer(function() {
                gl.clear(gl.COLOR_BUFFER_BIT);
                if (batch)
                    batch.draw();
            });
            rb_batch.draw();
        }
    };
}

function init_gui()
{
    Facet.UI.parameter_slider({ element: "#pointsize",   parameter: pointsize,   min: 0, max: 10 });
    Facet.UI.parameter_slider({ element: "#pointweight", parameter: pointweight, min: 0, max: 1  });

    $("#set_center").click(function() {
        var x = Number($("#realvalue").val()),
            y = Number($("#imagvalue").val());
        if (!isNaN(x) && !isNaN(y)) {
            interactor.transition_to(vec.make([x, y]), interactor.zoom.get(), 3);
            // interactor.center.set();
            // Facet.Scene.invalidate();
        }
    });
    $(window).resize(function(eventObject) {
        if (!rb)
            return;
        var w = window.innerWidth;
        var h = window.innerHeight;
        interactor.resize(w, h);
        gl.resize(w, h);
        rb.resize(w, h);
        Facet.Scene.invalidate();
    });
    $("#greeting").click(function() {
        $("#greeting").fadeOut(500);
    });
    window.setTimeout(function() {
        $("#greeting").fadeOut(500);
    }, 15000);
}

$().ready(function() {
    pointsize = Shade.parameter("float", 2.5);
    pointweight = Shade.parameter("float", 0.5);
    init_gui();

    var canvas = document.getElementById("webgl");
    var width = window.innerWidth, height = window.innerHeight;
    canvas.width = width;
    canvas.height = height;

    interactor = Facet.UI.center_zoom_interactor({
        width: width, height: height, zoom: 2/3
    });

    $("#overview").click(function() { interactor.transition_to(vec.make([0, 0]), 0.8333, 3); });
    $("#fractal1").click(function() { interactor.transition_to(vec.make([-0.4501, -0.5069]), 15, 3); });
    $("#fractal2").click(function() { interactor.transition_to(vec.make([0.6601, -0.1711]), 9, 3); });
    $("#fractal3").click(function() { interactor.transition_to(vec.make([-1.5333, 0.2376]), 6, 3); });
    $("#fractal4").click(function() { interactor.transition_to(vec.make([-0.9129, 1.298]), 4, 3); });
    $("#squares").click(function() { interactor.transition_to(vec.make([0, 0.73]), 7, 3); });
    $("#eye1").click(function() { interactor.transition_to(vec.make([-1, 0]), 7, 3); });
    $("#eye2").click(function() { interactor.transition_to(vec.make([0, -1]), 20, 3); });
    $("#eye3").click(function() { interactor.transition_to(vec.make([-0.5, 0.8666]), 15, 3); });
    $("#eye4").click(function() { interactor.transition_to(vec.make([0.7071, -0.7071]), 15, 3); });

    interactor.center.watch(function(c) {
        $("#current-real").text(Math.round(c[0] * 10000) / 10000);
        $("#current-imag").text(Math.round(c[1] * 10000) / 10000);
        $("#plus-sign").css("display", c[1] >= 0 ? "" : "none");
    });

    // FIXME That hardcoded 240 should be computed based on screen size or something
    gl = Facet.init(canvas, {
        clearDepth: 1.0,
        clearColor: [0,0,0,1],
        interactor: interactor,
        highDPS: false
    });

    Facet.Net.binary(["data/roots_real.raw", "data/roots_imag.raw"], function (obj) {
        var x = Facet.attribute_buffer({ vertex_array: new Float32Array(obj["data/roots_real.raw"]), item_size: 1});
        var y = Facet.attribute_buffer({ vertex_array: new Float32Array(obj["data/roots_imag.raw"]), item_size: 1});
        points_batch = make_points_batch(x, y, width, height);

        $("#loading").fadeOut(500);
        Facet.Scene.add(points_batch);
        Facet.Scene.invalidate();
    });
    Facet.Scene.invalidate();
});
<|endoftext|>


<commit_before>export const agenda1 = [
  { time: "0800-1000", text: "Registration and light breakfast", muted: true },
  { time: "0900", text: "Early Session", sessions: [null,"d1d1e044-8627-5cce-c793-45f0a9442a1e",null] },
  { time: "1000", text: "Welcome + Keynote", sessions: "3c1e5e0a-9774-7ff8-043b-c421a71e8b31" },
  { time: "1050", text: "Break", muted: true },
  { time: "1110", sessions: [
    "11896515-320d-537b-b8ce-a414a3def110",
    "7ad6d40b-4e5a-8d57-81dd-800f849938ba",
    "fd37d9f1-b376-5aaf-5f74-c7c7286157a4"
  ]},
  { time: "1150", text: "Break", muted: true },
  { time: "1200", sessions: [
    "0576eb1d-a8ff-858f-6493-8739d373ba9a",
    "2ba4bb5f-25a7-f109-ea86-5d87b10e4e6e",
    "1dd1f609-06db-b640-b836-a33ed3dc4f61"
  ] },
  { time: "1240", text: "Lunch", muted: true },
  { time: "1340", text: "Ignites", shortSessions: [
    "70c5d0d3-e3e1-710d-bc8a-09d5a6eabf69",
    "6746a1e4-9fe8-dbd9-4e83-b355c5be2e17",
    "dab65d9b-29c7-1c07-e2f3-73923c0376e3",
    "38ea24bb-0eb0-5803-1ea2-728e52fcc57c",
    "18cc673c-32de-ce18-bb5d-19c17689a390",
    "1739b0ca-5b60-1e9d-4105-3f167874c336",
    "30461c08-353f-962e-c4a0-c345921a18ad"
  ] },
  { time: "1420", text: "Break", muted: true },
  { time: "1430", sessions: [
    "94c6bc98-3287-0ba5-a729-308279d415fc",
    "980eb393-c851-2207-162a-3d6c95c3e7c6",
    "099994f7-45fb-5d67-f7a9-98f9a6aa2834"
  ] },
  { time: "1500", text: "Break", muted: true },
  { time: "1510", sessions: [{ text: "OSS in Israel", sessions: [
    "32689a4d-f440-d6e4-59f4-3de6c6828031",
    "0d2d0c86-1fa1-7464-49a1-e841db4cc959",
    "5ffe1f3f-137a-405a-c420-08816400cc8e",
    "22001f52-fe1d-3164-733f-5dcb786095a0"
  ]},
    "ae7d9c23-b30b-9b69-13c7-3ab4d4e58354",
    null
  ] },
  { time: "1550", text: "Break", muted: true },
  { time: "1610", sessions: [
    "51619b54-21a4-a5e5-d393-08deac134132",
    "6ac729a2-1369-6613-6e27-84e1bd3bce7b",
    "84641a40-095a-b9a6-a9fc-9e0a539d2fdf"
  ] },
  { time: "1650", text: "Break", muted: true },
  { time: "1700", sessions: [
    "358ab26f-46c6-41b5-c178-3db392ae62b9",
    "ff3e6bb4-88f1-b6a2-db82-81f75a2e50e9",
    "3c0885c7-3857-b68b-d283-24ed216a316f"
  ] },
  { time: "1740", text: "Beer Break", muted: true },
  { time: "1800", sessions: "77789faf-ba34-d71e-de3a-a0a802387c6a" },
  { time: "1900", text: "Goodbye", muted: true },
];

export const agenda2 = [
  { time: "0800-1000", text: "Registration and light breakfast", muted: true },
  { time: "0900", text: "Early Session", sessions: [null,"75691af5-ce4e-2d67-ae2a-603c2f12e397",null] },
  { time: "1000", text: "Welcome + Keynote", sessions: "b89383ea-ba2a-7e2d-425d-e0c2f2fe27d0" },
  { time: "1050", text: "Break", muted: true },
  { time: "1110", sessions: [
    "21bd03f7-c711-2e1d-6a95-f6998beec2b9",
    "c1380280-bad1-d498-fd3f-c664995c5c99",
    "e273ba54-ca58-0cf9-940f-cceb86bd98b7"
  ]},
  { time: "1150", text: "Break", muted: true },
  { time: "1200", sessions: [
    "ba5a920e-6596-bc62-d5b7-16d141e9e8bc",
    "9d15b17d-d73a-9c77-d196-4307126b9be9",
    "a0188f4a-825e-d83b-52c3-d7d5e1859955"
  ] },
  { time: "1240", text: "Lunch", muted: true },
  { time: "1340", text: "Ignites", shortSessions: [
    "0e493b6e-220a-2208-c7da-40e81aab982d",
    "0717532c-78ac-f849-efad-6a2e882244e9",
    "516fc501-a1ad-0097-cbae-5f069d524c03",
    "b193b43d-8d12-775c-a01c-c0f1805e9794",
    "87fceb26-f76e-c412-15e3-8eed45c31b9f",
    "ba169253-ab97-86ca-74e2-beceb1bc523c",
    "48d882bc-1088-a1e3-45d5-9014072e58c6"
  ] },
  { time: "1420", text: "Break", muted: true },
  { time: "1430", sessions: [
    "e9f4d8fb-75af-eb68-103b-2ccb24d49a7b",
    "b114c756-2011-dcd5-7c0d-714edacdb764",
    "1fe6e617-1f01-4c70-357c-d0be588d1775"
  ] },
  { time: "1500", text: "Break", muted: true },
  { time: "1510", sessions: [{ text: "OSS in Israel", sessions: [
    "e27df61b-a45d-bb0f-ce90-c127df244eee",
    "f9afbecf-8eff-0aa1-9108-ff233d259af7",
    "57a4c603-bbe9-da61-08b5-f3703bd250dd",
    "397b1985-f55c-988c-8a7f-309b7198b729"
  ]},
    "ac719d2a-ea06-7a00-6153-68d99e78cc1e",
    null
  ] },
  { time: "1550", text: "Break", muted: true },
  { time: "1610", sessions: [
    "d86450a0-fd2b-4701-25c8-0716849a1de5",
    "cbcc3966-0df2-f37a-0590-857f5401791a",
    "b4cf69e6-4cbc-1663-332b-528bc400deea"
  ] },
  { time: "1650", text: "Break", muted: true },
  { time: "1700", sessions: [
    "5675c068-d551-b49e-95c1-66d03c63b577",
    "ce03940b-ad4b-369e-8163-26531341017f",
    "d6cc3aba-4930-12a3-7ebb-88fa565d574c"
  ] },
  { time: "1740", text: "Beer Break", muted: true },
  { time: "1800", text: "Hall of Shame" },
  { time: "1900", text: "Goodbye", muted: true },
];<commit_msg>swap sessions<commit_after>export const agenda1 = [
  { time: "0800-1000", text: "Registration and light breakfast", muted: true },
  { time: "0900", text: "Early Session", sessions: [null,"d1d1e044-8627-5cce-c793-45f0a9442a1e",null] },
  { time: "1000", text: "Welcome + Keynote", sessions: "3c1e5e0a-9774-7ff8-043b-c421a71e8b31" },
  { time: "1050", text: "Break", muted: true },
  { time: "1110", sessions: [
    "11896515-320d-537b-b8ce-a414a3def110",
    "7ad6d40b-4e5a-8d57-81dd-800f849938ba",
    "fd37d9f1-b376-5aaf-5f74-c7c7286157a4"
  ]},
  { time: "1150", text: "Break", muted: true },
  { time: "1200", sessions: [
    "0576eb1d-a8ff-858f-6493-8739d373ba9a",
    "2ba4bb5f-25a7-f109-ea86-5d87b10e4e6e",
    "1dd1f609-06db-b640-b836-a33ed3dc4f61"
  ] },
  { time: "1240", text: "Lunch", muted: true },
  { time: "1340", text: "Ignites", shortSessions: [
    "70c5d0d3-e3e1-710d-bc8a-09d5a6eabf69",
    "6746a1e4-9fe8-dbd9-4e83-b355c5be2e17",
    "dab65d9b-29c7-1c07-e2f3-73923c0376e3",
    "38ea24bb-0eb0-5803-1ea2-728e52fcc57c",
    "18cc673c-32de-ce18-bb5d-19c17689a390",
    "1739b0ca-5b60-1e9d-4105-3f167874c336",
    "30461c08-353f-962e-c4a0-c345921a18ad"
  ] },
  { time: "1420", text: "Break", muted: true },
  { time: "1430", sessions: [
    "94c6bc98-3287-0ba5-a729-308279d415fc",
    "980eb393-c851-2207-162a-3d6c95c3e7c6",
    "099994f7-45fb-5d67-f7a9-98f9a6aa2834"
  ] },
  { time: "1500", text: "Break", muted: true },
  { time: "1510", sessions: [{ text: "OSS in Israel", sessions: [
    "32689a4d-f440-d6e4-59f4-3de6c6828031",
    "0d2d0c86-1fa1-7464-49a1-e841db4cc959",
    "5ffe1f3f-137a-405a-c420-08816400cc8e",
    "22001f52-fe1d-3164-733f-5dcb786095a0"
  ]},
    "ae7d9c23-b30b-9b69-13c7-3ab4d4e58354",
    null
  ] },
  { time: "1550", text: "Break", muted: true },
  { time: "1610", sessions: [
    "ba5a920e-6596-bc62-d5b7-16d141e9e8bc",
    "6ac729a2-1369-6613-6e27-84e1bd3bce7b",
    "84641a40-095a-b9a6-a9fc-9e0a539d2fdf"
  ] },
  { time: "1650", text: "Break", muted: true },
  { time: "1700", sessions: [
    "358ab26f-46c6-41b5-c178-3db392ae62b9",
    "ff3e6bb4-88f1-b6a2-db82-81f75a2e50e9",
    "3c0885c7-3857-b68b-d283-24ed216a316f"
  ] },
  { time: "1740", text: "Beer Break", muted: true },
  { time: "1800", sessions: "77789faf-ba34-d71e-de3a-a0a802387c6a" },
  { time: "1900", text: "Goodbye", muted: true },
];

export const agenda2 = [
  { time: "0800-1000", text: "Registration and light breakfast", muted: true },
  { time: "0900", text: "Early Session", sessions: [null,"75691af5-ce4e-2d67-ae2a-603c2f12e397",null] },
  { time: "1000", text: "Welcome + Keynote", sessions: "b89383ea-ba2a-7e2d-425d-e0c2f2fe27d0" },
  { time: "1050", text: "Break", muted: true },
  { time: "1110", sessions: [
    "21bd03f7-c711-2e1d-6a95-f6998beec2b9",
    "c1380280-bad1-d498-fd3f-c664995c5c99",
    "e273ba54-ca58-0cf9-940f-cceb86bd98b7"
  ]},
  { time: "1150", text: "Break", muted: true },
  { time: "1200", sessions: [
    "51619b54-21a4-a5e5-d393-08deac134132",
    "9d15b17d-d73a-9c77-d196-4307126b9be9",
    "a0188f4a-825e-d83b-52c3-d7d5e1859955"
  ] },
  { time: "1240", text: "Lunch", muted: true },
  { time: "1340", text: "Ignites", shortSessions: [
    "0e493b6e-220a-2208-c7da-40e81aab982d",
    "0717532c-78ac-f849-efad-6a2e882244e9",
    "516fc501-a1ad-0097-cbae-5f069d524c03",
    "b193b43d-8d12-775c-a01c-c0f1805e9794",
    "87fceb26-f76e-c412-15e3-8eed45c31b9f",
    "ba169253-ab97-86ca-74e2-beceb1bc523c",
    "48d882bc-1088-a1e3-45d5-9014072e58c6"
  ] },
  { time: "1420", text: "Break", muted: true },
  { time: "1430", sessions: [
    "e9f4d8fb-75af-eb68-103b-2ccb24d49a7b",
    "b114c756-2011-dcd5-7c0d-714edacdb764",
    "1fe6e617-1f01-4c70-357c-d0be588d1775"
  ] },
  { time: "1500", text: "Break", muted: true },
  { time: "1510", sessions: [{ text: "OSS in Israel", sessions: [
    "e27df61b-a45d-bb0f-ce90-c127df244eee",
    "f9afbecf-8eff-0aa1-9108-ff233d259af7",
    "57a4c603-bbe9-da61-08b5-f3703bd250dd",
    "397b1985-f55c-988c-8a7f-309b7198b729"
  ]},
    "ac719d2a-ea06-7a00-6153-68d99e78cc1e",
    null
  ] },
  { time: "1550", text: "Break", muted: true },
  { time: "1610", sessions: [
    "d86450a0-fd2b-4701-25c8-0716849a1de5",
    "cbcc3966-0df2-f37a-0590-857f5401791a",
    "b4cf69e6-4cbc-1663-332b-528bc400deea"
  ] },
  { time: "1650", text: "Break", muted: true },
  { time: "1700", sessions: [
    "5675c068-d551-b49e-95c1-66d03c63b577",
    "ce03940b-ad4b-369e-8163-26531341017f",
    "d6cc3aba-4930-12a3-7ebb-88fa565d574c"
  ] },
  { time: "1740", text: "Beer Break", muted: true },
  { time: "1800", text: "Hall of Shame" },
  { time: "1900", text: "Goodbye", muted: true },
];<|endoftext|>


<commit_before>var express = require('express');

var routes = function(Book){
    var bookRouter = express.Router();

    bookRouter.route('/')
       .post(function(req,res){
        var book = new Book(req.body);

        book.save();
        res.status(201).send(book);
    })
    .get(function(req,res){
        console.log('aqui');
        var query = req.query;
        Book.find(query,function(err,books){
            if(err)
                res.status(500).send(err);
            else
                res.json(books);
        });
});

bookRouter.route('/books/:id')
    .get(function(req,res){
        Book.findById(req.params.id,function(err,books){
            if(err)
                res.status(500).send(err);
            else
                res.json(books);
        });
    });
    return bookRouter;
};

module.exports = routes;<commit_msg>change controllers<commit_after>var express = require('express');

var routes = function(Book){
    var bookRouter = express.Router();

    bookRouter.route('/')
       .post(function(req,res){
        var book = new Book(req.body);

        book.save();
        res.status(201).send(book);
    })
    .get(function(req,res){
        var query = req.query;
        Book.find(query,function(err,books){
            if(err)
                res.status(500).send(err);
            else
                res.json(books);
        });
});

bookRouter.route('/books/:id')
    .get(function(req,res){
        Book.findById(req.params.id,function(err,books){
            if(err)
                res.status(500).send(err);
            else
                res.json(books);
        });
    })
.put(function(req,res){
        Book.findById(req.params.id, function(err,books){
            if(err)
                res.status(500).send(err);
            else
                books.title     = req.body.title;
                books.author    = req.body.author;
                books.genre     = req.body.genre;
                books.read      = req.body.read;
                books.save();
                res.json(books);
        });
});
    return bookRouter;
};

module.exports = routes;<|endoftext|>


<commit_before>import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import vue from 'rollup-plugin-vue'
import uglify from 'rollup-plugin-uglify'
import sass from 'rollup-plugin-sass';
import autoprefixer from 'autoprefixer'
import postcss from 'postcss'
import csso from 'postcss-csso';
import { minify } from 'uglify-es'
import pkg from './package.json';

const isProduction = process.env.NODE_ENV === `production`
const isDevelopment = process.env.NODE_ENV === `development`

function createConfig(entry, module, name) {

  const output = module ? module +'/index' : 'index'
  const banner = `/**
  * @module vue-mdc-adapter{{module}} {{version}}
  * @exports {{name}}
  * @copyright (c) 2017-present, Sebastien Tasson
  * @license https://opensource.org/licenses/MIT
  * @implements {{dependencies}}
  * @requires {{peerDependencies}}
  * @see https://github.com/stasson/vue-mdc-adapter
  */`
  .replace('{{module}}', module || '')
  .replace('{{name}}', name)
  .replace('{{version}}', pkg.version)
  .replace('{{dependencies}}', JSON.stringify(pkg.dependencies))
  .replace('{{peerDependencies}}', JSON.stringify(pkg.peerDependencies))

  const libPath = (isDevelopment
        ? `dist/${output}.js`
        : `dist/${output}.min.js`)

  const babelConfig = {
    'compact': false,
    'babelrc': false,
    'presets': [
      [
        // env preset https://github.com/babel/babel-preset-env
        'env',
        // let rollup take care of modules
        { 'modules': false }
      ]
    ],
    'plugins': [
      // let rollup bundle helpers once
      // see https://github.com/rollup/rollup-plugin-babel#helpers
      'external-helpers'
    ]
  }

  const sassConfig = {
    include: [ '**/*.css', '**/*.scss' ],
    options: {includePaths: ['node_modules']},
    processor: css => postcss((isDevelopment
                        ? [autoprefixer()]
                        : [autoprefixer(), csso()]))
                      .process(css)
                      .then(result => result.css)
  }

  if (isProduction) {
    sassConfig.output = `dist/${output}.min.css`
  } else {
    sassConfig.insert = true
  }

  const config = {
    input: entry,
    output: {
      file: libPath,
      format: 'umd',
      name: name
    },
    external: ['vue'],
    plugins: [
      vue ({ autoStyles: false, styleToImports: true }),
      resolve({ jsnext: true, main: true, browser: true }),
      sass(sassConfig),
      babel(babelConfig),
      commonjs(),
    ],
    banner,
    sourcemap: isDevelopment ? 'inline' : true,
    onwarn
  }

  if (isProduction) {
    config.plugins.push(uglify({
      output: {
        comments: function(node, comment) {
            var text = comment.value;
            var type = comment.type;
            if (type == "comment2") {
                // multiline comment
                return /@preserve|@license|@cc_on/i.test(text);
            }
        }
      }
    }, minify))
  }
  return config
}

export default [
  createConfig('components/entry.js', undefined, 'VueMDCAdapter'),
  createConfig('components/button/entry.js', 'button', 'VueMDCButton'),
  createConfig('components/card/entry.js', 'card', 'VueMDCCard'),
  createConfig('components/checkbox/entry.js', 'checkbox', 'VueMDCCheckbox'),
  createConfig('components/dialog/entry.js', 'dialog', 'VueMDCDialog'),
  createConfig('components/drawer/entry.js', 'drawer', 'VueMDCDrawer'),
  createConfig('components/fab/entry.js', 'fab', 'VueMDCFab'),
  createConfig('components/grid-list/entry.js', 'grid-list', 'VueMDCGridList'),
  createConfig('components/icon-toggle/entry.js', 'icon-toggle', 'VueMDCIconToggle'),
  createConfig('components/icon/entry.js', 'icon', 'VueMDCIcon'),
  createConfig('components/layout-app/entry.js', 'layout-app', 'VueMDCLayoutApp'),
  createConfig('components/layout-grid/entry.js', 'layout-grid', 'VueMDCLayoutGrid'),
  createConfig('components/linear-progress/entry.js', 'linear-progress', 'VueMDCLinearProgress'),
  createConfig('components/list/entry.js', 'list', 'VueMDCList'),
  createConfig('components/menu/entry.js', 'menu', 'VueMDCMenu'),
  createConfig('components/radio/entry.js', 'radio', 'VueMDCRadio'),
  createConfig('components/select/entry.js', 'select', 'VueMDCSelect'),
  createConfig('components/slider/entry.js', 'slider', 'VueMDCSlider'),
  createConfig('components/snackbar/entry.js', 'snackbar', 'VueMDCSnackbar'),
  createConfig('components/switch/entry.js', 'switch', 'VueMDCSwitch'),
  createConfig('components/tabs/entry.js', 'tabs', 'VueMDCTabs'),
  createConfig('components/textfield/entry.js', 'texfield', 'VueMDCTextfield'),
  createConfig('components/toolbar/entry.js', 'toolbar', 'VueMDCToolbar'),
  createConfig('components/typography/entry.js', 'typography', 'VueMDCTypography'),
]

function onwarn (warning) {

  // skip certain warnings
  if (warning.code == 'NON_EXISTENT_EXPORT') {
    if (warning.name == 'MDCIconToggleAdapter') return;
  }

  // console.warn everything else
  console.log(warning);
  console.warn(warning.message);
}
<commit_msg>fix(rollup): allow transform-object-rest-spread<commit_after>import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import vue from 'rollup-plugin-vue'
import uglify from 'rollup-plugin-uglify'
import sass from 'rollup-plugin-sass';
import autoprefixer from 'autoprefixer'
import postcss from 'postcss'
import csso from 'postcss-csso';
import { minify } from 'uglify-es'
import pkg from './package.json';

const isProduction = process.env.NODE_ENV === `production`
const isDevelopment = process.env.NODE_ENV === `development`

function createConfig(entry, module, name) {

  const output = module ? module +'/index' : 'index'
  const banner = `/**
  * @module vue-mdc-adapter{{module}} {{version}}
  * @exports {{name}}
  * @copyright (c) 2017-present, Sebastien Tasson
  * @license https://opensource.org/licenses/MIT
  * @implements {{dependencies}}
  * @requires {{peerDependencies}}
  * @see https://github.com/stasson/vue-mdc-adapter
  */`
  .replace('{{module}}', module || '')
  .replace('{{name}}', name)
  .replace('{{version}}', pkg.version)
  .replace('{{dependencies}}', JSON.stringify(pkg.dependencies))
  .replace('{{peerDependencies}}', JSON.stringify(pkg.peerDependencies))

  const libPath = (isDevelopment
        ? `dist/${output}.js`
        : `dist/${output}.min.js`)

  const babelConfig = {
    'compact': false,
    'babelrc': false,
    'presets': [
      [
        // env preset https://github.com/babel/babel-preset-env
        'env',
        // let rollup take care of modules
        { 'modules': false }
      ]
    ],
    'plugins': [
      "transform-object-rest-spread",
      // let rollup bundle helpers once
      // see https://github.com/rollup/rollup-plugin-babel#helpers
      'external-helpers'
    ]
  }

  const sassConfig = {
    include: [ '**/*.css', '**/*.scss' ],
    options: {includePaths: ['node_modules']},
    processor: css => postcss((isDevelopment
                        ? [autoprefixer()]
                        : [autoprefixer(), csso()]))
                      .process(css)
                      .then(result => result.css)
  }

  if (isProduction) {
    sassConfig.output = `dist/${output}.min.css`
  } else {
    sassConfig.insert = true
  }

  const config = {
    input: entry,
    output: {
      file: libPath,
      format: 'umd',
      name: name
    },
    external: ['vue'],
    plugins: [
      vue ({ autoStyles: false, styleToImports: true }),
      resolve({ jsnext: true, main: true, browser: true }),
      sass(sassConfig),
      babel(babelConfig),
      commonjs(),
    ],
    banner,
    sourcemap: isDevelopment ? 'inline' : true,
    onwarn
  }

  if (isProduction) {
    config.plugins.push(uglify({
      output: {
        comments: function(node, comment) {
            var text = comment.value;
            var type = comment.type;
            if (type == "comment2") {
                // multiline comment
                return /@preserve|@license|@cc_on/i.test(text);
            }
        }
      }
    }, minify))
  }
  return config
}

export default [
  createConfig('components/entry.js', undefined, 'VueMDCAdapter'),
  createConfig('components/button/entry.js', 'button', 'VueMDCButton'),
  createConfig('components/card/entry.js', 'card', 'VueMDCCard'),
  createConfig('components/checkbox/entry.js', 'checkbox', 'VueMDCCheckbox'),
  createConfig('components/dialog/entry.js', 'dialog', 'VueMDCDialog'),
  createConfig('components/drawer/entry.js', 'drawer', 'VueMDCDrawer'),
  createConfig('components/fab/entry.js', 'fab', 'VueMDCFab'),
  createConfig('components/grid-list/entry.js', 'grid-list', 'VueMDCGridList'),
  createConfig('components/icon-toggle/entry.js', 'icon-toggle', 'VueMDCIconToggle'),
  createConfig('components/icon/entry.js', 'icon', 'VueMDCIcon'),
  createConfig('components/layout-app/entry.js', 'layout-app', 'VueMDCLayoutApp'),
  createConfig('components/layout-grid/entry.js', 'layout-grid', 'VueMDCLayoutGrid'),
  createConfig('components/linear-progress/entry.js', 'linear-progress', 'VueMDCLinearProgress'),
  createConfig('components/list/entry.js', 'list', 'VueMDCList'),
  createConfig('components/menu/entry.js', 'menu', 'VueMDCMenu'),
  createConfig('components/radio/entry.js', 'radio', 'VueMDCRadio'),
  createConfig('components/select/entry.js', 'select', 'VueMDCSelect'),
  createConfig('components/slider/entry.js', 'slider', 'VueMDCSlider'),
  createConfig('components/snackbar/entry.js', 'snackbar', 'VueMDCSnackbar'),
  createConfig('components/switch/entry.js', 'switch', 'VueMDCSwitch'),
  createConfig('components/tabs/entry.js', 'tabs', 'VueMDCTabs'),
  createConfig('components/textfield/entry.js', 'texfield', 'VueMDCTextfield'),
  createConfig('components/toolbar/entry.js', 'toolbar', 'VueMDCToolbar'),
  createConfig('components/typography/entry.js', 'typography', 'VueMDCTypography'),
]

function onwarn (warning) {

  // skip certain warnings
  if (warning.code == 'NON_EXISTENT_EXPORT') {
    if (warning.name == 'MDCIconToggleAdapter') return;
  }

  // console.warn everything else
  console.log(warning);
  console.warn(warning.message);
}
<|endoftext|>


<commit_before>(function() {
  "use strict";

  var ns = "nkf.core";
  var self = $.namespace(ns);

  Controller.className = "Controller";

  function Controller() {
    addEventHandler();

    function addEventHandler() {
      window.onpopstate = function(event) {
        $(document).trigger("nkf.core.Controller", {
          type: nkf.def.events.type.make,
          name: "load",
          data: {
            pageName: Controller.getNormalizedObject(event.state.path).pageName,
            params: Controller.getNormalizedObject(event.state.path).params,
            init: true
          }
        });
      };

      $(document).bind("{ns}.{className}".format({
        ns: ns,
        className: Controller.className
      }), function(e, object) {
        if (object.type === nkf.def.events.type.make && object.name === "load") {
          if (!isInit) {
            init();
          }

          if (!object) {
            object = {};
          }

          if (!object.data) {
            object.data = {};
          }

          if (isInit) {
            object.data.pageName = object.data.pageName || Controller.getNormalizedObject(Controller.getCurrentPath()).pageName || "Home";
            object.data.params = object.data.clear ? object.data.params : $.extend({}, Controller.getNormalizedObject(Controller.getCurrentPath()).params, object.data.params);

            $(document).trigger("nkf.core.Controller", {
              type: nkf.def.events.type.is,
              name: "load",
              data: {
                init: object.data.init
              }
            });

            if (!object.data.appInit) {
              Controller.setCurrentPath(object.data);
            }

            if (object.data.init) {
              ++historyCounter;

              componentManager.load(object.data);
            }
          }
        }
      });
    }

    function init() {
      if (!nkf.impl) {
        throw "No implementation found";
      } else if (!nkf.impl.components) {
        throw "No component found";
      } else if (!nkf.impl.components.layout) {
        throw "No layout component found";
      } else if (!nkf.impl.components.page) {
        throw "No page component found";
      }

      isInit = true;
    }
  }

  Controller.getCurrentPath = function() {
    var normalBrowsers = window.location.href.replace(window.location.protocol + "//" + window.location.host, "").replace(/\/#\//, "").replace(/^\//, "");
    var ie = window.location.hash.replace(/\#?\/?/, "");

    if ($.browser.msie && $.browser.version < 10) {
      return ie || normalBrowsers;
    } else {
      return normalBrowsers;
    }
  };

  Controller.setCurrentPath = function(data) {
    var output = data.pageName || Controller.getNormalizedObject(Controller.getCurrentPath()).pageName;

    if (data.params && $Utils.getObjectSize(data.params)) {
      var preparedData = $Utils.prepareURLObject(data.params);

      if ($Utils.getObjectSize(preparedData)) {
        var serializedData = $Utils.getSerializeObject(preparedData);

        output += "/" + serializedData;
      }
    }

    previousLogin = $.cookie("isLogin");

    history.pushState({path: "/" + output}, "", "/" + output);
  };

  Controller.getNormalizedObject = function(url) {
    var output = {};

    var splited = (url || Controller.getCurrentPath()).replace(/^\//, "").split("/");
//    var splited = (url || Controller.getCurrentPath()).replace(/^\#?\.?\/?/, "").split("/");

    var pageName = splited[0];
    var parameters = splited[1];

    output.pageName = pageName;
    output.params = $Utils.getDeserializedObject(parameters);

    return output;
  };

  Controller.getHistoryCounter = function() {
    //HACK: Chrome fire popustate on the page load... don't know why
    return $.browser.chrome ? historyCounter - 1 : historyCounter;
  };

  $.extend(self, {
    Controller: Controller
  });

  var controller = new Controller();
  var componentManager = new self.components.ComponentManager.getInstance();
  var $Utils = nkf.core.Utils;

  var historyCounter = -1;
  var previousLogin = false;

  var isInit = false;
})();
<commit_msg>fixed HTML5 History<commit_after>(function() {
  "use strict";

  var ns = "nkf.core";
  var self = $.namespace(ns);

  Controller.className = "Controller";

  function Controller() {
    addEventHandler();

    function addEventHandler() {
      window.onpopstate = function(event) {
        $(document).trigger("nkf.core.Controller", {
          type: nkf.def.events.type.make,
          name: "load",
          data: {
            pageName: Controller.getNormalizedObject(event.state.path).pageName,
            params: Controller.getNormalizedObject(event.state.path).params,
            init: true,
            type: "popstate"
          }
        });
      };

      $(document).bind("{ns}.{className}".format({
        ns: ns,
        className: Controller.className
      }), function(e, object) {
        if (object.type === nkf.def.events.type.make && object.name === "load") {
          if (!isInit) {
            init();
          }

          if (!object) {
            object = {};
          }

          if (!object.data) {
            object.data = {};
          }

          if (isInit) {
            object.data.pageName = object.data.pageName || Controller.getNormalizedObject(Controller.getCurrentPath()).pageName || "Home";
            object.data.params = object.data.clear ? object.data.params : $.extend({}, Controller.getNormalizedObject(Controller.getCurrentPath()).params, object.data.params);

            $(document).trigger("nkf.core.Controller", {
              type: nkf.def.events.type.is,
              name: "load",
              data: {
                init: object.data.init
              }
            });

            if (!object.data.appInit && object.data.type !== "popstate") {
              Controller.setCurrentPath(object.data);
            }

            if (object.data.init) {
              ++historyCounter;

              componentManager.load(object.data);
            }
          }
        }
      });
    }

    function init() {
      if (!nkf.impl) {
        throw "No implementation found";
      } else if (!nkf.impl.components) {
        throw "No component found";
      } else if (!nkf.impl.components.layout) {
        throw "No layout component found";
      } else if (!nkf.impl.components.page) {
        throw "No page component found";
      }

      isInit = true;
    }
  }

  Controller.getCurrentPath = function() {
    var normalBrowsers = window.location.href.replace(window.location.protocol + "//" + window.location.host, "").replace(/\/#\//, "").replace(/^\//, "");
    var ie = window.location.hash.replace(/\#?\/?/, "");

    if ($.browser.msie && $.browser.version < 10) {
      return ie || normalBrowsers;
    } else {
      return normalBrowsers;
    }
  };

  Controller.setCurrentPath = function(data) {
    var output = data.pageName || Controller.getNormalizedObject(Controller.getCurrentPath()).pageName;

    if (data.params && $Utils.getObjectSize(data.params)) {
      var preparedData = $Utils.prepareURLObject(data.params);

      if ($Utils.getObjectSize(preparedData)) {
        var serializedData = $Utils.getSerializeObject(preparedData);

        output += "/" + serializedData;
      }
    }

    previousLogin = $.cookie("isLogin");

    history.pushState({path: "/" + output}, "", "/" + output);
  };

  Controller.getNormalizedObject = function(url) {
    var output = {};

    var splited = (url || Controller.getCurrentPath()).replace(/^\//, "").split("/");
//    var splited = (url || Controller.getCurrentPath()).replace(/^\#?\.?\/?/, "").split("/");

    var pageName = splited[0];
    var parameters = splited[1];

    output.pageName = pageName;
    output.params = $Utils.getDeserializedObject(parameters);

    return output;
  };

  Controller.getHistoryCounter = function() {
    //HACK: Chrome fire popustate on the page load... don't know why
    return $.browser.chrome ? historyCounter - 1 : historyCounter;
  };

  $.extend(self, {
    Controller: Controller
  });

  var controller = new Controller();
  var componentManager = new self.components.ComponentManager.getInstance();
  var $Utils = nkf.core.Utils;

  var historyCounter = -1;
  var previousLogin = false;

  var isInit = false;
})();
<|endoftext|>