<commit_before>import _ from 'lodash'
import bcrypt from 'bcrypt-as-promised'
import {HTTPError} from 'netiam-errors'
import moment from 'moment'
import Promise from 'bluebird'
import {
  OAUTH_INVALID_CREDENTIALS,
  OAUTH_INVALID_PASSWORD,
  OAUTH_PASSWORD_MISSING,
  OAUTH_USERNAME_MISSING
} from '../errors'

const TOKEN_TYPE_ACCESS = 'access_token'
const TOKEN_TYPE_REFRESH = 'refresh_token'

const ACCESS_TOKEN_TYPE_BEARER = 'bearer'

export default function({
  req,
  res,
  userModel,
  tokenModel,
  usernameField,
  passwordField,
  tokenField,
  accessTokenTTL,
  refreshTokenTTL
  }) {
  const {
    username,
    password,
    scope,
    state} = req.body

  if (!_.isString(username) || username.length === 0) {
    return Promise.reject(new HTTPError(OAUTH_USERNAME_MISSING))
  }

  if (!_.isString(password) || password.length === 0) {
    return Promise.reject(new HTTPError(OAUTH_PASSWORD_MISSING))
  }

  return userModel
    .findOne({where: {[usernameField]: username}})
    .then(user => {
      if (!user) {
        return Promise.reject(new HTTPError(OAUTH_INVALID_CREDENTIALS))
      }

      return bcrypt
        .compare(password, user[passwordField])
        .then(() => {
          const accessToken = tokenModel
            .create({
              type: TOKEN_TYPE_ACCESS,
              expires_at: moment().add(accessTokenTTL, 'hours').format(),
              ownerId: user.id
            })
          const refreshToken = tokenModel
            .create({
              type: TOKEN_TYPE_REFRESH,
              expires_at: moment().add(refreshTokenTTL, 'days').format(),
              ownerId: user.id
            })

          return Promise
            .all([accessToken, refreshToken])
            .then(tokens => {
              const [accessToken, refreshToken] = tokens
              res.body = {
                access_token: accessToken[tokenField],
                refresh_token: refreshToken[tokenField],
                token_type: ACCESS_TOKEN_TYPE_BEARER,
                expires_in: moment(accessToken.expires_at).diff(moment(), 'seconds'),
                user_id: user.id
              }
            })
        })
        .catch(bcrypt.MISMATCH_ERROR, () => Promise.reject(new HTTPError(OAUTH_INVALID_PASSWORD)))
        .catch(() => Promise.reject(new HTTPError(OAUTH_USERNAME_MISSING)))
    })
}
<commit_msg>fix: return correct error for `bcrypt.compare`<commit_after>import _ from 'lodash'
import bcrypt from 'bcrypt-as-promised'
import {HTTPError} from 'netiam-errors'
import moment from 'moment'
import Promise from 'bluebird'
import {
  OAUTH_INVALID_CREDENTIALS,
  OAUTH_INVALID_PASSWORD,
  OAUTH_PASSWORD_MISSING,
  OAUTH_USERNAME_MISSING
} from '../errors'

const TOKEN_TYPE_ACCESS = 'access_token'
const TOKEN_TYPE_REFRESH = 'refresh_token'

const ACCESS_TOKEN_TYPE_BEARER = 'bearer'

export default function({
  req,
  res,
  userModel,
  tokenModel,
  usernameField,
  passwordField,
  tokenField,
  accessTokenTTL,
  refreshTokenTTL
  }) {
  const {
    username,
    password,
    scope,
    state} = req.body

  if (!_.isString(username) || username.length === 0) {
    return Promise.reject(new HTTPError(OAUTH_USERNAME_MISSING))
  }

  if (!_.isString(password) || password.length === 0) {
    return Promise.reject(new HTTPError(OAUTH_PASSWORD_MISSING))
  }

  return userModel
    .findOne({where: {[usernameField]: username}})
    .then(user => {
      if (!user) {
        return Promise.reject(new HTTPError(OAUTH_INVALID_CREDENTIALS))
      }

      return bcrypt
        .compare(password, user[passwordField])
        .then(() => {
          const accessToken = tokenModel
            .create({
              type: TOKEN_TYPE_ACCESS,
              expires_at: moment().add(accessTokenTTL, 'hours').format(),
              ownerId: user.id
            })
          const refreshToken = tokenModel
            .create({
              type: TOKEN_TYPE_REFRESH,
              expires_at: moment().add(refreshTokenTTL, 'days').format(),
              ownerId: user.id
            })

          return Promise
            .all([accessToken, refreshToken])
            .then(tokens => {
              const [accessToken, refreshToken] = tokens
              res.body = {
                access_token: accessToken[tokenField],
                refresh_token: refreshToken[tokenField],
                token_type: ACCESS_TOKEN_TYPE_BEARER,
                expires_in: moment(accessToken.expires_at).diff(moment(), 'seconds'),
                user_id: user.id
              }
            })
        })
        .catch(bcrypt.MISMATCH_ERROR, () => Promise.reject(new HTTPError(OAUTH_INVALID_PASSWORD)))
        .catch(() => Promise.reject(new HTTPError(OAUTH_INVALID_CREDENTIALS)))
    })
}
<|endoftext|>


<commit_before>import React from "react";
import {connect} from "react-redux";
import _ from "lodash";
import ActionsUtils from "../../actions/ActionsUtils";
import "../../stylesheets/visualization.styl";
import GenericModalDialog from "./GenericModalDialog";
import Dialogs from "./Dialogs"
import CommentInput from "../CommentInput";
import HttpService from "../../http/HttpService";
import ProcessUtils from "../../common/ProcessUtils";
import ProcessDialogWarnings from "./ProcessDialogWarnings";

class DeployProcessDialog extends React.Component {

  constructor(props) {
    super(props);
    this.initState = {
      comment: ""
    }
    this.state = this.initState
  }

  deploy = (closeDialog) => {
    const { actions, processId, processVersionId } = this.props
    const comment = this.state.comment

    closeDialog()

    return HttpService.deploy(processId)
      .then(resp => {
        if (resp.isSuccess) {
          actions.addComment(processId, processVersionId, comment)
        }
        actions.displayCurrentProcessVersion(processId)
      })
  }

  okBtnConfig = () => {
    const commentIsRequired = this.props.deploySettings.requireComment
    const isDeployDisabled = commentIsRequired && _.isEmpty(this.state.comment)
    const toolTip = "Comment is required."

    return isDeployDisabled ? {disabled: true, title: toolTip} : {}
  }

  onInputChange = (e) => {
    this.setState({comment: e.target.value})
  }

  render() {
    return (
      <GenericModalDialog
        init={() => this.setState(this.initState)}
        type={Dialogs.types.deployProcess}
        confirm={this.deploy}
        okBtnConfig={this.okBtnConfig()}
      >

Deploy process {this.props.processId}

        <ProcessDialogWarnings processHasWarnings={this.props.processHasWarnings} />
        <CommentInput onChange={this.onInputChange}/>
      </GenericModalDialog>
    );
  }
}

function mapState(state) {
  const processHasNoWarnings = ProcessUtils.hasNoWarnings(state.graphReducer.processToDisplay || {})

  return {
    deploySettings: _.get(state.settings, "featuresSettings.deploySettings") || {},
    processId: _.get(state.graphReducer, 'fetchedProcessDetails.id'),
    processVersionId: _.get(state.graphReducer, "fetchedProcessDetails.processVersionId"),
    processHasWarnings: !processHasNoWarnings
  }
}

export default connect(mapState, ActionsUtils.mapDispatchWithEspActions)(DeployProcessDialog)

<commit_msg>do not refresh page after process deploy when user is on other page already<commit_after>import React from "react";
import {connect} from "react-redux";
import _ from "lodash";
import ActionsUtils from "../../actions/ActionsUtils";
import "../../stylesheets/visualization.styl";
import GenericModalDialog from "./GenericModalDialog";
import Dialogs from "./Dialogs"
import CommentInput from "../CommentInput";
import HttpService from "../../http/HttpService";
import ProcessUtils from "../../common/ProcessUtils";
import ProcessDialogWarnings from "./ProcessDialogWarnings";

class DeployProcessDialog extends React.Component {

  constructor(props) {
    super(props);
    this.initState = {
      comment: ""
    }
    this.state = this.initState
  }

  deploy = (closeDialog) => {
    const { actions, processId, processVersionId } = this.props
    const comment = this.state.comment

    closeDialog()
    const deploymentPath = window.location.pathname
    return HttpService.deploy(processId)
      .then(resp => {
        if (resp.isSuccess) {
          actions.addComment(processId, processVersionId, comment)
        }
        const currentPath = window.location.pathname
        if (currentPath.startsWith(deploymentPath)) {
          actions.displayCurrentProcessVersion(processId)
        }
      })
  }

  okBtnConfig = () => {
    const commentIsRequired = this.props.deploySettings.requireComment
    const isDeployDisabled = commentIsRequired && _.isEmpty(this.state.comment)
    const toolTip = "Comment is required."

    return isDeployDisabled ? {disabled: true, title: toolTip} : {}
  }

  onInputChange = (e) => {
    this.setState({comment: e.target.value})
  }

  render() {
    return (
      <GenericModalDialog
        init={() => this.setState(this.initState)}
        type={Dialogs.types.deployProcess}
        confirm={this.deploy}
        okBtnConfig={this.okBtnConfig()}
      >

Deploy process {this.props.processId}

        <ProcessDialogWarnings processHasWarnings={this.props.processHasWarnings} />
        <CommentInput onChange={this.onInputChange}/>
      </GenericModalDialog>
    );
  }
}

function mapState(state) {
  const processHasNoWarnings = ProcessUtils.hasNoWarnings(state.graphReducer.processToDisplay || {})

  return {
    deploySettings: _.get(state.settings, "featuresSettings.deploySettings") || {},
    processId: _.get(state.graphReducer, 'fetchedProcessDetails.id'),
    processVersionId: _.get(state.graphReducer, "fetchedProcessDetails.processVersionId"),
    processHasWarnings: !processHasNoWarnings
  }
}

export default connect(mapState, ActionsUtils.mapDispatchWithEspActions)(DeployProcessDialog)

<|endoftext|>


<commit_before>/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
var WinChan = require('winchan');

var windowHandler = require('./window');
var objectHelper = require('./object');
var qs = require('qs');

function PopupHandler() {
  this._current_popup = null;
}

PopupHandler.prototype.calculatePosition = function (options) {
  var width = options.width || 500;
  var height = options.height || 600;
  var _window = windowHandler.getWindow();

  var screenX = typeof _window.screenX !== 'undefined' ? _window.screenX : _window.screenLeft;
  var screenY = typeof _window.screenY !== 'undefined' ? _window.screenY : _window.screenTop;

  var outerWidth = typeof _window.outerWidth !== 'undefined'
    ? _window.outerWidth
    : _window.document.body.clientWidth;

  var outerHeight = typeof _window.outerHeight !== 'undefined'
    ? _window.outerHeight
    : _window.document.body.clientHeight;

  var left = screenX + ((outerWidth - width) / 2);
  var top = screenY + ((outerHeight - height) / 2);

  return { width: width, height: height, left: left, top: top };
};

PopupHandler.prototype.preload = function (options) {
  var _this = this;
  var _window = windowHandler.getWindow();
  var popupPosition = this.calculatePosition(options.popupOptions || {});
  var popupOptions = objectHelper.merge(popupPosition).with(options.popupOptions);
  var url = options.url || 'about:blank';
  var windowFeatures = qs.stringify(popupOptions, {
    encode: false,
    delimiter: ','
  });

  if (this._current_popup && !this._current_popup.closed) {
    return this._current_popup;
  }

  this._current_popup = _window.open(url, 'auth0_signup_popup', windowFeatures);

  this._current_popup.kill = function () {
    this.close();
    _this._current_popup = null;
  };

  return this._current_popup;
};

PopupHandler.prototype.load = function (url, relayUrl, options, cb) {
  var _this = this;
  var popupPosition = this.calculatePosition(options.popupOptions || {});
  var popupOptions = objectHelper.merge(popupPosition).with(options.popupOptions);

  var winchanOptions = objectHelper.merge({
    url: url,
    relay_url: relayUrl,
    window_features: qs.stringify(popupOptions, {
        delimiter: ',',
        encode: false
    }),
    popup: this._current_popup
  }).with(options);

  var popup = WinChan.open(winchanOptions, function (err, data) {
    _this._current_popup = null;
    return cb(err, data);
  });

  popup.focus();

  return popup;
};

module.exports = PopupHandler;
<commit_msg>Fix lint errors<commit_after>/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
var WinChan = require('winchan');

var windowHandler = require('./window');
var objectHelper = require('./object');
var qs = require('qs');

function PopupHandler() {
  this._current_popup = null;
}

PopupHandler.prototype.calculatePosition = function (options) {
  var width = options.width || 500;
  var height = options.height || 600;
  var _window = windowHandler.getWindow();

  var screenX = typeof _window.screenX !== 'undefined' ? _window.screenX : _window.screenLeft;
  var screenY = typeof _window.screenY !== 'undefined' ? _window.screenY : _window.screenTop;

  var outerWidth = typeof _window.outerWidth !== 'undefined'
    ? _window.outerWidth
    : _window.document.body.clientWidth;

  var outerHeight = typeof _window.outerHeight !== 'undefined'
    ? _window.outerHeight
    : _window.document.body.clientHeight;

  var left = screenX + ((outerWidth - width) / 2);
  var top = screenY + ((outerHeight - height) / 2);

  return { width: width, height: height, left: left, top: top };
};

PopupHandler.prototype.preload = function (options) {
  var _this = this;
  var _window = windowHandler.getWindow();
  var popupPosition = this.calculatePosition(options.popupOptions || {});
  var popupOptions = objectHelper.merge(popupPosition).with(options.popupOptions);
  var url = options.url || 'about:blank';
  var windowFeatures = qs.stringify(popupOptions, {
    encode: false,
    delimiter: ','
  });

  if (this._current_popup && !this._current_popup.closed) {
    return this._current_popup;
  }

  this._current_popup = _window.open(url, 'auth0_signup_popup', windowFeatures);

  this._current_popup.kill = function () {
    this.close();
    _this._current_popup = null;
  };

  return this._current_popup;
};

PopupHandler.prototype.load = function (url, relayUrl, options, cb) {
  var _this = this;
  var popupPosition = this.calculatePosition(options.popupOptions || {});
  var popupOptions = objectHelper.merge(popupPosition).with(options.popupOptions);

  var winchanOptions = objectHelper.merge({
    url: url,
    relay_url: relayUrl,
    window_features: qs.stringify(popupOptions, {
      delimiter: ',',
      encode: false
    }),
    popup: this._current_popup
  }).with(options);

  var popup = WinChan.open(winchanOptions, function (err, data) {
    _this._current_popup = null;
    return cb(err, data);
  });

  popup.focus();

  return popup;
};

module.exports = PopupHandler;
<|endoftext|>


<commit_before>'use strict'

// Code thanks to MDN
export function storageAvailable (type) {
  try {
    let storage = window[type]
    let x = '__storage_test__'
    storage.setItem(x, x)
    storage.removeItem(x)
    return true
  } catch (e) {
    let storage = window[type]
    return e instanceof DOMException && (
      // everything except Firefox
      e.code === 22 ||
      // Firefox
      e.code === 1014 ||
      // test name field too, because code might not be present
      // everything except Firefox
      e.name === 'QuotaExceededError' ||
      // Firefox
      e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
      // acknowledge QuotaExceededError only if there's something already stored
      storage.length !== 0
  }
}

function storagePopulated () {
  if (Storage.length !== 0) {
    console.log('populated')
    return true
  }
}
<commit_msg>Add function to populate storage<commit_after>'use strict'

// Code thanks to MDN
export function storageAvailable (type) {
  try {
    let storage = window[type]
    let x = '__storage_test__'
    storage.setItem(x, x)
    storage.removeItem(x)
    return true
  } catch (e) {
    let storage = window[type]
    return e instanceof DOMException && (
      // everything except Firefox
      e.code === 22 ||
      // Firefox
      e.code === 1014 ||
      // test name field too, because code might not be present
      // everything except Firefox
      e.name === 'QuotaExceededError' ||
      // Firefox
      e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
      // acknowledge QuotaExceededError only if there's something already stored
      storage.length !== 0
  }
}

export function storagePopulated () {
  if (window.localStorage.length !== 0) {
    console.log('populated')
    return true
  }
}

export function populateStorage () {
  window.localStorage.setItem('pomodoroTime', document.getElementById('pomodoroInput').value)
  window.localStorage.setItem('shortBreakTime', document.getElementById('shortBreakInput').value)
  window.localStorage.setItem('longBreakTime', document.getElementById('longBreakInput').value)
}
<|endoftext|>


<commit_before>/**
 * Movable
 *
 * A Movable Something, that sends onMove events based on the
 * mouse coordinate (graphie unscaled, non-pixel-value) of the
 * move.
 *
 * Other MovableThings should generally have a Movable field, and
 * let this class handle all of the virtual mouse events, and then
 * take appropriate action in onMoveStart, onMove, onMoveEnd
 */

var InteractiveUtil = require("./interactive-util.js");
var normalizeOptions = InteractiveUtil.normalizeOptions;

var knumber = KhanUtil.knumber;
var kpoint = KhanUtil.kpoint;

// state parameters that should be converted into an array of
// functions
var FUNCTION_ARRAY_OPTIONS = [
    "add",
    "modify",
    "draw",
    "remove",
    "onMoveStart",
    "onMove",
    "onMoveEnd",
    "onClick"
];

// Default "props" and "state". Both are added to this.state and
// receive magic getter methods (this.isHovering() etc).
// However, properties in DEFAULT_PROPS are updated on `modify()`,
// while those in DEFAULT_STATE persist and are not updated.
// Things that the user might want to change should be on "props",
// while things used to render the movable should be on "state".
var DEFAULT_PROPS = {
    cursor: null
};
var DEFAULT_STATE = {
    added: false,
    isHovering: false,
    isMouseOver: false,
    isDragging: false,
    mouseTarget: null
};

var Movable = function(graphie, options) {
    _.extend(this, {
        graphie: graphie,
        state: {
            // Set here because this must be unique for each instance
            id: _.uniqueId("movable")
        }
    });

    // We only set DEFAULT_STATE once, here
    this.modify(_.extend({}, DEFAULT_STATE, options));
};

InteractiveUtil.createGettersFor(Movable, _.extend({},
    DEFAULT_PROPS,
    DEFAULT_STATE
));
InteractiveUtil.addMovableHelperMethodsTo(Movable);

_.extend(Movable.prototype, {

    cloneState: function() {
        return _.clone(this.state);
    },

    _createDefaultState: function() {
        return _.extend({
            id: this.state.id,
            add: [],
            modify: [],
            draw: [],
            remove: [],
            onMoveStart: [],
            onMove: [],
            onMoveEnd: [],
            onClick: []

        // We only update props here, because we want things on state to
        // be persistent, and updated appropriately in modify()
        }, DEFAULT_PROPS);
    },

    /**
     * Resets the object to its state as if it were constructed with
     * `options` originally. The only state maintained is `state.id`
     *
     * Analogous to React.js's replaceProps
     */
    modify: function(options) {
        this.update(_.extend({}, this._createDefaultState(), options));
    },

    /**
     * Adjusts constructor parameters without changing previous settings
     * for any option not specified
     *
     * Analogous to React.js's setProps
     */
    update: function(options) {
        var self = this;
        var graphie = self.graphie;

        var prevState = self.cloneState();
        var state = _.extend(
            self.state,
            normalizeOptions(FUNCTION_ARRAY_OPTIONS, options)
        );

        // the invisible shape in front of the point that gets mouse events
        if (state.mouseTarget && !prevState.mouseTarget) {
            var $mouseTarget = $(state.mouseTarget[0]);

            var isMouse = !('ontouchstart' in window);

            if (isMouse) {
                $mouseTarget.on("mouseover", function(e) {
                    state.isMouseOver = true;
                    if (!graphie.isDragging) {
                        state.isHovering = true;
                    }
                    self.draw();
                });

                $mouseTarget.on("mouseout", function(e) {
                    state.isMouseOver = false;
                    if (!state.isDragging) {
                        state.isHovering = false;
                    }
                    self.draw();
                });
            }

            $mouseTarget.on("vmousedown", function(e) {
                if (e.which !== 0 && e.which !== 1) {
                    return;
                }
                e.preventDefault();

                var startMouseCoord = graphie.getMouseCoord(e);
                var prevMouseCoord = startMouseCoord;
                self._fireEvent(
                    state.onMoveStart,
                    startMouseCoord,
                    startMouseCoord
                );
                state.isHovering = true;

                $(document).bind("vmousemove", function(e) {
                    e.preventDefault();

                    state.isDragging = true;
                    graphie.isDragging = true;

                    var mouseCoord = graphie.getMouseCoord(e);
                    self._fireEvent(
                        state.onMove,
                        mouseCoord,
                        prevMouseCoord
                    );
                    self.draw();
                    prevMouseCoord = mouseCoord;
                });

                $(document).bind("vmouseup", function(e) {
                    $(document).unbind("vmousemove vmouseup");
                    if (state.isHovering) {
                        self._fireEvent(
                            state.onClick,
                            prevMouseCoord,
                            startMouseCoord
                        );
                    }
                    state.isHovering = self.state.isMouseOver;
                    state.isDragging = false;
                    graphie.isDragging = false;
                    self._fireEvent(
                        state.onMoveEnd,
                        prevMouseCoord,
                        startMouseCoord
                    );
                    self.draw();
                });
            });
        }

        if (state.mouseTarget && state.cursor !== undefined) {
            // "" removes the css cursor if state.cursor is null
            $(state.mouseTarget[0]).css("cursor", state.cursor || "");
        }

        // Trigger an add event if this hasn't been added before
        if (!state.added) {
            self._fireEvent(state.modify, self.cloneState(), {});
            state.added = true;

            // Update the state for `added` and in case the add event
            // changed it
            self.prevState = self.cloneState();
        }

        // Trigger a modify event
        self._fireEvent(state.modify, self.cloneState(), self.prevState);
    },

    remove: function() {
        this.state.added = false;
        this._fireEvent(this.state.remove);
        if (this.state.mouseTarget) {
            $(this.state.mouseTarget).off();
            this.state.mouseTarget.remove();
            this.state.mouseTarget = null;
        }
    },

    // Change z-order to back
    toBack: function() {
        if (this.state.mouseTarget) {
            this.state.mouseTarget.toBack();
        }
    },

    // Change z-order to front
    toFront: function() {
        if (this.state.mouseTarget) {
            this.state.mouseTarget.toFront();
        }
    }
});

module.exports = Movable;
<commit_msg>Points now delete properly in click-to-add-points<commit_after>/**
 * Movable
 *
 * A Movable Something, that sends onMove events based on the
 * mouse coordinate (graphie unscaled, non-pixel-value) of the
 * move.
 *
 * Other MovableThings should generally have a Movable field, and
 * let this class handle all of the virtual mouse events, and then
 * take appropriate action in onMoveStart, onMove, onMoveEnd
 */

var InteractiveUtil = require("./interactive-util.js");
var normalizeOptions = InteractiveUtil.normalizeOptions;

var knumber = KhanUtil.knumber;
var kpoint = KhanUtil.kpoint;

// state parameters that should be converted into an array of
// functions
var FUNCTION_ARRAY_OPTIONS = [
    "add",
    "modify",
    "draw",
    "remove",
    "onMoveStart",
    "onMove",
    "onMoveEnd",
    "onClick"
];

// Default "props" and "state". Both are added to this.state and
// receive magic getter methods (this.isHovering() etc).
// However, properties in DEFAULT_PROPS are updated on `modify()`,
// while those in DEFAULT_STATE persist and are not updated.
// Things that the user might want to change should be on "props",
// while things used to render the movable should be on "state".
var DEFAULT_PROPS = {
    cursor: null
};
var DEFAULT_STATE = {
    added: false,
    isHovering: false,
    isMouseOver: false,
    isDragging: false,
    mouseTarget: null
};

var Movable = function(graphie, options) {
    _.extend(this, {
        graphie: graphie,
        state: {
            // Set here because this must be unique for each instance
            id: _.uniqueId("movable")
        }
    });

    // We only set DEFAULT_STATE once, here
    this.modify(_.extend({}, DEFAULT_STATE, options));
};

InteractiveUtil.createGettersFor(Movable, _.extend({},
    DEFAULT_PROPS,
    DEFAULT_STATE
));
InteractiveUtil.addMovableHelperMethodsTo(Movable);

_.extend(Movable.prototype, {

    cloneState: function() {
        return _.clone(this.state);
    },

    _createDefaultState: function() {
        return _.extend({
            id: this.state.id,
            add: [],
            modify: [],
            draw: [],
            remove: [],
            onMoveStart: [],
            onMove: [],
            onMoveEnd: [],
            onClick: []

        // We only update props here, because we want things on state to
        // be persistent, and updated appropriately in modify()
        }, DEFAULT_PROPS);
    },

    /**
     * Resets the object to its state as if it were constructed with
     * `options` originally. The only state maintained is `state.id`
     *
     * Analogous to React.js's replaceProps
     */
    modify: function(options) {
        this.update(_.extend({}, this._createDefaultState(), options));
    },

    /**
     * Adjusts constructor parameters without changing previous settings
     * for any option not specified
     *
     * Analogous to React.js's setProps
     */
    update: function(options) {
        var self = this;
        var graphie = self.graphie;

        var prevState = self.cloneState();
        var state = _.extend(
            self.state,
            normalizeOptions(FUNCTION_ARRAY_OPTIONS, options)
        );

        // the invisible shape in front of the point that gets mouse events
        if (state.mouseTarget && !prevState.mouseTarget) {
            var $mouseTarget = $(state.mouseTarget[0]);

            var isMouse = !('ontouchstart' in window);

            if (isMouse) {
                $mouseTarget.on("vmouseover", function() {
                    state.isMouseOver = true;
                    if (!graphie.isDragging) {
                        state.isHovering = true;
                    }
                    self.draw();
                });

                $mouseTarget.on("vmouseout", function() {
                    state.isMouseOver = false;
                    if (!state.isDragging) {
                        state.isHovering = false;
                    }
                    self.draw();
                });
            }

            $mouseTarget.on("vmousedown", function(e) {
                if (e.which !== 0 && e.which !== 1) {
                    return;
                }
                e.preventDefault();

                var startMouseCoord = graphie.getMouseCoord(e);
                var prevMouseCoord = startMouseCoord;
                self._fireEvent(
                    state.onMoveStart,
                    startMouseCoord,
                    startMouseCoord
                );
                state.isHovering = true;

                $(document).bind("vmousemove", function(e) {
                    e.preventDefault();

                    state.isDragging = true;
                    graphie.isDragging = true;

                    var mouseCoord = graphie.getMouseCoord(e);
                    self._fireEvent(
                        state.onMove,
                        mouseCoord,
                        prevMouseCoord
                    );
                    self.draw();
                    prevMouseCoord = mouseCoord;
                });

                $(document).bind("vmouseup", function(e) {
                    $(document).unbind("vmousemove vmouseup");
                    if (state.isHovering) {
                        self._fireEvent(
                            state.onClick,
                            prevMouseCoord,
                            startMouseCoord
                        );
                    }
                    state.isHovering = self.state.isMouseOver;
                    state.isDragging = false;
                    graphie.isDragging = false;
                    self._fireEvent(
                        state.onMoveEnd,
                        prevMouseCoord,
                        startMouseCoord
                    );
                    self.draw();
                });
            });
        }

        if (state.mouseTarget && state.cursor !== undefined) {
            // "" removes the css cursor if state.cursor is null
            $(state.mouseTarget[0]).css("cursor", state.cursor || "");
        }

        // Trigger an add event if this hasn't been added before
        if (!state.added) {
            self._fireEvent(state.modify, self.cloneState(), {});
            state.added = true;

            // Update the state for `added` and in case the add event
            // changed it
            self.prevState = self.cloneState();
        }

        // Trigger a modify event
        self._fireEvent(state.modify, self.cloneState(), self.prevState);
    },

    remove: function() {
        this.state.added = false;
        this._fireEvent(this.state.remove);
        if (this.state.mouseTarget) {
            $(this.state.mouseTarget).off();
            this.state.mouseTarget.remove();
            this.state.mouseTarget = null;
        }
    },

    // Change z-order to back
    toBack: function() {
        if (this.state.mouseTarget) {
            this.state.mouseTarget.toBack();
        }
    },

    // Change z-order to front
    toFront: function() {
        if (this.state.mouseTarget) {
            this.state.mouseTarget.toFront();
        }
    }
});

module.exports = Movable;
<|endoftext|>


<commit_before>/**
 * Basic polyfill for Pointer Events W3C Specification.
 *
 * @author Kir Belevich <kir@soulshine.in>
 * @copyright Kir Belevich 2013
 * @license MIT
 * @version 0.4.0
 */
(function(win, $) {

    /*global jQuery:true*/
    'use strict';

    /*
       http://www.w3.org/TR/pointerevents/
       https://dvcs.w3.org/hg/pointerevents/raw-file/tip/pointerEvents.html
       https://dvcs.w3.org/hg/webevents/raw-file/default/touchevents.html
       http://msdn.microsoft.com/en-US/library/ie/hh673557.aspx
       http://www.benalman.com/news/2010/03/jquery-special-events/
       http://api.jquery.com/category/events/event-object/
    */

    var doc = win.document,
        binds = {
            mouse: {
                enter: 'mouseenter',
                over: 'mouseover',
                down: 'mousedown',
                move: 'mousemove',
                up: 'mouseup',
                out: 'mouseout',
                leave: 'mouseleave'
            },

            touch: {
                enter: 'touchstart',
                over: 'touchstart',
                down: 'touchstart',
                move: 'touchmove',
                up: 'touchend',
                out: 'touchend',
                leave: 'touchend',
                cancel: 'touchcancel'
            },

            mspointer: {
                over: 'MSPointerOver',
                down: 'MSPointerDown',
                move: 'MSPointerMove',
                up: 'MSPointerUp',
                out: 'MSPointerOut',
                cancel: 'MSPointerCancel'
            }
        };

    /**
     * Normalize touch-event by keeping all the
     * possible properties normalized by jQuery.
     *
     * @see http://api.jquery.com/category/events/event-object/
     *
     * @param {Object} e event
     */
    function normalizeTouchEvent(e) {

        if(e.pointerType === 'touch') {

            e.originalEvent = e.originalEvent || e;

            // multitouch
            if(e.originalEvent.touches.length > 1) {
                e.multitouch = true;
                return;
            }

            var touchPoint = e.originalEvent.changedTouches[0];

            // keep all the properties normalized by jQuery
            e.clientX = touchPoint.clientX;
            e.clientY = touchPoint.clientY;
            e.pageX = touchPoint.pageX;
            e.pageY = touchPoint.pageY;
            e.screenX = touchPoint.screenX;
            e.screenY = touchPoint.screenY;
            e.layerX = e.originalEvent.layerX;
            e.layerY = e.originalEvent.layerY;
            e.offsetX = e.layerX - e.target.offsetLeft;
            e.offsetY = e.layerY - e.target.offsetTop;
            e.identifier = touchPoint.identifier;
        }

    }

    /**
     * Extend event to match PointerEvent Interface.
     *
     * @see https://dvcs.w3.org/hg/pointerevents/raw-file/tip/pointerEvents.html#pointer-events-and-interfaces
     * @see https://dvcs.w3.org/hg/webevents/raw-file/default/touchevents.html
     *
     * @param {object} e event
     */
    function extendToPointerEvent(e) {

        /*eslint complexity:0*/
        e.width = e.width ||
                  e.webkitRadiusX ||
                  e.radiusX ||
                  0;

        e.height = e.width ||
                   e.webkitRadiusY ||
                   e.radiusY ||
                   0;

        // TODO: stupid Android somehow could send "force" > 1 ;(
        e.pressure = e.pressure ||
                     e.mozPressure ||
                     e.webkitForce ||
                     e.force ||
                     e.which && 0.5 ||
                     0;

        e.tiltX = e.tiltX || 0;
        e.tiltY = e.tiltY || 0;

        switch(e.pointerType) {
            case 2: e.pointerType = 'touch'; break;
            case 3: e.pointerType = 'pen'; break;
            case 4: e.pointerType = 'mouse'; break;
            default: e.pointerType = e.pointerType;
        }

        e.isPrimary = true;

        // "1" is always for mouse, need to +2 for touch which can start from "0"
        e.pointerId = e.identifier ? e.identifier + 2 : 1;

    }

    /**
     * Mutate an event to PointerEvent.
     *
     * @param {object} e current event object
     * @param {string} type future pointerevent type
     */
    function PointerEvent(e, type) {

        extendToPointerEvent(e);
        normalizeTouchEvent(e);
        e.type = type;

        $.extend(this, e);

    }

    // export PointerEvent class
    $.PointerEvent = PointerEvent;

    // nothing to do in IE11 for today
    if(win.navigator.pointerEnabled) {
        return;
    }

    /**
     * Create new $.event.special wrapper with some default behavior.
     *
     * @param {string} type event type
     * @param {object} toExtend object to extend default wrapper
     */
    function addPointerEvent(type, toExtend) {

        var eventName = 'pointer' + type,
            pointerevent,

            eventSpecial = $.event.special[eventName] = {
                // touch/mspointer event is already in the process
                _processed: false,

                // bind
                setup: function() {
                    $(this)
                        .on(binds.mouse[type], eventSpecial.mouseHandler)
                        .on(binds.touch[type], eventSpecial.touchHandler)
                        .on(binds.mspointer[type], eventSpecial.msPointerHandler);
                },

                // unbind
                teardown: function() {
                    $(this)
                        .off(binds.mouse[type], eventSpecial.mouseHandler)
                        .off(binds.touch[type], eventSpecial.touchHandler)
                        .off(binds.mspointer[type], eventSpecial.msPointerHandler);
                },

                // mouse
                mouseHandler: function(e) {

                    // ignore all handler calls due to bubbling
                    if(e.target !== e.currentTarget) { return; }

                    // do not duplicate PointerEvent if
                    // touch/mspointer is already processed
                    if(eventSpecial._processed === false) {
                        e.pointerType = 4;
                        pointerevent = new PointerEvent(e, eventName);
                        $(e.target).trigger(pointerevent);
                    }

                    // clear the "processed" key right after
                    // current event and all the bubblings
                    setTimeout(function() {
                        eventSpecial._processed = false;
                    }, 0);
                },

                // touch
                touchHandler: function(e) {
                    // ignore all handler calls due to bubbling
                    if(e.target !== e.currentTarget){ return; }

                    // stop mouse events handling
                    eventSpecial._processed = true;

                    e.pointerType = 2;
                    pointerevent = new PointerEvent(e, eventName);

                    $(e.target).trigger(pointerevent);
                },

                // mspointer
                msPointerHandler: function(e) {
                    // ignore all handler calls due to bubbling
                    if(e.target !== e.currentTarget){ return; }

                    // stop mouse events handling
                    eventSpecial._processed = true;

                    pointerevent = new PointerEvent(e, eventName);
                    $(e.target).trigger(pointerevent);
                }
            };

        // extend this $.event.special wrapper
        if(toExtend) {
            $.extend(eventSpecial, toExtend(eventSpecial, eventName, type));
        }

    }

    /**
     * Object to extend $.event.special touchHandler
     * with "elementFromPoint" target.
     *
     * @param {object} eventSpecial current $.event.special
     * @param {sring} eventName event name
     * @return {object}
     */
    function extendTouchHandlerWithTarget(eventSpecial, eventName) {

        return {
            touchHandler: function(e) {
                // ignore all handler calls due to bubbling
                if(e.target !== e.currentTarget) { return; }

                // stop mouse events handling
                eventSpecial._processed = true;

                e.pointerType = 2;

                var pointerevent = new PointerEvent(e, eventName),
                    targetFromPoint = doc.elementFromPoint(pointerevent.clientX, pointerevent.clientY);

                $(targetFromPoint).trigger(pointerevent);
            }
        }

    }

    /**
     * Object to extend $.event.special to handle
     * pointermove with touch events.
     *
     * @param {object} eventSpecial current $.event.special
     * @param {sring} eventName event name
     * @return {object}
     */
    function extendTouchMove(eventSpecial, eventName, type) {

        return {
            setup: function() {
                $(this)
                    .on(binds.mouse[type], eventSpecial.mouseHandler)
                    .on(binds.touch[type], eventSpecial.touchHandler)
                    .on(binds.touch.down, eventSpecial.touchDownHandler)
                    .on(binds.mspointer[type], eventSpecial.msPointerHandler);
            },

            teardown: function() {
                $(this)
                    .off(binds.mouse[type], eventSpecial.mouseHandler)
                    .off(binds.touch[type], eventSpecial.touchHandler)
                    .off(binds.touch.down, eventSpecial.touchDownHandler)
                    .off(binds.mspointer[type], eventSpecial.msPointerHandler);
            },

            touchDownHandler: function(e) {
                // stop mouse events handling
                eventSpecial._processed = true;
                eventSpecial._target = e.target;
            },

            touchHandler: function(e) {
                // ignore all handler calls due to bubbling
                if(e.target !== e.currentTarget) { return; }

                e.pointerType = 2;

                var pointerevent = new PointerEvent(e, eventName),
                    targetFromPoint = doc.elementFromPoint(pointerevent.clientX, pointerevent.clientY),
                    target = eventSpecial._target;

                $(targetFromPoint).trigger(pointerevent);

                // new target
                if(target !== targetFromPoint) {
                    // out target
                    pointerevent = new PointerEvent(e, 'pointerout');
                    $(target).trigger(pointerevent);

                    pointerevent = new PointerEvent(e, 'pointerleave');
                    // leave to parent
                    if(targetFromPoint.contains(target)) {
                        $(target).triggerHandler(pointerevent);
                    // leave!
                    } else {
                        $(target).trigger(pointerevent);
                    }

                    // new target is not the parent of the current -> leave targetFromPoint
                    if(!targetFromPoint.contains(target)) {
                        pointerevent = new PointerEvent(e, 'pointerenter');
                        $(targetFromPoint).trigger(pointerevent);
                    }

                    // over targetFromPoint
                    pointerevent = new PointerEvent(e, 'pointerover');
                    $(targetFromPoint).trigger(pointerevent);

                    // targetFromPoint -> target
                    eventSpecial._target = targetFromPoint;
                }
            }
        }

    }

    // init pointer events
    addPointerEvent('enter');
    addPointerEvent('over');
    addPointerEvent('down');
    addPointerEvent('move', extendTouchMove);
    addPointerEvent('up', extendTouchHandlerWithTarget);
    addPointerEvent('out', extendTouchHandlerWithTarget);
    addPointerEvent('leave', extendTouchHandlerWithTarget);
    addPointerEvent('cancel');

})(window, jQuery);
<commit_msg>AMDify<commit_after>/**
 * Basic polyfill for Pointer Events W3C Specification.
 *
 * @author Kir Belevich <kir@soulshine.in>
 * @copyright Kir Belevich 2013
 * @license MIT
 * @version 0.4.0
 */
 (function(factory) {

    /*global define*/
    'use strict';

    // AMD
    if(typeof define === 'function' && define.amd) {
        define([ 'jquery' ], factory);
    // browser globals
    } else {
        factory(jQuery);
    }

 }(function($) {

    /*global jQuery*/
    'use strict';

    /*
       http://www.w3.org/TR/pointerevents/
       https://dvcs.w3.org/hg/pointerevents/raw-file/tip/pointerEvents.html
       https://dvcs.w3.org/hg/webevents/raw-file/default/touchevents.html
       http://msdn.microsoft.com/en-US/library/ie/hh673557.aspx
       http://www.benalman.com/news/2010/03/jquery-special-events/
       http://api.jquery.com/category/events/event-object/
    */

    var win = window,
        doc = win.document,
        binds = {
            mouse: {
                enter: 'mouseenter',
                over: 'mouseover',
                down: 'mousedown',
                move: 'mousemove',
                up: 'mouseup',
                out: 'mouseout',
                leave: 'mouseleave'
            },

            touch: {
                enter: 'touchstart',
                over: 'touchstart',
                down: 'touchstart',
                move: 'touchmove',
                up: 'touchend',
                out: 'touchend',
                leave: 'touchend',
                cancel: 'touchcancel'
            },

            mspointer: {
                over: 'MSPointerOver',
                down: 'MSPointerDown',
                move: 'MSPointerMove',
                up: 'MSPointerUp',
                out: 'MSPointerOut',
                cancel: 'MSPointerCancel'
            }
        };

    /**
     * Normalize touch-event by keeping all the
     * possible properties normalized by jQuery.
     *
     * @see http://api.jquery.com/category/events/event-object/
     *
     * @param {Object} e event
     */
    function normalizeTouchEvent(e) {

        if(e.pointerType === 'touch') {

            e.originalEvent = e.originalEvent || e;

            // multitouch
            if(e.originalEvent.touches.length > 1) {
                e.multitouch = true;
                return;
            }

            var touchPoint = e.originalEvent.changedTouches[0];

            // keep all the properties normalized by jQuery
            e.clientX = touchPoint.clientX;
            e.clientY = touchPoint.clientY;
            e.pageX = touchPoint.pageX;
            e.pageY = touchPoint.pageY;
            e.screenX = touchPoint.screenX;
            e.screenY = touchPoint.screenY;
            e.layerX = e.originalEvent.layerX;
            e.layerY = e.originalEvent.layerY;
            e.offsetX = e.layerX - e.target.offsetLeft;
            e.offsetY = e.layerY - e.target.offsetTop;
            e.identifier = touchPoint.identifier;
        }

    }

    /**
     * Extend event to match PointerEvent Interface.
     *
     * @see https://dvcs.w3.org/hg/pointerevents/raw-file/tip/pointerEvents.html#pointer-events-and-interfaces
     * @see https://dvcs.w3.org/hg/webevents/raw-file/default/touchevents.html
     *
     * @param {object} e event
     */
    function extendToPointerEvent(e) {

        /*eslint complexity:0*/
        e.width = e.width ||
                  e.webkitRadiusX ||
                  e.radiusX ||
                  0;

        e.height = e.width ||
                   e.webkitRadiusY ||
                   e.radiusY ||
                   0;

        // TODO: stupid Android somehow could send "force" > 1 ;(
        e.pressure = e.pressure ||
                     e.mozPressure ||
                     e.webkitForce ||
                     e.force ||
                     e.which && 0.5 ||
                     0;

        e.tiltX = e.tiltX || 0;
        e.tiltY = e.tiltY || 0;

        switch(e.pointerType) {
            case 2: e.pointerType = 'touch'; break;
            case 3: e.pointerType = 'pen'; break;
            case 4: e.pointerType = 'mouse'; break;
            default: e.pointerType = e.pointerType;
        }

        e.isPrimary = true;

        // "1" is always for mouse, need to +2 for touch which can start from "0"
        e.pointerId = e.identifier ? e.identifier + 2 : 1;

    }

    /**
     * Mutate an event to PointerEvent.
     *
     * @param {object} e current event object
     * @param {string} type future pointerevent type
     */
    function PointerEvent(e, type) {

        extendToPointerEvent(e);
        normalizeTouchEvent(e);
        e.type = type;

        $.extend(this, e);

    }

    // export PointerEvent class
    $.PointerEvent = PointerEvent;

    // nothing to do in IE11 for today
    if(win.navigator.pointerEnabled) {
        return;
    }

    /**
     * Create new $.event.special wrapper with some default behavior.
     *
     * @param {string} type event type
     * @param {object} toExtend object to extend default wrapper
     */
    function addPointerEvent(type, toExtend) {

        var eventName = 'pointer' + type,
            pointerevent,

            eventSpecial = $.event.special[eventName] = {
                // touch/mspointer event is already in the process
                _processed: false,

                // bind
                setup: function() {
                    $(this)
                        .on(binds.mouse[type], eventSpecial.mouseHandler)
                        .on(binds.touch[type], eventSpecial.touchHandler)
                        .on(binds.mspointer[type], eventSpecial.msPointerHandler);
                },

                // unbind
                teardown: function() {
                    $(this)
                        .off(binds.mouse[type], eventSpecial.mouseHandler)
                        .off(binds.touch[type], eventSpecial.touchHandler)
                        .off(binds.mspointer[type], eventSpecial.msPointerHandler);
                },

                // mouse
                mouseHandler: function(e) {

                    // ignore all handler calls due to bubbling
                    if(e.target !== e.currentTarget) { return; }

                    // do not duplicate PointerEvent if
                    // touch/mspointer is already processed
                    if(eventSpecial._processed === false) {
                        e.pointerType = 4;
                        pointerevent = new PointerEvent(e, eventName);
                        $(e.target).trigger(pointerevent);
                    }

                    // clear the "processed" key right after
                    // current event and all the bubblings
                    setTimeout(function() {
                        eventSpecial._processed = false;
                    }, 0);
                },

                // touch
                touchHandler: function(e) {
                    // ignore all handler calls due to bubbling
                    if(e.target !== e.currentTarget){ return; }

                    // stop mouse events handling
                    eventSpecial._processed = true;

                    e.pointerType = 2;
                    pointerevent = new PointerEvent(e, eventName);

                    $(e.target).trigger(pointerevent);
                },

                // mspointer
                msPointerHandler: function(e) {
                    // ignore all handler calls due to bubbling
                    if(e.target !== e.currentTarget){ return; }

                    // stop mouse events handling
                    eventSpecial._processed = true;

                    pointerevent = new PointerEvent(e, eventName);
                    $(e.target).trigger(pointerevent);
                }
            };

        // extend this $.event.special wrapper
        if(toExtend) {
            $.extend(eventSpecial, toExtend(eventSpecial, eventName, type));
        }

    }

    /**
     * Object to extend $.event.special touchHandler
     * with "elementFromPoint" target.
     *
     * @param {object} eventSpecial current $.event.special
     * @param {sring} eventName event name
     * @return {object}
     */
    function extendTouchHandlerWithTarget(eventSpecial, eventName) {

        return {
            touchHandler: function(e) {
                // ignore all handler calls due to bubbling
                if(e.target !== e.currentTarget) { return; }

                // stop mouse events handling
                eventSpecial._processed = true;

                e.pointerType = 2;

                var pointerevent = new PointerEvent(e, eventName),
                    targetFromPoint = doc.elementFromPoint(pointerevent.clientX, pointerevent.clientY);

                $(targetFromPoint).trigger(pointerevent);
            }
        }

    }

    /**
     * Object to extend $.event.special to handle
     * pointermove with touch events.
     *
     * @param {object} eventSpecial current $.event.special
     * @param {sring} eventName event name
     * @return {object}
     */
    function extendTouchMove(eventSpecial, eventName, type) {

        return {
            setup: function() {
                $(this)
                    .on(binds.mouse[type], eventSpecial.mouseHandler)
                    .on(binds.touch[type], eventSpecial.touchHandler)
                    .on(binds.touch.down, eventSpecial.touchDownHandler)
                    .on(binds.mspointer[type], eventSpecial.msPointerHandler);
            },

            teardown: function() {
                $(this)
                    .off(binds.mouse[type], eventSpecial.mouseHandler)
                    .off(binds.touch[type], eventSpecial.touchHandler)
                    .off(binds.touch.down, eventSpecial.touchDownHandler)
                    .off(binds.mspointer[type], eventSpecial.msPointerHandler);
            },

            touchDownHandler: function(e) {
                // stop mouse events handling
                eventSpecial._processed = true;
                eventSpecial._target = e.target;
            },

            touchHandler: function(e) {
                // ignore all handler calls due to bubbling
                if(e.target !== e.currentTarget) { return; }

                e.pointerType = 2;

                var pointerevent = new PointerEvent(e, eventName),
                    targetFromPoint = doc.elementFromPoint(pointerevent.clientX, pointerevent.clientY),
                    target = eventSpecial._target;

                $(targetFromPoint).trigger(pointerevent);

                // new target
                if(target !== targetFromPoint) {
                    // out target
                    pointerevent = new PointerEvent(e, 'pointerout');
                    $(target).trigger(pointerevent);

                    pointerevent = new PointerEvent(e, 'pointerleave');
                    // leave to parent
                    if(targetFromPoint.contains(target)) {
                        $(target).triggerHandler(pointerevent);
                    // leave!
                    } else {
                        $(target).trigger(pointerevent);
                    }

                    // new target is not the parent of the current -> leave targetFromPoint
                    if(!targetFromPoint.contains(target)) {
                        pointerevent = new PointerEvent(e, 'pointerenter');
                        $(targetFromPoint).trigger(pointerevent);
                    }

                    // over targetFromPoint
                    pointerevent = new PointerEvent(e, 'pointerover');
                    $(targetFromPoint).trigger(pointerevent);

                    // targetFromPoint -> target
                    eventSpecial._target = targetFromPoint;
                }
            }
        }

    }

    // init pointer events
    addPointerEvent('enter');
    addPointerEvent('over');
    addPointerEvent('down');
    addPointerEvent('move', extendTouchMove);
    addPointerEvent('up', extendTouchHandlerWithTarget);
    addPointerEvent('out', extendTouchHandlerWithTarget);
    addPointerEvent('leave', extendTouchHandlerWithTarget);
    addPointerEvent('cancel');

 }));
<|endoftext|>


<commit_before>jsHyphen.factory("IndexedDbCommandBase", ['$q', function () {
    var IndexedDbCommandBase = function (name, version) {
        var self = this;
        this.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

        if (!this.indexedDB) {
            console.log("Indexed db not supported, offline mode not supported");
        }
        var request;
        if(version) {
            request = window.indexedDB.open(name, version);
        }else{
            request = window.indexedDB.open(name, version);
        }
        request.onsuccess = function (event) {
            self.db = event.target.result;
            //IndexedDbC self.db;
            if (self.openEvent) {
                self.openEvent(event);
            }

        }
        request.onerror = function (event) {
            console.log(event);
        };
        request.onupgradeneeded = function (event) {
            if (self.upgradeEvent) {
                self.upgradeEvent(event);
            }
        };

        request.oncomplete = function (event) {
            console.log(event);
        }
    }

    return IndexedDbCommandBase;
}]);

jsHyphen.factory("HyphenIndexDb", ['$q', 'IndexedDbCommandBase', function ($q, IndexedDbCommandBase) {
    var HyphenIndexDb = function (name, version) {
        IndexedDbCommandBase.call(this, name, version);
        HyphenIndexDb.instance = this;
    }
    HyphenIndexDb.prototype = Object.create(IndexedDbCommandBase.prototype);

    //static methods

    HyphenIndexDb.closeDb = function () {
        this.db=HyphenIndexDb.instance.db;
        if (this.db) {
            this.db.close();
            this.db = null;
        }
    }

    HyphenIndexDb.isInitialized = function () {
        if (HyphenIndexDb.instance && HyphenIndexDb.instance.db) {
            return true;
        }
        else {
            return false;
        }
    }

    HyphenIndexDb.addRecordToStore = function (data, store, id) {
        var transaction = HyphenIndexDb.instance.db.transaction(store, "readwrite");
        var storeObject = transaction.objectStore(store);
        storeObject.add(data, id);
    }

    HyphenIndexDb.addOrUpdateRecord = function (record, store, id) {
        var self = this;
        var transaction = HyphenIndexDb.instance.db.transaction(store, "readwrite");
        var storeObject = transaction.objectStore(store);
        var request = storeObject.get(id);
        request.onerror = function () {
            console.log('can not get record ' + record);
        };
        request.onsuccess = function () {
            // Do something with the request.result!
            if (request.result) {
                self.updateRecord(record, store, id);
            } else {
                self.addRecordToStore(record, store, id);
            }
        };
    }

    HyphenIndexDb.updateRecordStore = function (data, store, id) {
        var objectStore = HyphenIndexDb.instance.db.transaction(store, "readwrite").objectStore(store);
        var request = objectStore.get(id);
        request.onsuccess = function () {
            objectStore.put(data, id);
        };
    }

    //instance methods
    HyphenIndexDb.deleteRecord = function (store, id) {
        var objectStore = HyphenIndexDb.instance.db.transaction(store, "readwrite").objectStore(store);
        objectStore.delete(id);
    }

    HyphenIndexDb.prototype.createStore = function (store, key, transaction) {
        var request = transaction.target.result.createObjectStore(store, {
            autoIncrement: false
        });

        return request;
    }

    HyphenIndexDb.prototype.removeStore = function (store, transaction) {
        var request = transaction.target.result.deleteObjectStore(store, transaction);
        return request;
    }

    HyphenIndexDb.prototype.upgradeEvent = function (method) {
        return this.upgradeEvent = method;
    }

    HyphenIndexDb.prototype.openEvent = function (method) {
        return this.openEvent = method;
    }

    HyphenIndexDb.prototype.getStoreData = function (store) {
        var transaction = this.db.transaction(store.name, "readwrite");
        var dbStore = transaction.objectStore(store.name);
        var request = dbStore.openCursor();
        var data = [];
        var deferred = $q.defer();
        request.onsuccess = function (event) {
            var cursor = event.target.result;
            if (cursor) {
                data.push(cursor.value);
                cursor.continue();
            } else {
                deferred.resolve({data: data, model: store});
            }
        }
        request.onerror = function (event) {
            deferred.resolve(event);
        };
        return deferred.promise;
    }

    return HyphenIndexDb;
}]);<commit_msg>-more indexed db refactor<commit_after>jsHyphen.factory("HyphenIndexDb", ['$q', function ($q) {
    var HyphenIndexDb = function (name, version) {
        var self = this;
        var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

        if (!indexedDB) {
            console.log("Indexed db not supported, offline mode not supported");
        }
        var request;
        if(version) {
            request = indexedDB.open(name, version);
        }else{
            request = indexedDB.open(name);
        }
        request.onsuccess = function (event) {
            HyphenIndexDb.db = event.target.result;
            if (self.openEvent) {
                self.openEvent(event);
            }
        }
        request.onerror = function (event) {
            console.log(event);
        };

        request.onupgradeneeded = function (event) {
            if (self.upgradeEvent) {
                self.upgradeEvent(event);
            }
        };

        request.oncomplete = function (event) {
            console.log(event);
        }
    }

    //static methods
    HyphenIndexDb.closeDb = function () {
        this.db=HyphenIndexDb.db;
        if (this.db) {
            this.db.close();
            this.db = null;
        }
    }

    HyphenIndexDb.isInitialized = function () {
        if (HyphenIndexDb.db) {
            return true;
        }
        else {
            return false;
        }
    }

    HyphenIndexDb.addRecordToStore = function (data, store, id) {
        var transaction = HyphenIndexDb.db.transaction(store, "readwrite");
        var storeObject = transaction.objectStore(store);
        storeObject.add(data, id);
    }

    HyphenIndexDb.addOrUpdateRecord = function (record, store, id) {
        var self = this;
        var transaction = HyphenIndexDb.db.transaction(store, "readwrite");
        var storeObject = transaction.objectStore(store);
        var request = storeObject.get(id);
        request.onerror = function () {
            console.log('can not get record ' + record);
        };
        request.onsuccess = function () {
            // Do something with the request.result!
            if (request.result) {
                self.updateRecord(record, store, id);
            } else {
                self.addRecordToStore(record, store, id);
            }
        };
    }

    HyphenIndexDb.updateRecordStore = function (data, store, id) {
        var objectStore = HyphenIndexDb.db.transaction(store, "readwrite").objectStore(store);
        var request = objectStore.get(id);
        request.onsuccess = function () {
            objectStore.put(data, id);
        };
    }

    HyphenIndexDb.prototype.getStoreData = function (store) {
        var transaction = HyphenIndexDb.db.transaction(store.name, "readwrite");
        var dbStore = transaction.objectStore(store.name);
        var request = dbStore.openCursor();
        var data = [];
        var deferred = $q.defer();
        request.onsuccess = function (event) {
            var cursor = event.target.result;
            if (cursor) {
                data.push(cursor.value);
                cursor.continue();
            } else {
                deferred.resolve({data: data, model: store});
            }
        }
        request.onerror = function (event) {
            deferred.resolve(event);
        };
        return deferred.promise;
    }

    //instance methods
    HyphenIndexDb.deleteRecord = function (store, id) {
        var objectStore = HyphenIndexDb.db.transaction(store, "readwrite").objectStore(store);
        objectStore.delete(id);
    }

    HyphenIndexDb.prototype.createStore = function (store, key, transaction) {
        var request = transaction.target.result.createObjectStore(store, {
            autoIncrement: false
        });

        return request;
    }

    HyphenIndexDb.prototype.removeStore = function (store, transaction) {
        var request = transaction.target.result.deleteObjectStore(store, transaction);
        return request;
    }

    HyphenIndexDb.prototype.upgradeEvent = function (method) {
        return this.upgradeEvent = method;
    }

    HyphenIndexDb.prototype.openEvent = function (method) {
        return this.openEvent = method;
    }

    return HyphenIndexDb;
}]);<|endoftext|>


<commit_before>angular
  .module("animeHub")
  .config(MainRouter);

  MainRouter.$inject = ['$stateProvider', '$urlRouterProvider'];
  function MainRouter($stateProvider, $urlRouterProvider) {

    $stateProvider
      .state('home', {
        url: '/',
        templateUrl: "partials/home.html",
        controller: 'animesController as anime'
      })
      .state('login', {
        url: '/login',
        templateUrl: "partials/login.html"
      })
      .state('signup', {
        url: '/signup',
        templateUrl: "partials/signup.html"
      })
      .state('oneAnime', {
        url: '/anime/:animeId',
        templateUrl: "partials/oneAnime.html",
        controller: 'animesController as anime'
      });

    $urlRouterProvider.otherwise('/');
  }<commit_msg>profile route<commit_after>angular
  .module("animeHub")
  .config(MainRouter);

  MainRouter.$inject = ['$stateProvider', '$urlRouterProvider'];
  function MainRouter($stateProvider, $urlRouterProvider) {

    $stateProvider
      .state('home', {
        url: '/',
        templateUrl: "partials/home.html",
        controller: 'animesController as anime'
      })
      .state('login', {
        url: '/login',
        templateUrl: "partials/login.html"
      })
      .state('signup', {
        url: '/signup',
        templateUrl: "partials/signup.html"
      })
      .state('oneAnime', {
        url: '/anime/:animeId',
        templateUrl: "partials/oneAnime.html",
        controller: 'animesController as anime'
      })
      .state('profile', {
        url: '/profile',
        templateUrl: "partials/profile.html"
      })

    $urlRouterProvider.otherwise('/');
  }<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Box, Tabs, Tab } from 'grommet';
import { Map } from 'react-d3-map';
import { Table } from '../components';
import { deviceActions } from '../actions';

const mapConf = {
  width: 1400,
  height: 600,
  scale: 4000,
  scaleExtent: [1 << 12, 1 << 13],
  center: [111, 36]
};

class Device extends Component {
  componentDidMount() {
    this.props.actions.loadDevices();
  }

  render() {
    const { records } = this.props;
    return (
      <Box pad="small">
        <Tabs>
          <Tab title="Location">
            <Box size="large">
              <Map {...mapConf}/>
            </Box>

          </Tab>
          <Tab title="Model" />
          <Tab title="Customer" />
        </Tabs>
      </Box>
    );
  }
}

let mapStateToProps = (state) => {
  return {
    records: state.device.records
  };
};

let mapDispatchProps = (dispatch) => ({
  actions: bindActionCreators(deviceActions, dispatch)
});

export default connect(mapStateToProps, mapDispatchProps)(Device);
<commit_msg>Add MarkerGroup in Map by device geo info<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Box, Tabs, Tab } from 'grommet';
import { Map, MarkerGroup } from 'react-d3-map';
import { Table } from '../components';
import { deviceActions } from '../actions';

const mapConf = {
  width: 1400,
  height: 600,
  scale: 4000,
  scaleExtent: [1 << 12, 1 << 13],
  center: [111, 36]
};

class Device extends Component {
  componentDidMount() {
    this.props.actions.loadDevices();
  }

  renderMarkerGroup(records) {
    return records.map((record) => {
      var data = {
          "type": "Feature",
          "properties": {
            "text": record.name
          },
          "geometry": {
              "type": "Point",
              "coordinates": [record.longitude, record.latitude]
          }
      }
      return <MarkerGroup data={data}/>
    });
  }

  render() {
    const { records } = this.props;
    return (
      <Box pad="small">
        <Tabs>
          <Tab title="Location">
            <Box size="large">
              <Map {...mapConf}>
                { this.renderMarkerGroup(records) }
              </Map>
            </Box>

          </Tab>
          <Tab title="Model" />
          <Tab title="Customer" />
        </Tabs>
      </Box>
    );
  }
}

let mapStateToProps = (state) => {
  return {
    records: state.device.records
  };
};

let mapDispatchProps = (dispatch) => ({
  actions: bindActionCreators(deviceActions, dispatch)
});

export default connect(mapStateToProps, mapDispatchProps)(Device);
<|endoftext|>


<commit_before>'use strict'

angular.module('github-directives')
    .directive('ghCommits', function () {
        return {
            restrict: 'E',
            scope: {
                'user': '@',
                'repo': '@',
                'hideAvatar': '=',
                'hideDate': '=',
                'hideAuthor': '='
            },
            template:
                '
' +
                    '
{{ user }} / {{ repo }} / Commits
' +
                    '
' +
                        '' +
                            '' +
                            '{{ commit.commit.message }}' +
                            'By: {{ commit.commit.author.name }}' +
                            '{{ commit.commit.author.date | date:mediumDate }}' +
                        '' +
                    '
' +
                '
',
            controller: ['$scope', '$http', 'apiUrl', function($scope, $http, apiUrl) {
                $scope.createGravatarUrl = function (id) {// TODO extract as service
                    var size = 36;

                    if (id == null) {
                        id = '';
                    }

                    return 'http://gravatar.com/avatar/' + id + '?s=' + size;
                };

                $scope.commits = [];

                $scope.$watch('repo', function () {
                    if ($scope.user == undefined || $scope.repo == undefined) {
                        return;
                    }
                    $http({method: 'GET', url: apiUrl + '/repos/' + $scope.user + '/' + $scope.repo + '/commits'})
                        .success(function (data) {
                            $scope.commits = data;
                        });
                });
            }]
        };
    });

<commit_msg>Limit attribute added<commit_after>'use strict'

angular.module('github-directives')
    .directive('ghCommits', function () {
        return {
            restrict: 'E',
            scope: {
                'user': '@',
                'repo': '@',
                'hideAvatar': '=',
                'hideDate': '=',
                'hideAuthor': '=',
                'limit': '='
            },
            template:
                '
' +
                    '
{{ user }} / {{ repo }} / Commits
' +
                    '
' +
                        '' +
                            '' +
                            '{{ commit.commit.message }}' +
                            'By: {{ commit.commit.author.name }}' +
                            '{{ commit.commit.author.date | date:mediumDate }}' +
                        '' +
                    '
' +
                '
',
            controller: ['$scope', '$http', 'apiUrl', function($scope, $http, apiUrl) {
                $scope.createGravatarUrl = function (id) {// TODO extract as service
                    var size = 36;

                    if (id == null) {
                        id = '';
                    }

                    return 'http://gravatar.com/avatar/' + id + '?s=' + size;
                };

                $scope.commits = [];

                $scope.$watch('repo', function () {
                    if ($scope.user == undefined || $scope.repo == undefined) {
                        return;
                    }
                    $http({method: 'GET', url: apiUrl + '/repos/' + $scope.user + '/' + $scope.repo + '/commits'})
                        .success(function (data) {
                            if ($scope.limit == undefined) {
                                $scope.commits = data;
                            } else {
                                $scope.commits = data.splice(0,$scope.limit);
                            }
                        });
                });
            }]
        };
    });

<|endoftext|>


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

	app.model.Email = Backbone.Model.extend({

		defaults: {
			id: null,
			from: null,
			to: [],
			cc: [],
			bcc: [],
			subject: null,
			body: null,
			sentDate: null
		},

		initialize: function() {
			// decode body
			try {
				var decodedBody = window.atob(this.get('body'));
				this.set('body', decodedBody);
			} catch (ex) {
				console.log(ex);
			}
		}

	});

	app.model.EmailCollection = Backbone.Collection.extend({

		model: app.model.Email,

		findByName: function(key) {}

	});

}());<commit_msg>removed base64 decoding in email model<commit_after>(function() {
	'use strict';

	app.model.Email = Backbone.Model.extend({

		defaults: {
			id: null,
			from: null,
			to: [],
			cc: [],
			bcc: [],
			subject: null,
			body: null,
			sentDate: null
		},

		initialize: function() {}

	});

	app.model.EmailCollection = Backbone.Collection.extend({

		model: app.model.Email,

		findByName: function(key) {}

	});

}());<|endoftext|>


<commit_before>/**
 *
 * @author Andriy Oblivantsev <eslider@gmail.com>
 */
/**
 * Form helper plugin for jQuery
 *
 * @author Andriy Oblivantsev <eslider@gmail.com>
 * @copyright 02.02.2015 by WhereGroup GmbH & Co. KG
 *
 */
$.fn.formData = function(values) {
    var form = $(this);
    var inputs = $(':input', form).get();
    var hasNewValues = typeof values == 'object';
    var textElements = $(".form-group.text", form);

    if (hasNewValues) {

        $.each(textElements, function() {
            var textElementContainer = $(this);
            var textElement = $('.text', textElementContainer);
            var declaration = textElementContainer.data('item');
            if(declaration.hasOwnProperty('text')) {
                if (typeof declaration.text === 'function') {
                    textElement.html(declaration.text(values));
                } else {
                    var html = "";
                    try {
                        console.error("Using Javascript code in the configuration is deprecated",declaration.text);
                        var data = values;
                        eval('html=' + declaration.text + ';');
                    } catch (e) {
                        console.error("The defenition", declaration, " of ", textElement, ' is erroneous.', e);
                    }
                    textElement.html(html);
                }
            }
        });

        $.each(inputs, function() {
            var input = $(this);
            var value = values[this.name];
            var declaration = input.data('declaration');

            if(values.hasOwnProperty(this.name)) {

                switch (this.type) {
                    case 'select-multiple':
                        //var declaration = input.data('declaration');
                        var type = declaration.fieldType ? declaration.fieldType : 'text';

                        if(type == 'text' && value ) {
                            var separator = declaration.separator ? declaration.separator : ',';
                            var vals = $.isArray(value) ? value : value.split(separator);
                            $.each(vals, function(i, optionValue) {
                                $("option[value='" + optionValue + "']", input).prop("selected", true);
                            });
                            if(input.select2){
                                input.select2();
                            }
                        } else {
                            input.val(value);
                        }
                        break;

                    case 'checkbox':
                        input.prop('checked', value !== null && value);
                        break;
                    case 'radio':
                        if (value === null) {
                            input.prop('checked', false);
                        } else if (input.val() == value) {
                            input.prop("checked", true);
                        }
                        break;
                    case 'hidden':
                        input.val(value);
                        input.trigger('change');
                        break;

                    case 'text':
                        if(input.hasClass('hasDatepicker')) {
                            var dateFormat = input.datepicker("option", "dateFormat");

                            if(value === '' || value === 0 || value === '0') {
                                value = null;
                            }
                            // if(value !== null) {
                                // value = $.datepicker.formatDate(dateFormat, $.datepicker.parseDate(dateFormat, value))
                            // }

                            input.datepicker("setDate", value);
                            input.datepicker("refresh");
                        } else {
                            input.val(value);
                        }
                        break;
                    default:
                        input.val(value);
                }
                input.trigger('filled', {
                    data:   values,
                    value:  value
                });
                input.trigger("changeValue");

            }
        });
        return form;
    } else {
        values = {};
        var firstInput;
        $.each(inputs, function() {
            var input = $(this);
            var value;
            var declaration = input.data('declaration');

            if(this.name == ""){
                return;
            }

            switch (this.type) {
                case 'checkbox':
                case 'radio':
                    if(values.hasOwnProperty(this.name) && values[this.name] != null){
                        return;
                    }
                    value = input.is(':checked') ? input.val() : null;
                    break;
                default:
                    value = input.val();
            }

            if(value === ""){
                value = null;
            }

            if(values !== false && declaration){
                if(declaration.hasOwnProperty('mandatory') && declaration.mandatory ){
                    var isDataReady = false;
                    if(typeof declaration.mandatory === "function"){
                        isDataReady = declaration.mandatory(input, declaration, value);
                    } else{
                        isDataReady = input.data('warn')(value);
                    }
                    if(!isDataReady && !firstInput && input.is(":visible")){
                        firstInput = input;
                        input.focus();
                    }
                }
                values[this.name] = value;
            }else{
                values[this.name] = value;
            }

        });
        return values;
    }
};

$.fn.disableForm = function() {
    var form = this;
    var inputs = $(" :input", form);
    form.attr('readonly', true);
    form.css('cursor', 'wait');
    $.each(inputs, function(idx, el) {
        var $el = $(el);
        if($el.is(':checkbox') || $el.is(':radio') || $el.is('select')) {
            $el.attr('disabled', 'disabled');
        } else {
            $el.attr('readonly', 'true');
        }
    })
};

$.fn.enableForm = function() {
    var form = this;
    var inputs = $(" :input", form);
    form.css('cursor', '');
    $.each(inputs, function(idx, el) {
        var $el = $(el);
        if($el.is(':checkbox') || $el.is(':radio') || $el.is('select')) {
            $el.removeAttr('disabled', 'disabled');
        } else {
            $el.removeAttr('readonly', 'true');
        }
    })
};

<commit_msg>Fix select2 visual update<commit_after>/**
 *
 * @author Andriy Oblivantsev <eslider@gmail.com>
 */
/**
 * Form helper plugin for jQuery
 *
 * @author Andriy Oblivantsev <eslider@gmail.com>
 * @copyright 02.02.2015 by WhereGroup GmbH & Co. KG
 *
 */
$.fn.formData = function(values) {
    var form = $(this);
    var inputs = $(':input', form).get();
    var hasNewValues = typeof values == 'object';
    var textElements = $(".form-group.text", form);

    if (hasNewValues) {

        $.each(textElements, function() {
            var textElementContainer = $(this);
            var textElement = $('.text', textElementContainer);
            var declaration = textElementContainer.data('item');
            if(declaration.hasOwnProperty('text')) {
                if (typeof declaration.text === 'function') {
                    textElement.html(declaration.text(values));
                } else {
                    var html = "";
                    try {
                        console.error("Using Javascript code in the configuration is deprecated",declaration.text);
                        var data = values;
                        eval('html=' + declaration.text + ';');
                    } catch (e) {
                        console.error("The defenition", declaration, " of ", textElement, ' is erroneous.', e);
                    }
                    textElement.html(html);
                }
            }
        });

        $.each(inputs, function() {
            var input = $(this);
            var value = values[this.name];
            var declaration = input.data('declaration');

            if(values.hasOwnProperty(this.name)) {

                switch (this.type) {
                    case 'select-multiple':
                        var type = declaration.fieldType ? declaration.fieldType : 'text';

                        if(type == 'text' && value ) {
                            var separator = declaration.separator ? declaration.separator : ',';
                            input.val($.isArray(value) ? value : value.split(separator));
                        } else {
                            input.val(value);
                        }
                        input.trigger('change.select2');
                        break;
                    case 'checkbox':
                        input.prop('checked', value !== null && value);
                        break;
                    case 'radio':
                        if (value === null) {
                            input.prop('checked', false);
                        } else if (input.val() == value) {
                            input.prop("checked", true);
                        }
                        break;
                    case 'hidden':
                        input.val(value);
                        input.trigger('change');
                        break;

                    case 'text':
                        if(input.hasClass('hasDatepicker')) {
                            var dateFormat = input.datepicker("option", "dateFormat");

                            if(value === '' || value === 0 || value === '0') {
                                value = null;
                            }
                            // if(value !== null) {
                                // value = $.datepicker.formatDate(dateFormat, $.datepicker.parseDate(dateFormat, value))
                            // }

                            input.datepicker("setDate", value);
                            input.datepicker("refresh");
                        } else {
                            input.val(value);
                        }
                        break;
                    default:
                        input.val(value);
                        input.trigger('change.select2');
                        break;
                }
                input.trigger('filled', {
                    data:   values,
                    value:  value
                });
                input.trigger("changeValue");

            }
        });
        return form;
    } else {
        values = {};
        var firstInput;
        $.each(inputs, function() {
            var input = $(this);
            var value;
            var declaration = input.data('declaration');

            if(this.name == ""){
                return;
            }

            switch (this.type) {
                case 'checkbox':
                case 'radio':
                    if(values.hasOwnProperty(this.name) && values[this.name] != null){
                        return;
                    }
                    value = input.is(':checked') ? input.val() : null;
                    break;
                default:
                    value = input.val();
            }

            if(value === ""){
                value = null;
            }

            if(values !== false && declaration){
                if(declaration.hasOwnProperty('mandatory') && declaration.mandatory ){
                    var isDataReady = false;
                    if(typeof declaration.mandatory === "function"){
                        isDataReady = declaration.mandatory(input, declaration, value);
                    } else{
                        isDataReady = input.data('warn')(value);
                    }
                    if(!isDataReady && !firstInput && input.is(":visible")){
                        firstInput = input;
                        input.focus();
                    }
                }
                values[this.name] = value;
            }else{
                values[this.name] = value;
            }

        });
        return values;
    }
};

$.fn.disableForm = function() {
    var form = this;
    var inputs = $(" :input", form);
    form.attr('readonly', true);
    form.css('cursor', 'wait');
    $.each(inputs, function(idx, el) {
        var $el = $(el);
        if($el.is(':checkbox') || $el.is(':radio') || $el.is('select')) {
            $el.attr('disabled', 'disabled');
        } else {
            $el.attr('readonly', 'true');
        }
    })
};

$.fn.enableForm = function() {
    var form = this;
    var inputs = $(" :input", form);
    form.css('cursor', '');
    $.each(inputs, function(idx, el) {
        var $el = $(el);
        if($el.is(':checkbox') || $el.is(':radio') || $el.is('select')) {
            $el.removeAttr('disabled', 'disabled');
        } else {
            $el.removeAttr('readonly', 'true');
        }
    })
};

<|endoftext|>


<commit_before>import {Icon} from './Icon';
import {toPoint as point} from '../../geometry/Point';

/*
 * @class DivIcon
 * @aka L.DivIcon
 * @inherits Icon
 *
 * Represents a lightweight icon for markers that uses a simple `<div>`
 * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
 *
 * @example
 * ```js
 * var myIcon = L.divIcon({className: 'my-div-icon'});
 * // you can set .my-div-icon styles in CSS
 *
 * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
 * ```
 *
 * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
 */

export var DivIcon = Icon.extend({
	options: {
		// @section
		// @aka DivIcon options
		iconSize: [12, 12], // also can be set through CSS

		// iconAnchor: (Point),
		// popupAnchor: (Point),

		// @option html: String = ''
		// Custom HTML code to put inside the div element, empty by default.
		html: false,

		// @option bgPos: Point = [0, 0]
		// Optional relative position of the background, in pixels
		bgPos: null,

		className: 'leaflet-div-icon'
	},

	createIcon: function (oldIcon) {
		var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
		    options = this.options;

		div.innerHTML = options.html !== false ? options.html : '';

		if (options.bgPos) {
			var bgPos = point(options.bgPos);
			div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
		}
		this._setIconStyles(div, 'icon');

		return div;
	},

	createShadow: function () {
		return null;
	}
});

// @factory L.divIcon(options: DivIcon options)
// Creates a `DivIcon` instance with the given options.
export function divIcon(options) {
	return new DivIcon(options);
}
<commit_msg>Make DivIcon html option accept HTMLElement (#6571)<commit_after>import {Icon} from './Icon';
import {toPoint as point} from '../../geometry/Point';
import {empty} from '../../dom/DomUtil';

/*
 * @class DivIcon
 * @aka L.DivIcon
 * @inherits Icon
 *
 * Represents a lightweight icon for markers that uses a simple `<div>`
 * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
 *
 * @example
 * ```js
 * var myIcon = L.divIcon({className: 'my-div-icon'});
 * // you can set .my-div-icon styles in CSS
 *
 * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
 * ```
 *
 * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
 */

export var DivIcon = Icon.extend({
	options: {
		// @section
		// @aka DivIcon options
		iconSize: [12, 12], // also can be set through CSS

		// iconAnchor: (Point),
		// popupAnchor: (Point),

		// @option html: String|HTMLElement = ''
		// Custom HTML code to put inside the div element, empty by default. Alternatively,
		// an instance of `HTMLElement`.
		html: false,

		// @option bgPos: Point = [0, 0]
		// Optional relative position of the background, in pixels
		bgPos: null,

		className: 'leaflet-div-icon'
	},

	createIcon: function (oldIcon) {
		var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
		    options = this.options;

		if (options.html instanceof Element) {
			empty(div);
			div.appendChild(options.html);
		} else {
			div.innerHTML = options.html !== false ? options.html : '';
		}

		if (options.bgPos) {
			var bgPos = point(options.bgPos);
			div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
		}
		this._setIconStyles(div, 'icon');

		return div;
	},

	createShadow: function () {
		return null;
	}
});

// @factory L.divIcon(options: DivIcon options)
// Creates a `DivIcon` instance with the given options.
export function divIcon(options) {
	return new DivIcon(options);
}
<|endoftext|>