<commit_before>/**
 * @author Russell Toris - rctoris@wpi.edu
 */

/**
 * A OccupancyGridClientNav uses an OccupancyGridClient to create a map for use with a Navigator.
 *
 * @constructor
 * @param options - object with following keys:
 *   * ros - the ROSLIB.Ros connection handle
 *   * topic (optional) - the map topic to listen to
 *   * rootObject (optional) - the root object to add this marker to
 *   * continuous (optional) - if the map should be continuously loaded (e.g., for SLAM)
 *   * serverName (optional) - the action server name to use for navigation, like '/move_base'
 *   * actionName (optional) - the navigation action name, like 'move_base_msgs/MoveBaseAction'
 *   * rootObject (optional) - the root object to add the click listeners to and render robot markers to
 *   * withOrientation (optional) - if the Navigator should consider the robot orientation (default: false)
 *   * viewer - the main viewer to render to
 */
NAV2D.OccupancyGridClientNav = function(options) {
  var that = this;
  options = options || {};
  this.ros = options.ros;
  var topic = options.topic || '/map';
  var continuous = options.continuous;
  this.serverName = options.serverName || '/move_base';
  this.actionName = options.actionName || 'move_base_msgs/MoveBaseAction';
  this.rootObject = options.rootObject || new createjs.Container();
  this.viewer = options.viewer;
  this.withOrientation = options.withOrientation || false;

  this.navigator = null;

  // setup a client to get the map
  var client = new ROS2D.OccupancyGridClient({
    ros : this.ros,
    rootObject : this.rootObject,
    continuous : continuous,
    topic : topic
  });
  client.on('change', function() {
    that.navigator = new NAV2D.Navigator({
      ros : that.ros,
      serverName : that.serverName,
      actionName : that.actionName,
      rootObject : that.rootObject,
      withOrientation : that.withOrientation
    });

    // scale the viewer to fit the map
    that.viewer.scaleToDimensions(client.currentGrid.width, client.currentGrid.height);
    that.viewer.shift(client.currentGrid.pose.position.x, client.currentGrid.pose.position.y);
  });
};
<commit_msg>Update OccupancyGridClientNav.js<commit_after>/**
 * @author Russell Toris - rctoris@wpi.edu
 */

/**
 * A OccupancyGridClientNav uses an OccupancyGridClient to create a map for use with a Navigator.
 *
 * @constructor
 * @param options - object with following keys:
 *   * ros - the ROSLIB.Ros connection handle
 *   * tfClient (optional) - Read information from TF
 *   * topic (optional) - the map topic to listen to
 *   * robot_pose (optional) - the robot topic or TF to listen position
 *   * rootObject (optional) - the root object to add this marker to
 *   * continuous (optional) - if the map should be continuously loaded (e.g., for SLAM)
 *   * serverName (optional) - the action server name to use for navigation, like '/move_base'
 *   * actionName (optional) - the navigation action name, like 'move_base_msgs/MoveBaseAction'
 *   * rootObject (optional) - the root object to add the click listeners to and render robot markers to
 *   * withOrientation (optional) - if the Navigator should consider the robot orientation (default: false)
 *   * viewer - the main viewer to render to
 */
NAV2D.OccupancyGridClientNav = function(options) {
  var that = this;
  options = options || {};
  this.ros = options.ros;
	this.tfClient = options.tfClient || null;
  var map_topic = options.topic || '/map';
  this.robot_pose = options.robot_pose || '/robot_pose';
  var continuous = options.continuous;
  this.serverName = options.serverName || '/move_base';
  this.actionName = options.actionName || 'move_base_msgs/MoveBaseAction';
  this.rootObject = options.rootObject || new createjs.Container();
  this.viewer = options.viewer;
  this.withOrientation = options.withOrientation || false;

  this.navigator = null;

  // setup a client to get the map
  var client = new ROS2D.OccupancyGridClient({
    ros : this.ros,
    rootObject : this.rootObject,
    continuous : continuous,
    topic : map_topic
  });
  client.on('change', function() {
    that.navigator = new NAV2D.Navigator({
      ros : that.ros,
      tfClient: that.tfClient,
      serverName : that.serverName,
      actionName : that.actionName,
      robot_pose : that.robot_pose,
      rootObject : that.rootObject,
      withOrientation : that.withOrientation
    });

    // scale the viewer to fit the map
    that.viewer.scaleToDimensions(client.currentGrid.width, client.currentGrid.height);
    that.viewer.shift(client.currentGrid.pose.position.x, client.currentGrid.pose.position.y);
  });
};
<|endoftext|>


<commit_before>var path = require('path');
var eejs = require('ep_etherpad-lite/node/eejs');
var installer = require('ep_etherpad-lite/static/js/pluginfw/installer');
var fs = require('fs');

exports.expressCreateServer = function (hook_name, args, cb) {
  args.app.get('/admin/settings', function(req, res) {

    var render_args = {
      settings: "",
      search_results: {},
      errors: []
    };

    res.send( eejs.require("ep_etherpad-lite/templates/admin/settings.html", render_args) );

  });
}

exports.socketio = function (hook_name, args, cb) {
  var io = args.io.of("/settings");
  io.on('connection', function (socket) {
    if (!socket.handshake.session.user || !socket.handshake.session.user.is_admin) return;

    socket.on("load", function (query) {
//      socket.emit("installed-results", {results: plugins.plugins});
      fs.readFile('settings.json', 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        else
        {
          socket.emit("settings", {results: data});
        }
      });
    });

/*
    socket.on("search", function (query) {
      socket.emit("progress", {progress:0, message:'Fetching results...'});
        installer.search(query, true, function (progress) {
        if (progress.results)
          socket.emit("search-result", progress);
        socket.emit("progress", progress);
      });
    });

    socket.on("install", function (plugin_name) {
      socket.emit("progress", {progress:0, message:'Downloading and installing ' + plugin_name + "..."});
      installer.install(plugin_name, function (progress) {
        socket.emit("progress", progress);
      });
    });

    socket.on("uninstall", function (plugin_name) {
      socket.emit("progress", {progress:0, message:'Uninstalling ' + plugin_name + "..."});
      installer.uninstall(plugin_name, function (progress) {
        socket.emit("progress", progress);
      });
    });
*/
  });
}
<commit_msg>make the server save settings<commit_after>var path = require('path');
var eejs = require('ep_etherpad-lite/node/eejs');
var installer = require('ep_etherpad-lite/static/js/pluginfw/installer');
var fs = require('fs');

exports.expressCreateServer = function (hook_name, args, cb) {
  args.app.get('/admin/settings', function(req, res) {

    var render_args = {
      settings: "",
      search_results: {},
      errors: []
    };

    res.send( eejs.require("ep_etherpad-lite/templates/admin/settings.html", render_args) );

  });
}

exports.socketio = function (hook_name, args, cb) {
  var io = args.io.of("/settings");
  io.on('connection', function (socket) {
    if (!socket.handshake.session.user || !socket.handshake.session.user.is_admin) return;

    socket.on("load", function (query) {
      fs.readFile('settings.json', 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        else
        {
          socket.emit("settings", {results: data});
        }
      });
    });

    socket.on("saveSettings", function (settings) {
      fs.writeFile('settings.json', settings, function (err) {
        if (err) throw err;
        socket.emit("saveprogress", "saved");
      });
    });

/*
    socket.on("install", function (plugin_name) {
      socket.emit("progress", {progress:0, message:'Downloading and installing ' + plugin_name + "..."});
      installer.install(plugin_name, function (progress) {
        socket.emit("progress", progress);
      });
    });

    socket.on("uninstall", function (plugin_name) {
      socket.emit("progress", {progress:0, message:'Uninstalling ' + plugin_name + "..."});
      installer.uninstall(plugin_name, function (progress) {
        socket.emit("progress", progress);
      });
    });
*/
  });
}
<|endoftext|>


<commit_before>// @flow

const localStorage = window.localStorage || {};

export const AUTH =
  localStorage.REACT_APP_GDC_AUTH || process.env.REACT_APP_GDC_AUTH || '';
export const AUTH_API = `${AUTH}/api`;
export const API = localStorage.REACT_APP_API || process.env.REACT_APP_API;

export const DATA_CATEGORIES = {
  SEQ: { full: 'Raw Sequencing Data', abbr: 'Seq' },
  EXP: { full: 'Transcriptome Profiling', abbr: 'Exp' },
  SNV: { full: 'Simple Nucleotide Variation', abbr: 'SNV' },
  CNV: { full: 'Copy Number Variation', abbr: 'CNV' },
  METH: { full: 'DNA Methylation', abbr: 'Meth' },
  CLINICAL: { full: 'Clinical', abbr: 'Clinical' },
  BIOSPECIMEN: { full: 'Biospecimen', abbr: 'Bio' },
};

export const DATA_TYPES = {
  GEQ: { full: 'Gene Expression Quantification', abbr: 'GEQ' },
};

export const EXPERIMENTAL_STRATEGIES = [
  'Genotyping Array',
  'Gene Expression Array',
  'Exon Array',
  'miRNA Expression Array',
  'Methylation Array',
  'CGH Array',
  'MSI-Mono-Dinucleotide Assay',
  'WGS',
  'WGA',
  'WXS',
  'RNA-Seq',
  'miRNA-Seq',
  'ncRNA-Seq',
  'WCS',
  'CLONE',
  'POOLCLONE',
  'AMPLICON',
  'CLONEEND',
  'FINISHING',
  'ChIP-Seq',
  'MNase-Seq',
  'DNase-Hypersensitivity',
  'Bisulfite-Seq',
  'EST',
  'FL-cDNA',
  'CTS',
  'MRE-Seq',
  'MeDIP-Seq',
  'MBD-Seq',
  'Tn-Seq',
  'FAIRE-seq',
  'SELEX',
  'RIP-Seq',
  'ChIA-PET',
  'DNA-Seq',
  'Total RNA-Seq',
  'VALIDATION',
  'OTHER',
  'Targeted Sequencing',
].map(n => n.toLowerCase());

export const MUTATION_SUBTYPE_MAP = {
  'single base substitution': 'Substitution',
  'small deletion': 'Deletion',
  'small insertion': 'Insertion',
};

export const DNA_CHANGE_MARKERS = ['del', 'ins', '>'];

export const HUMAN_BODY_SITES_MAP = {
  Bladder: 'Bladder',
  Breast: 'Breast',
  Esophagus: 'Esophagus',
  'Other And Ill-Defined Sites': 'Other And Ill-Defined Sites',
  'Other And Unspecified Major Salivary Glands': 'Head and Neck',
  Kidney: 'Kidney',
  'Not Reported': 'Not Reported',
  Unknown: 'Not Reported',
  Ovary: 'Ovary',
  Pancreas: 'Pancreas',
  Thymus: 'Thymus',
  'Thyroid Gland': 'Thyroid',
  'Bronchus And Lung': 'Lung',
  Nasopharynx: 'Head and Neck',
  'Prostate Gland': 'Prostate',
  'Anus And Anal Canal': 'Other And Ill-Defined Sites',
  'Cervix Uteri': 'Cervix',
  Penis: 'Other And Ill-Defined Sites',
  Rectum: 'Colorectal',
  Skin: 'Skin',
  Vagina: 'Other And Ill-Defined Sites',
  Vulva: 'Other And Ill-Defined Sites',
  Ureter: 'Other And Ill-Defined Sites',
  Colon: 'Colorectal',
  'Other And Unspecified Parts Of Biliary Tract': 'Bile Duct',
  Hypopharynx: 'Head and Neck',
  'Small Intestine': 'Other And Ill-Defined Sites',
  'Other An Unspecified Female Genital Organs': 'Other And Ill-Defined Sites',
  Gallbladder: 'Other And Ill-Defined Sites',
  'Retroperitoneum And Peritoneum': 'Other And Ill-Defined Sites',
  Stomach: 'Stomach',
  Uterus: 'Uterus',
  'Uterus, NOS': 'Uterus',
  'Liver And Intrahepatic Bile Ducts': 'Liver',
  Trachea: 'Head and Neck',
  'Other Endocrine Glands And Related Structures':
    'Other And Ill-Defined Sites',
  'Adrenal Gland': 'Adrenal Gland',
  'Eye And Adnexa': 'Eye',
  'Other And Ill-Defined Digestive Organs': 'Other And Ill-Defined Sites',
  'Heart, Mediastinum, And Pleura': 'Pleura',
  Testis: 'Testis',
  'Spinal Cord, Cranial Nerves, And Other Parts Of Central Nervous System':
    'Nervous System',
  'Peripheral Nerves And Autonomic Nervous System':
    'Other And Ill-Defined Sites',
  'Other And Unspecified Urinary Organs': 'Other And Ill-Defined Sites',
};

export const HUMAN_BODY_ALL_ALLOWED_SITES = [
  'Adrenal Gland',
  'Bile Duct',
  'Bladder',
  'Blood',
  'Bone',
  'Bone Marrow',
  'Brain',
  'Breast',
  'Cervix',
  'Colorectal',
  'Esophagus',
  'Eye',
  'Head and Neck',
  'Kidney',
  'Liver',
  'Lung',
  'Lymph Nodes',
  'Nervous System',
  'Ovary',
  'Pancreas',
  'Pleura',
  'Prostate',
  'Skin',
  'Soft Tissue',
  'Stomach',
  'Testis',
  'Thymus',
  'Thyroid',
  'Uterus',
];
<commit_msg>dont append /api to AUTH_API from localstorage (#2084)<commit_after>// @flow

const localStorage = window.localStorage || {};

export const AUTH =
  localStorage.REACT_APP_GDC_AUTH || process.env.REACT_APP_GDC_AUTH || '';
export const AUTH_API = localStorage.REACT_APP_GDC_AUTH_API || `${AUTH}/api`;
export const API = localStorage.REACT_APP_API || process.env.REACT_APP_API;

export const DATA_CATEGORIES = {
  SEQ: { full: 'Raw Sequencing Data', abbr: 'Seq' },
  EXP: { full: 'Transcriptome Profiling', abbr: 'Exp' },
  SNV: { full: 'Simple Nucleotide Variation', abbr: 'SNV' },
  CNV: { full: 'Copy Number Variation', abbr: 'CNV' },
  METH: { full: 'DNA Methylation', abbr: 'Meth' },
  CLINICAL: { full: 'Clinical', abbr: 'Clinical' },
  BIOSPECIMEN: { full: 'Biospecimen', abbr: 'Bio' },
};

export const DATA_TYPES = {
  GEQ: { full: 'Gene Expression Quantification', abbr: 'GEQ' },
};

export const EXPERIMENTAL_STRATEGIES = [
  'Genotyping Array',
  'Gene Expression Array',
  'Exon Array',
  'miRNA Expression Array',
  'Methylation Array',
  'CGH Array',
  'MSI-Mono-Dinucleotide Assay',
  'WGS',
  'WGA',
  'WXS',
  'RNA-Seq',
  'miRNA-Seq',
  'ncRNA-Seq',
  'WCS',
  'CLONE',
  'POOLCLONE',
  'AMPLICON',
  'CLONEEND',
  'FINISHING',
  'ChIP-Seq',
  'MNase-Seq',
  'DNase-Hypersensitivity',
  'Bisulfite-Seq',
  'EST',
  'FL-cDNA',
  'CTS',
  'MRE-Seq',
  'MeDIP-Seq',
  'MBD-Seq',
  'Tn-Seq',
  'FAIRE-seq',
  'SELEX',
  'RIP-Seq',
  'ChIA-PET',
  'DNA-Seq',
  'Total RNA-Seq',
  'VALIDATION',
  'OTHER',
  'Targeted Sequencing',
].map(n => n.toLowerCase());

export const MUTATION_SUBTYPE_MAP = {
  'single base substitution': 'Substitution',
  'small deletion': 'Deletion',
  'small insertion': 'Insertion',
};

export const DNA_CHANGE_MARKERS = ['del', 'ins', '>'];

export const HUMAN_BODY_SITES_MAP = {
  Bladder: 'Bladder',
  Breast: 'Breast',
  Esophagus: 'Esophagus',
  'Other And Ill-Defined Sites': 'Other And Ill-Defined Sites',
  'Other And Unspecified Major Salivary Glands': 'Head and Neck',
  Kidney: 'Kidney',
  'Not Reported': 'Not Reported',
  Unknown: 'Not Reported',
  Ovary: 'Ovary',
  Pancreas: 'Pancreas',
  Thymus: 'Thymus',
  'Thyroid Gland': 'Thyroid',
  'Bronchus And Lung': 'Lung',
  Nasopharynx: 'Head and Neck',
  'Prostate Gland': 'Prostate',
  'Anus And Anal Canal': 'Other And Ill-Defined Sites',
  'Cervix Uteri': 'Cervix',
  Penis: 'Other And Ill-Defined Sites',
  Rectum: 'Colorectal',
  Skin: 'Skin',
  Vagina: 'Other And Ill-Defined Sites',
  Vulva: 'Other And Ill-Defined Sites',
  Ureter: 'Other And Ill-Defined Sites',
  Colon: 'Colorectal',
  'Other And Unspecified Parts Of Biliary Tract': 'Bile Duct',
  Hypopharynx: 'Head and Neck',
  'Small Intestine': 'Other And Ill-Defined Sites',
  'Other An Unspecified Female Genital Organs': 'Other And Ill-Defined Sites',
  Gallbladder: 'Other And Ill-Defined Sites',
  'Retroperitoneum And Peritoneum': 'Other And Ill-Defined Sites',
  Stomach: 'Stomach',
  Uterus: 'Uterus',
  'Uterus, NOS': 'Uterus',
  'Liver And Intrahepatic Bile Ducts': 'Liver',
  Trachea: 'Head and Neck',
  'Other Endocrine Glands And Related Structures':
    'Other And Ill-Defined Sites',
  'Adrenal Gland': 'Adrenal Gland',
  'Eye And Adnexa': 'Eye',
  'Other And Ill-Defined Digestive Organs': 'Other And Ill-Defined Sites',
  'Heart, Mediastinum, And Pleura': 'Pleura',
  Testis: 'Testis',
  'Spinal Cord, Cranial Nerves, And Other Parts Of Central Nervous System':
    'Nervous System',
  'Peripheral Nerves And Autonomic Nervous System':
    'Other And Ill-Defined Sites',
  'Other And Unspecified Urinary Organs': 'Other And Ill-Defined Sites',
};

export const HUMAN_BODY_ALL_ALLOWED_SITES = [
  'Adrenal Gland',
  'Bile Duct',
  'Bladder',
  'Blood',
  'Bone',
  'Bone Marrow',
  'Brain',
  'Breast',
  'Cervix',
  'Colorectal',
  'Esophagus',
  'Eye',
  'Head and Neck',
  'Kidney',
  'Liver',
  'Lung',
  'Lymph Nodes',
  'Nervous System',
  'Ovary',
  'Pancreas',
  'Pleura',
  'Prostate',
  'Skin',
  'Soft Tissue',
  'Stomach',
  'Testis',
  'Thymus',
  'Thyroid',
  'Uterus',
];
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */
import { UIDatabase, createRecord } from '../../database';
import { parsePositiveInteger } from '../../utilities';
import Settings from '../../settings/MobileAppSettings';
import { SETTINGS_KEYS } from '../../settings/index';

import { MODAL_KEYS } from '../../utilities/getModalTitle';

const { STOCKTAKE_OUTDATED_ITEM, EDIT_STOCKTAKE_BATCH, STOCKTAKE_COMMENT_EDIT } = MODAL_KEYS;

/**
 * Actions for use with a data table reducer
 */

export const editField = rowKey => ({ type: 'editField', rowKey });

export const editTotalQuantity = (value, rowKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.setTotalQuantity(UIDatabase, parsePositiveInteger(value));
    UIDatabase.save('TransactionItem', objectToEdit);
  });

  dispatch(editField(rowKey));
};

export const focusCell = (rowKey, columnKey) => ({
  type: 'focusCell',
  rowKey,
  columnKey,
});

export const focusNext = (rowKey, columnKey) => ({
  type: 'focusNextCell',
  rowKey,
  columnKey,
});

export const selectRow = rowKey => ({
  type: 'selectRow',
  rowKey,
});

export const deselectRow = rowKey => ({
  type: 'deselectRow',
  rowKey,
});

export const deselectAll = () => ({
  type: 'deselectAll',
});

export const sortData = (sortBy, isAscending) => ({
  type: 'sortData',
  sortBy,
  isAscending,
});

export const filterData = searchTerm => ({
  type: 'filterData',
  searchTerm,
});

export const openBasicModal = modalKey => ({
  type: 'openBasicModal',
  modalKey,
});

export const closeBasicModal = () => ({
  type: 'closeBasicModal',
});

export const addMasterListItems = objectType => (dispatch, getState) => {
  const { pageObject } = getState();

  const thisStore = UIDatabase.objects('Name').filtered(
    'id == $0',
    Settings.get(SETTINGS_KEYS.THIS_STORE_NAME_ID)
  )[0];

  UIDatabase.write(() => {
    pageObject.addItemsFromMasterList(UIDatabase, thisStore);
    UIDatabase.save(objectType, pageObject);
  });
  dispatch({ type: 'addMasterListItems', objectType });
};

export const addItem = (item, addedItemType) => (dispatch, getState) => {
  const { pageObject } = getState();
  let addedItem;

  UIDatabase.write(() => {
    if (pageObject.hasItem(item)) return;
    addedItem = createRecord(UIDatabase, addedItemType, pageObject, item);
  });

  if (addedItem) dispatch({ type: 'addItem', item: addedItem });
  else dispatch(closeBasicModal());
};

export const editTheirRef = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();

  const { theirRef } = pageObject;

  if (theirRef !== value) {
    UIDatabase.write(() => {
      UIDatabase.update(pageObjectType, {
        ...pageObject,
        theirRef: value,
      });
    });
  }

  dispatch(closeBasicModal());
};

export const editComment = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();
  const { comment } = pageObject;

  if (comment !== value) {
    UIDatabase.write(() => {
      UIDatabase.update(pageObjectType, {
        ...pageObject,
        comment: value,
      });
    });
  }

  dispatch(closeBasicModal());
};

export const deleteItemsById = pageObjectType => (dispatch, getState) => {
  const { dataState, pageObject } = getState();

  const itemsIds = Array.from(dataState.keys()).filter(rowKey => dataState.get(rowKey).isSelected);

  UIDatabase.write(() => {
    pageObject.removeItemsById(UIDatabase, itemsIds);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'deleteRecordsById' });
};

export const deleteTransactionsById = () => (dispatch, getState) => {
  const { dataState, backingData } = getState();

  const transactionIds = Array.from(dataState.keys()).filter(
    rowKey => dataState.get(rowKey).isSelected
  );

  const transactionsToDelete = transactionIds.reduce((acc, transactionId) => {
    const transaction = backingData.filtered('id = $0', transactionId)[0];
    const shouldDelete = transaction && transaction.isValid() && !transaction.isFinalised;
    if (shouldDelete) return [...acc, transaction];
    return acc;
  }, []);

  UIDatabase.write(() => {
    UIDatabase.delete('Transaction', transactionsToDelete);
  });

  dispatch({ type: 'deleteRecordsById' });
};

export const refreshData = () => ({
  type: 'refreshData',
});

export const editTransactionBatchExpiryDate = (newDate, rowKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.expiryDate = newDate;
    UIDatabase.save('TransactionBatch', objectToEdit);
  });

  dispatch(editField(rowKey));
};

export const editTransactionBatchQuantity = (value, rowKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  if (!value) return;

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.setTotalQuantity(UIDatabase, parsePositiveInteger(Number(value)));
    UIDatabase.save('TransactionBatch', objectToEdit);
  });

  dispatch(editField(rowKey));
};

export const deleteTransactionBatchesById = pageObjectType => (dispatch, getState) => {
  const { dataState, pageObject } = getState();

  const itemsIds = Array.from(dataState.keys()).filter(rowKey => dataState.get(rowKey).isSelected);

  UIDatabase.write(() => {
    pageObject.removeTransactionBatchesById(UIDatabase, itemsIds);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'deleteRecordsById' });
};

export const deleteRequisitions = () => (dispatch, getState) => {
  const { dataState, backingData } = getState();

  const requisitionIds = Array.from(dataState.keys()).filter(
    rowKey => dataState.get(rowKey).isSelected
  );

  const requisitionsToDelete = requisitionIds.reduce((acc, requisitionId) => {
    const requisition = backingData.filtered('id = $0', requisitionId)[0];
    const shouldDelete = requisition && requisition.isValid() && !requisition.isFinalised;
    if (shouldDelete) return [...acc, requisition];
    return acc;
  }, []);

  UIDatabase.write(() => {
    UIDatabase.delete('Requisition', requisitionsToDelete);
  });

  dispatch({ type: 'deleteRecordsById' });
};

export const addTransactionBatch = item => (dispatch, getState) => {
  const { pageObject } = getState();
  let addedTransactionBatch;

  UIDatabase.write(() => {
    const transItem = createRecord(UIDatabase, 'TransactionItem', pageObject, item);
    const itemBatch = createRecord(UIDatabase, 'ItemBatch', item, '');
    addedTransactionBatch = createRecord(UIDatabase, 'TransactionBatch', transItem, itemBatch);
  });

  if (addedTransactionBatch) dispatch({ type: 'addItem', item: addedTransactionBatch });
  else dispatch(closeBasicModal());
};

export const createAutomaticOrder = pageObjectType => (dispatch, getState) => {
  const { pageObject } = getState();

  const thisStore = UIDatabase.objects('Name').filtered(
    'id == $0',
    Settings.get(SETTINGS_KEYS.THIS_STORE_NAME_ID)
  )[0];

  UIDatabase.write(() => {
    pageObject.createAutomaticOrder(UIDatabase, thisStore);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'createAutomaticOrder' });
};

export const useSuggestedQuantities = pageObjectType => (dispatch, getState) => {
  const { pageObject } = getState();

  UIDatabase.write(() => {
    pageObject.setRequestedToSuggested(UIDatabase);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'refreshData' });
};

export const hideOverStocked = () => ({
  type: 'hideOverStocked',
});

export const showOverStocked = () => ({
  type: 'showOverStocked',
});

export const editMonthsOfSupply = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();
  const { monthsToSupply } = pageObject;

  if (monthsToSupply !== value) {
    UIDatabase.write(() => {
      pageObject.monthsToSupply = value;
      UIDatabase.save(pageObjectType, pageObject);
    });
  }

  dispatch(closeBasicModal());
};

export const editRequiredQuantity = (value, rowKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.requiredQuantity = parsePositiveInteger(Number(value));
    UIDatabase.save('RequisitionItem', objectToEdit);
  });

  dispatch(editField(rowKey));
};

export const selectAll = () => ({
  type: 'selectAll',
});

export const hideStockOut = () => ({
  type: 'hideStockOut',
});

export const showStockOut = () => ({
  type: 'showStockOut',
});

export const selectItems = items => ({
  type: 'selectItems',
  items,
});

export const editName = value => ({
  type: 'editName',
  value,
});

export const editCountedTotalQuantity = (value, rowKey, columnKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  objectToEdit.setCountedTotalQuantity(UIDatabase, parsePositiveInteger(Number(value)));

  dispatch({
    type: 'editCountedTotalQuantity',
    value,
    rowKey,
    columnKey,
  });
};

export const openStocktakeBatchModal = (rowKey, columnKey) => ({
  type: 'openStocktakeBatchModal',
  rowKey,
  columnKey,
});

export const closeStocktakeBatchModal = () => ({
  type: 'closeStocktakeBatchModal',
});

export const openModal = (modalKey, value) => {
  switch (modalKey) {
    case EDIT_STOCKTAKE_BATCH:
      return { type: 'openStocktakeBatchModal', rowKey: value };
    case STOCKTAKE_COMMENT_EDIT:
      return { type: 'openCommentModal' };
    case STOCKTAKE_OUTDATED_ITEM:
      return { type: 'openStocktakeOutdatedItems' };
    default:
      return { type: 'openBasicModal', modalKey };
  }
};
<commit_msg>Add reset stocktake action<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */
import { UIDatabase, createRecord } from '../../database';
import { parsePositiveInteger } from '../../utilities';
import Settings from '../../settings/MobileAppSettings';
import { SETTINGS_KEYS } from '../../settings/index';

import { MODAL_KEYS } from '../../utilities/getModalTitle';

const { STOCKTAKE_OUTDATED_ITEM, EDIT_STOCKTAKE_BATCH, STOCKTAKE_COMMENT_EDIT } = MODAL_KEYS;

/**
 * Actions for use with a data table reducer
 */

export const editField = rowKey => ({ type: 'editField', rowKey });

export const editTotalQuantity = (value, rowKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.setTotalQuantity(UIDatabase, parsePositiveInteger(value));
    UIDatabase.save('TransactionItem', objectToEdit);
  });

  dispatch(editField(rowKey));
};

export const focusCell = (rowKey, columnKey) => ({
  type: 'focusCell',
  rowKey,
  columnKey,
});

export const focusNext = (rowKey, columnKey) => ({
  type: 'focusNextCell',
  rowKey,
  columnKey,
});

export const selectRow = rowKey => ({
  type: 'selectRow',
  rowKey,
});

export const deselectRow = rowKey => ({
  type: 'deselectRow',
  rowKey,
});

export const deselectAll = () => ({
  type: 'deselectAll',
});

export const sortData = (sortBy, isAscending) => ({
  type: 'sortData',
  sortBy,
  isAscending,
});

export const filterData = searchTerm => ({
  type: 'filterData',
  searchTerm,
});

export const openBasicModal = modalKey => ({
  type: 'openBasicModal',
  modalKey,
});

export const closeBasicModal = () => ({
  type: 'closeBasicModal',
});

export const addMasterListItems = objectType => (dispatch, getState) => {
  const { pageObject } = getState();

  const thisStore = UIDatabase.objects('Name').filtered(
    'id == $0',
    Settings.get(SETTINGS_KEYS.THIS_STORE_NAME_ID)
  )[0];

  UIDatabase.write(() => {
    pageObject.addItemsFromMasterList(UIDatabase, thisStore);
    UIDatabase.save(objectType, pageObject);
  });
  dispatch({ type: 'addMasterListItems', objectType });
};

export const addItem = (item, addedItemType) => (dispatch, getState) => {
  const { pageObject } = getState();
  let addedItem;

  UIDatabase.write(() => {
    if (pageObject.hasItem(item)) return;
    addedItem = createRecord(UIDatabase, addedItemType, pageObject, item);
  });

  if (addedItem) dispatch({ type: 'addItem', item: addedItem });
  else dispatch(closeBasicModal());
};

export const editTheirRef = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();

  const { theirRef } = pageObject;

  if (theirRef !== value) {
    UIDatabase.write(() => {
      UIDatabase.update(pageObjectType, {
        ...pageObject,
        theirRef: value,
      });
    });
  }

  dispatch(closeBasicModal());
};

export const editComment = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();
  const { comment } = pageObject;

  if (comment !== value) {
    UIDatabase.write(() => {
      UIDatabase.update(pageObjectType, {
        ...pageObject,
        comment: value,
      });
    });
  }

  dispatch(closeBasicModal());
};

export const deleteItemsById = pageObjectType => (dispatch, getState) => {
  const { dataState, pageObject } = getState();

  const itemsIds = Array.from(dataState.keys()).filter(rowKey => dataState.get(rowKey).isSelected);

  UIDatabase.write(() => {
    pageObject.removeItemsById(UIDatabase, itemsIds);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'deleteRecordsById' });
};

export const deleteTransactionsById = () => (dispatch, getState) => {
  const { dataState, backingData } = getState();

  const transactionIds = Array.from(dataState.keys()).filter(
    rowKey => dataState.get(rowKey).isSelected
  );

  const transactionsToDelete = transactionIds.reduce((acc, transactionId) => {
    const transaction = backingData.filtered('id = $0', transactionId)[0];
    const shouldDelete = transaction && transaction.isValid() && !transaction.isFinalised;
    if (shouldDelete) return [...acc, transaction];
    return acc;
  }, []);

  UIDatabase.write(() => {
    UIDatabase.delete('Transaction', transactionsToDelete);
  });

  dispatch({ type: 'deleteRecordsById' });
};

export const refreshData = () => ({
  type: 'refreshData',
});

export const editTransactionBatchExpiryDate = (newDate, rowKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.expiryDate = newDate;
    UIDatabase.save('TransactionBatch', objectToEdit);
  });

  dispatch(editField(rowKey));
};

export const editTransactionBatchQuantity = (value, rowKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  if (!value) return;

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.setTotalQuantity(UIDatabase, parsePositiveInteger(Number(value)));
    UIDatabase.save('TransactionBatch', objectToEdit);
  });

  dispatch(editField(rowKey));
};

export const deleteTransactionBatchesById = pageObjectType => (dispatch, getState) => {
  const { dataState, pageObject } = getState();

  const itemsIds = Array.from(dataState.keys()).filter(rowKey => dataState.get(rowKey).isSelected);

  UIDatabase.write(() => {
    pageObject.removeTransactionBatchesById(UIDatabase, itemsIds);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'deleteRecordsById' });
};

export const deleteRequisitions = () => (dispatch, getState) => {
  const { dataState, backingData } = getState();

  const requisitionIds = Array.from(dataState.keys()).filter(
    rowKey => dataState.get(rowKey).isSelected
  );

  const requisitionsToDelete = requisitionIds.reduce((acc, requisitionId) => {
    const requisition = backingData.filtered('id = $0', requisitionId)[0];
    const shouldDelete = requisition && requisition.isValid() && !requisition.isFinalised;
    if (shouldDelete) return [...acc, requisition];
    return acc;
  }, []);

  UIDatabase.write(() => {
    UIDatabase.delete('Requisition', requisitionsToDelete);
  });

  dispatch({ type: 'deleteRecordsById' });
};

export const addTransactionBatch = item => (dispatch, getState) => {
  const { pageObject } = getState();
  let addedTransactionBatch;

  UIDatabase.write(() => {
    const transItem = createRecord(UIDatabase, 'TransactionItem', pageObject, item);
    const itemBatch = createRecord(UIDatabase, 'ItemBatch', item, '');
    addedTransactionBatch = createRecord(UIDatabase, 'TransactionBatch', transItem, itemBatch);
  });

  if (addedTransactionBatch) dispatch({ type: 'addItem', item: addedTransactionBatch });
  else dispatch(closeBasicModal());
};

export const createAutomaticOrder = pageObjectType => (dispatch, getState) => {
  const { pageObject } = getState();

  const thisStore = UIDatabase.objects('Name').filtered(
    'id == $0',
    Settings.get(SETTINGS_KEYS.THIS_STORE_NAME_ID)
  )[0];

  UIDatabase.write(() => {
    pageObject.createAutomaticOrder(UIDatabase, thisStore);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'createAutomaticOrder' });
};

export const useSuggestedQuantities = pageObjectType => (dispatch, getState) => {
  const { pageObject } = getState();

  UIDatabase.write(() => {
    pageObject.setRequestedToSuggested(UIDatabase);
    UIDatabase.save(pageObjectType, pageObject);
  });

  dispatch({ type: 'refreshData' });
};

export const hideOverStocked = () => ({
  type: 'hideOverStocked',
});

export const showOverStocked = () => ({
  type: 'showOverStocked',
});

export const editMonthsOfSupply = (value, pageObjectType) => (dispatch, getState) => {
  const { pageObject } = getState();
  const { monthsToSupply } = pageObject;

  if (monthsToSupply !== value) {
    UIDatabase.write(() => {
      pageObject.monthsToSupply = value;
      UIDatabase.save(pageObjectType, pageObject);
    });
  }

  dispatch(closeBasicModal());
};

export const editRequiredQuantity = (value, rowKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  UIDatabase.write(() => {
    objectToEdit.requiredQuantity = parsePositiveInteger(Number(value));
    UIDatabase.save('RequisitionItem', objectToEdit);
  });

  dispatch(editField(rowKey));
};

export const selectAll = () => ({
  type: 'selectAll',
});

export const hideStockOut = () => ({
  type: 'hideStockOut',
});

export const showStockOut = () => ({
  type: 'showStockOut',
});

export const selectItems = items => ({
  type: 'selectItems',
  items,
});

export const editName = value => ({
  type: 'editName',
  value,
});

export const editCountedTotalQuantity = (value, rowKey, columnKey) => (dispatch, getState) => {
  const { data, keyExtractor } = getState();

  const objectToEdit = data.find(row => keyExtractor(row) === rowKey);

  objectToEdit.setCountedTotalQuantity(UIDatabase, parsePositiveInteger(Number(value)));

  dispatch({
    type: 'editCountedTotalQuantity',
    value,
    rowKey,
    columnKey,
  });
};

export const openStocktakeBatchModal = (rowKey, columnKey) => ({
  type: 'openStocktakeBatchModal',
  rowKey,
  columnKey,
});

export const closeStocktakeBatchModal = () => ({
  type: 'closeStocktakeBatchModal',
});

export const openModal = (modalKey, value) => {
  switch (modalKey) {
    case EDIT_STOCKTAKE_BATCH:
      return { type: 'openStocktakeBatchModal', rowKey: value };
    case STOCKTAKE_COMMENT_EDIT:
      return { type: 'openCommentModal' };
    case STOCKTAKE_OUTDATED_ITEM:
      return { type: 'openStocktakeOutdatedItems' };
    default:
      return { type: 'openBasicModal', modalKey };
  }
};

export const resetStocktake = () => (dispatch, getState) => {
  const { pageObject } = getState();

  pageObject.resetStocktake(UIDatabase);

  dispatch({ type: 'resetStocktake' });
};
<|endoftext|>


<commit_before>import { captureException } from 'common/errorLogger';

import Module from '../Module';
import { SELECTED_PLAYER, SELECTED_PLAYER_PET } from '../Analyzer';
import EventFilter from '../EventFilter';

const CATCH_ALL_EVENT = 'event';

/**
 * This (core) module takes care of:
 * - tracking attached event listeners
 * - filtering event listeners (as configured in EventFilter)
 * - firing event listeners
 */
class EventEmitter extends Module {
  static get catchAll() {
    return new EventFilter(CATCH_ALL_EVENT);
  }

  _eventListenersByEventType = {};
  /**
   * @param {string|EventFilter} eventFilter
   * @param {function} listener
   * @param {Module} module
   */
  addEventListener(eventFilter, listener, module) {
    const eventType = eventFilter instanceof EventFilter ? eventFilter.eventType : eventFilter;
    this._eventListenersByEventType[eventType] = this._eventListenersByEventType[eventType] || [];
    this._eventListenersByEventType[eventType].push({
      eventFilter,
      listener: this._compileListener(eventFilter, listener, module),
    });
  }
  _compileListener(eventFilter, listener, module) {
    listener = this._prependCounter(listener);
    if (eventFilter instanceof EventFilter) {
      listener = this._prependFilters(eventFilter, listener);
    }
    // We need to prepend this last so it's at the top level (the first check)
    listener = this._prependActiveCheck(listener, module);
    return listener;
  }
  _actualExecutions = 0;
  _prependCounter(listener) {
    return event => {
      this._actualExecutions += 1;
      listener(event);
    };
  }
  _prependActiveCheck(listener, module) {
    return function (event) {
      if (module.active) {
        listener(event);
      }
    };
  }
  _prependFilters(eventFilter, listener) {
    const by = eventFilter.by();
    if (by) {
      listener = this._prependByCheck(listener, by);
    }
    const to = eventFilter.to();
    if (to) {
      listener = this._prependToCheck(listener, to);
    }
    const spell = eventFilter.spell();
    if (spell) {
      listener = this._prependSpellCheck(listener, spell);
    }
    return listener;
  }
  _prependByCheck(listener, by) {
    const requiresSelectedPlayer = by & SELECTED_PLAYER;
    const requiresSelectedPlayerPet = by & SELECTED_PLAYER_PET;

    let check;
    if (requiresSelectedPlayer && requiresSelectedPlayerPet) {
      check = event => this.owner.byPlayer(event) || this.owner.byPlayerPet(event);
    } else if (requiresSelectedPlayer) {
      check = event => this.owner.byPlayer(event);
    } else if (requiresSelectedPlayerPet) {
      check = event => this.owner.byPlayerPet(event);
    } else {
      return listener;
    }

    return function (event) {
      if (check(event)) {
        listener(event);
      }
    };
  }
  _prependToCheck(listener, to) {
    const requiresSelectedPlayer = to & SELECTED_PLAYER;
    const requiresSelectedPlayerPet = to & SELECTED_PLAYER_PET;

    let check;
    if (requiresSelectedPlayer && requiresSelectedPlayerPet) {
      check = event => this.owner.toPlayer(event) || this.owner.toPlayerPet(event);
    } else if (requiresSelectedPlayer) {
      check = event => this.owner.toPlayer(event);
    } else if (requiresSelectedPlayerPet) {
      check = event => this.owner.toPlayerPet(event);
    } else {
      return listener;
    }

    return function (event) {
      if (check(event)) {
        listener(event);
      }
    };
  }
  _prependSpellCheck(listener, spell) {
    if(spell instanceof Array) {
      return function(event) {
        if (event.ability && spell.some(s => s.id === event.ability.guid)) {
          listener(event);
        }
      };
    }
    const spellId = spell.id;
    return function (event) {
      if (event.ability && event.ability.guid === spellId) {
        listener(event);
      }
    };
  }

  _listenersCalled = 0;
  _isHandlingEvent = false;
  triggerEvent(event) {
    if (process.env.NODE_ENV === 'development') {
      this._validateEvent(event);
    }

    // When benchmarking the event triggering make sure to disable the event batching and turn the listener into a dummy so you get the performance of just this piece of code. At the time of writing the event triggering code only has about 12ms overhead for a full log.

    // TODO: Make a module that does the timestamp tracking
    if (event.timestamp) {
      this.owner._timestamp = event.timestamp;
    }

    const run = options => {
      try {
        this._listenersCalled += 1;
        options.listener(event);
      } catch (err) {
        if (process.env.NODE_ENV !== 'production') {
          throw err;
        }
        console.error('Disabling', options.module.constructor.name, 'and child dependencies because an error occured', err);
        // Disable this module and all active modules that have this as a dependency
        this.owner.deepDisable(options.module);
        captureException(err);
      }
    };

    this._isHandlingEvent = true;
    {
      // Handle on_event (listeners of all events)
      const listeners = this._eventListenersByEventType[CATCH_ALL_EVENT];
      if (listeners) {
        listeners.forEach(run);
      }
    }
    {
      const listeners = this._eventListenersByEventType[event.type];
      if (listeners) {
        listeners.forEach(run);
      }
    }
    this._isHandlingEvent = false;

    this.owner.eventHistory.push(event);
    // Some modules need to have a primitive value to cause re-renders
    // TODO: This can probably be removed since we only render upon completion now
    this.owner.eventCount += 1;

    this.runFinally();

    return event;
  }
  _finally = null;
  finally(func) {
    this._finally = this._finally || [];
    this._finally.push(func);
  }
  runFinally() {
    if (this._finally) {
      const currentBatch = this._finally;
      // Reset before running so if an item calls another event, it doesn't do the same finally multiple times
      this._finally = null;
      currentBatch.forEach(item => item());
    }
  }
  fabricateEvent(event, trigger = null) {
    const fabricatedEvent = {
      // When no timestamp is provided in the event (you should always try to), the current timestamp will be used by default.
      timestamp: this.owner.currentTimestamp,
      // If this event was triggered you should pass it along
      trigger: trigger ? trigger : undefined,
      ...event,
      type: event.type instanceof EventFilter ? event.type.eventType : event.type,
      __fabricated: true,
    };
    if (this._isHandlingEvent) {
      this.finally(() => {
        this.triggerEvent(fabricatedEvent);
      });
    } else {
      this.triggerEvent(fabricatedEvent);
    }
    return fabricatedEvent;
  }
  _validateEvent(event) {
    if (!event.type) {
      console.log(event);
      throw new Error('Events should have a type. No type received. See the console for the event.');
    }
  }
}

export default EventEmitter;
<commit_msg>Fix crash in module error handling<commit_after>import { captureException } from 'common/errorLogger';

import Module from '../Module';
import { SELECTED_PLAYER, SELECTED_PLAYER_PET } from '../Analyzer';
import EventFilter from '../EventFilter';

const CATCH_ALL_EVENT = 'event';

/**
 * This (core) module takes care of:
 * - tracking attached event listeners
 * - filtering event listeners (as configured in EventFilter)
 * - firing event listeners
 */
class EventEmitter extends Module {
  static get catchAll() {
    return new EventFilter(CATCH_ALL_EVENT);
  }

  _eventListenersByEventType = {};
  /**
   * @param {string|EventFilter} eventFilter
   * @param {function} listener
   * @param {Module} module
   */
  addEventListener(eventFilter, listener, module) {
    const eventType = eventFilter instanceof EventFilter ? eventFilter.eventType : eventFilter;
    this._eventListenersByEventType[eventType] = this._eventListenersByEventType[eventType] || [];
    this._eventListenersByEventType[eventType].push({
      eventFilter,
      module, // used when the listener throws an exception to disable the related module
      listener: this._compileListener(eventFilter, listener, module),
    });
  }
  _compileListener(eventFilter, listener, module) {
    listener = this._prependCounter(listener);
    if (eventFilter instanceof EventFilter) {
      listener = this._prependFilters(eventFilter, listener);
    }
    // We need to prepend this last so it's at the top level (the first check)
    listener = this._prependActiveCheck(listener, module);
    return listener;
  }
  _actualExecutions = 0;
  _prependCounter(listener) {
    return event => {
      this._actualExecutions += 1;
      listener(event);
    };
  }
  _prependActiveCheck(listener, module) {
    return function (event) {
      if (module.active) {
        listener(event);
      }
    };
  }
  _prependFilters(eventFilter, listener) {
    const by = eventFilter.by();
    if (by) {
      listener = this._prependByCheck(listener, by);
    }
    const to = eventFilter.to();
    if (to) {
      listener = this._prependToCheck(listener, to);
    }
    const spell = eventFilter.spell();
    if (spell) {
      listener = this._prependSpellCheck(listener, spell);
    }
    return listener;
  }
  _prependByCheck(listener, by) {
    const requiresSelectedPlayer = by & SELECTED_PLAYER;
    const requiresSelectedPlayerPet = by & SELECTED_PLAYER_PET;

    let check;
    if (requiresSelectedPlayer && requiresSelectedPlayerPet) {
      check = event => this.owner.byPlayer(event) || this.owner.byPlayerPet(event);
    } else if (requiresSelectedPlayer) {
      check = event => this.owner.byPlayer(event);
    } else if (requiresSelectedPlayerPet) {
      check = event => this.owner.byPlayerPet(event);
    } else {
      return listener;
    }

    return function (event) {
      if (check(event)) {
        listener(event);
      }
    };
  }
  _prependToCheck(listener, to) {
    const requiresSelectedPlayer = to & SELECTED_PLAYER;
    const requiresSelectedPlayerPet = to & SELECTED_PLAYER_PET;

    let check;
    if (requiresSelectedPlayer && requiresSelectedPlayerPet) {
      check = event => this.owner.toPlayer(event) || this.owner.toPlayerPet(event);
    } else if (requiresSelectedPlayer) {
      check = event => this.owner.toPlayer(event);
    } else if (requiresSelectedPlayerPet) {
      check = event => this.owner.toPlayerPet(event);
    } else {
      return listener;
    }

    return function (event) {
      if (check(event)) {
        listener(event);
      }
    };
  }
  _prependSpellCheck(listener, spell) {
    if(spell instanceof Array) {
      return function(event) {
        if (event.ability && spell.some(s => s.id === event.ability.guid)) {
          listener(event);
        }
      };
    }
    const spellId = spell.id;
    return function (event) {
      if (event.ability && event.ability.guid === spellId) {
        listener(event);
      }
    };
  }

  _listenersCalled = 0;
  _isHandlingEvent = false;
  triggerEvent(event) {
    if (process.env.NODE_ENV === 'development') {
      this._validateEvent(event);
    }

    // When benchmarking the event triggering make sure to disable the event batching and turn the listener into a dummy so you get the performance of just this piece of code. At the time of writing the event triggering code only has about 12ms overhead for a full log.

    // TODO: Make a module that does the timestamp tracking
    if (event.timestamp) {
      this.owner._timestamp = event.timestamp;
    }

    const run = options => {
      try {
        this._listenersCalled += 1;
        options.listener(event);
      } catch (err) {
        if (process.env.NODE_ENV !== 'production') {
          throw err;
        }
        console.error('Disabling', options.module.constructor.name, 'and child dependencies because an error occured', err);
        // Disable this module and all active modules that have this as a dependency
        this.owner.deepDisable(options.module);
        captureException(err);
      }
    };

    this._isHandlingEvent = true;
    {
      // Handle on_event (listeners of all events)
      const listeners = this._eventListenersByEventType[CATCH_ALL_EVENT];
      if (listeners) {
        listeners.forEach(run);
      }
    }
    {
      const listeners = this._eventListenersByEventType[event.type];
      if (listeners) {
        listeners.forEach(run);
      }
    }
    this._isHandlingEvent = false;

    this.owner.eventHistory.push(event);
    // Some modules need to have a primitive value to cause re-renders
    // TODO: This can probably be removed since we only render upon completion now
    this.owner.eventCount += 1;

    this.runFinally();

    return event;
  }
  _finally = null;
  finally(func) {
    this._finally = this._finally || [];
    this._finally.push(func);
  }
  runFinally() {
    if (this._finally) {
      const currentBatch = this._finally;
      // Reset before running so if an item calls another event, it doesn't do the same finally multiple times
      this._finally = null;
      currentBatch.forEach(item => item());
    }
  }
  fabricateEvent(event, trigger = null) {
    const fabricatedEvent = {
      // When no timestamp is provided in the event (you should always try to), the current timestamp will be used by default.
      timestamp: this.owner.currentTimestamp,
      // If this event was triggered you should pass it along
      trigger: trigger ? trigger : undefined,
      ...event,
      type: event.type instanceof EventFilter ? event.type.eventType : event.type,
      __fabricated: true,
    };
    if (this._isHandlingEvent) {
      this.finally(() => {
        this.triggerEvent(fabricatedEvent);
      });
    } else {
      this.triggerEvent(fabricatedEvent);
    }
    return fabricatedEvent;
  }
  _validateEvent(event) {
    if (!event.type) {
      console.log(event);
      throw new Error('Events should have a type. No type received. See the console for the event.');
    }
  }
}

export default EventEmitter;
<|endoftext|>


<commit_before>const debug = require('debug')('metalsmith-svg-optimizer')
const each = require('async/each')
const SVGO = require('svgo')
const multimatch = require('multimatch')

function plugin (opts) {
  debug('Initialized metalsmith-svg-optimizer')
  debug('Options: %o', opts)

  const svgo = new SVGO({
    pretty: opts.pretty,
    plugins: opts.plugins
  })

  const pattern = opts.pattern || ['**/*.svg']

  return (files, metalsmith, done) => {
    each(
      multimatch(Object.keys(files), pattern),
      (filepath, callback) => {
        debug('Optimize file: %s', filepath)
        const file = files[filepath]

        svgo.optimize(file.contents.toString(), { path: filepath })
          .then((result) => {
            // Update the file contents with the optimized version
            file.contents = Buffer.from(result.data)
            callback()
          }, callback)
      }, done)
  }
}

module.exports = plugin
<commit_msg>fix: check if file is SVG<commit_after>const extname = require('path').extname
const debug = require('debug')('metalsmith-svg-optimizer')
const each = require('async/each')
const SVGO = require('svgo')
const multimatch = require('multimatch')

const svg = (file) => /\.svg$/.test(extname(file))

function plugin (opts) {
  debug('Initialized metalsmith-svg-optimizer')
  debug('Options: %o', opts)

  const svgo = new SVGO({
    pretty: opts.pretty,
    plugins: opts.plugins
  })

  const pattern = opts.pattern || ['**/*.svg']

  return (files, metalsmith, done) => {
    each(
      multimatch(Object.keys(files), pattern),
      (filepath, callback) => {
        if (!svg(filepath)) {
          return callback()
        }
        debug('Optimize file: %s', filepath)
        const file = files[filepath]

        svgo.optimize(file.contents.toString(), { path: filepath })
          .then((result) => {
            // Update the file contents with the optimized version
            file.contents = Buffer.from(result.data)
            callback()
          }, callback)
      }, done)
  }
}

module.exports = plugin
<|endoftext|>


<commit_before>/**
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.*
 */

const assert = require('assert');
const Effect = require('./Effect');

/**
 * An Effect which temporarily sets the target property to
 * a value before restoring its original value
 */
class PulseEffect extends Effect {
  /**
   * @param {EffectDescription} desc
   */
  constructor(desc) {
    super(desc);
    this.value = desc.value;
    assert(typeof this.value === this.property.type,
      'setpoint and property must be same type');
    this.on = false;
    this.oldValue = null;
  }

  /**
   * @return {EffectDescription}
   */
  toDescription() {
    return Object.assign(
      super.toDescription(),
      {value: this.value}
    );
  }

  /**
   * @param {State} state
   */
  setState(state) {
    if (!this.on && state.on) {
      this.property.get().then(value => {
        this.oldValue = value;
        this.on = true;
        return this.property.set(this.value);
      });
    }
    if (this.on && !state.on) {
      this.on = false;
      return this.property.set(this.oldValue);
    }
  }
}

module.exports = PulseEffect;
<commit_msg>Fix PropertyEffect activation logic<commit_after>/**
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.*
 */

const assert = require('assert');
const Effect = require('./Effect');

/**
 * An Effect which temporarily sets the target property to
 * a value before restoring its original value
 */
class PulseEffect extends Effect {
  /**
   * @param {EffectDescription} desc
   */
  constructor(desc) {
    super(desc);
    this.value = desc.value;
    assert(typeof this.value === this.property.type,
      'setpoint and property must be same type');
    this.on = false;
    this.oldValue = null;
  }

  /**
   * @return {EffectDescription}
   */
  toDescription() {
    return Object.assign(
      super.toDescription(),
      {value: this.value}
    );
  }

  /**
   * @param {State} state
   */
  setState(state) {
    if (state.on) {
      // If we're already active, just perform the effect again
      if (this.on) {
        return this.property.set(this.value);
      }
      // Activate the effect and save our current state to revert to upon
      // deactivation
       this.property.get().then(value => {
        this.oldValue = value;
        this.on = true;
        return this.property.set(this.value);
      });
    } else if (this.on) {
      // Revert to our original value
      this.on = false;
      return this.property.set(this.oldValue);
    }
  }
}

module.exports = PulseEffect;
<|endoftext|>


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

var _self = {},
	_ID = require("./manifest.json").namespace;

	// These methods are called by your App's JavaScript
	// They make WebWorks function calls to the methods
	// in the index.js of the Extension

	// Asynchronous with sending and returning a JSON object
	_self.vibration_request = function (input, callback) {

		if ( typeof(callback) == "function" ) {
			window.webworks.event.once(_ID, "requestVibrationCallbackResult", callback);
		}

		window.webworks.execAsync(_ID, "vibration_request", { input: input});

	};

module.exports = _self;
<commit_msg>had wrong callback string in the js layer<commit_after>/*
* Copyright 2013 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var _self = {},
	_ID = require("./manifest.json").namespace;

	// These methods are called by your App's JavaScript
	// They make WebWorks function calls to the methods
	// in the index.js of the Extension

	// Asynchronous with sending and returning a JSON object
	_self.vibration_request = function (input, callback) {

		if ( typeof(callback) == "function" ) {
			window.webworks.event.once(_ID, "vibration_requestCallbackResult", callback);
		}

		window.webworks.execAsync(_ID, "vibration_request", { input: input});

	};

module.exports = _self;
<|endoftext|>


<commit_before>//=============================================================================
// ChangeActorBattleAnimationToSsPlayer.js
//=============================================================================

/*:
 * @plugindesc Replace the actor's battle animations made by OPTPiX SpriteStudio.
 * @author Inaba Byakko
 *
 * @param Suffix(walk)
 * @desc An suffix of side view battler's image file name which means idling motion. Default value is "walk"
 * @default walk
 *
 * @param Suffix(wait)
 * @desc An suffix of side view battler's image file name which means physical ready motion. Default value is "wait"
 * @default wait
 *
 * @param Suffix(chant)
 * @desc An suffix of side view battler's image file name which means magical ready motion. Default value is "chant"
 * @default chant
 *
 * @param Suffix(guard)
 * @desc An suffix of side view battler's image file name which means guarding motion. Default value is "guard"
 * @default guard
 *
 * @param Suffix(damage)
 * @desc An suffix of side view battler's image file name which means damaged motion. Default value is "damage"
 * @default damage
 *
 * @param Suffix(evade)
 * @desc An suffix of side view battler's image file name which means evading motion. Default value is "evade"
 * @default evade
 *
 * @param Suffix(thrust)
 * @desc An suffix of side view battler's image file name which means stabbing motion. Default value is "thrust"
 * @default thrust
 *
 * @param Suffix(swing)
 * @desc An suffix of side view battler's image file name which means swinging motion. Default value is "swing"
 * @default swing
 *
 * @param Suffix(missile)
 * @desc An suffix of side view battler's image file name which means shooting motion. Default value is "missile"
 * @default missile
 *
 * @param Suffix(skill)
 * @desc An suffix of side view battler's image file name which means physical skill using motion. Default value is "skill"
 * @default skill
 *
 * @param Suffix(spell)
 * @desc An suffix of side view battler's image file name which means magical skill using motion. Default value is "spell"
 * @default spell
 *
 * @param Suffix(item)
 * @desc An suffix of side view battler's image file name which means item using motion. Default value is "item"
 * @default item
 *
 * @param Suffix(escape)
 * @desc An suffix of side view battler's image file name which means escaping motion. Default value is "escape"
 * @default escape
 *
 * @param Suffix(victory)
 * @desc An suffix of side view battler's image file name which means victory motion. Default value is "victory"
 * @default victory
 *
 * @param Suffix(dying)
 * @desc An suffix of side view battler's image file name which means idling motion with crisis. Default value is "dying"
 * @default dying
 *
 * @param Suffix(abnormal)
 * @desc An suffix of side view battler's image file name which means idling motion with abnormal state. Default value is "abnormal"
 * @default abnormal
 *
 * @param Suffix(sleep)
 * @desc An suffix of side view battler's image file name which means sleeping motion. Default value is "sleep"
 * @default sleep
 *
 * @param Suffix(dead)
 * @desc An suffix of side view battler's image file name which means dead motion. Default value is "dead"
 * @default dead
 *
 * @param HideWeaponGraphics
 * @desc Select whether you hide battler's weapon animation graphics(ON or OFF). Default value is "OFF"
 * @default OFF
 *
 * @param Loop(dead)
 * @desc Select whether you play dead motion repeatedly(ON or OFF). Default value is "ON"
 * @default ON
 *
 * @param Loop(victory)
 * @desc Select whether you play victory motion repeatedly(ON or OFF). Default value is "ON"
 * @default ON
 *
 * @help
 * ** INFORMATION **
 * This plug-in is depends on other plug-in "SsPlayerForRPGMV".
 * Please download from following URL and install above this plug-in.
 * https://github.com/InabaByakko/SSPlayerForRPGMV
 *
 * Plug-in commands:
 *   (none)
 */

/*:ja
 * @plugindesc サイドビュー戦闘時のアクター側アニメーションをSpriteStudioアニメーションに差し替えるプラグインです。
 * @author Inaba Byakko
 *
 * @param Suffix(walk)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、前進時のモーション名。デフォルトは"walk"
 * @default walk
 *
 * @param Suffix(wait)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、通常待機時のモーション名。デフォルトは"wait"
 * @default wait
 *
 * @param Suffix(chant)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、詠唱待機時のモーション名。デフォルトは"chant"
 * @default chant
 *
 * @param Suffix(guard)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、防御時のモーション名。デフォルトは"guard"
 * @default guard
 *
 * @param Suffix(damage)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、ダメージ時のモーション名。デフォルトは"damage"
 * @default damage
 *
 * @param Suffix(evade)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、回避時のモーション名。デフォルトは"evade"
 * @default evade
 *
 * @param Suffix(thrust)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、突き攻撃時のモーション名。デフォルトは"thrust"
 * @default thrust
 *
 * @param Suffix(swing)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、振り攻撃時のモーション名。デフォルトは"swing"
 * @default swing
 *
 * @param Suffix(missile)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、飛び道具攻撃時のモーション名。デフォルトは"missile"
 * @default missile
 *
 * @param Suffix(skill)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、汎用スキル発動時のモーション名。デフォルトは"skill"
 * @default skill
 *
 * @param Suffix(spell)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、魔法発動時のモーション名。デフォルトは"spell"
 * @default spell
 *
 * @param Suffix(item)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、アイテム使用時のモーション名。デフォルトは"item"
 * @default item
 *
 * @param Suffix(escape)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、逃げる時のモーション名。デフォルトは"escape"
 * @default escape
 *
 * @param Suffix(victory)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、勝利時のモーション名。デフォルトは"victory"
 * @default victory
 *
 * @param Suffix(dying)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、瀕死時のモーション名。デフォルトは"dying"
 * @default dying
 *
 * @param Suffix(abnormal)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、状態異常時のモーション名。デフォルトは"abnormal"
 * @default abnormal
 *
 * @param Suffix(sleep)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、睡眠時のモーション名。デフォルトは"sleep"
 * @default sleep
 *
 * @param Suffix(dead)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、戦闘不能時のモーション名。デフォルトは"dead"
 * @default dead
 *
 * @param HideWeaponGraphics
 * @desc 攻撃中の武器アニメーションを非表示にするか（ON/OFF) 。デフォルトはOFF
 * @default OFF
 *
 * @param Loop(dead)
 * @desc 戦闘不能モーションを繰り返し再生するか（ON/OFF) 。デフォルトはON
 * @default ON
 *
 * @param Loop(victory)
 * @desc 勝利モーションを繰り返し再生するか（ON/OFF) 。デフォルトはON
 * @default ON
 *
 * @help
 * ※注意
 * 本プラグインの動作には、依存プラグイン「SsPlayerForRPGMV」
 * が必要です。下のURLからダウンロードの上、本プラグインより
 * 上の位置にインストールしてください。
 * https://github.com/InabaByakko/SSPlayerForRPGMV
 *
 * プラグインコマンド:
 *   （なし）
 */

(function () {

    // 依存プラグイン導入チェック
    if (typeof SsSprite !== "function") {
        throw new Error(
                "Dependency plug-in 'SsPlayerForRPGMV' is not installed.");
    }

    // 接尾語収集
    var parameters = PluginManager
            .parameters('ChangeActorBattleAnimationToSsPlayer');
    var motion_suffixes = {
        walk: parameters["Suffix(walk)"],
        wait: parameters["Suffix(wait)"],
        chant: parameters["Suffix(chant)"],
        guard: parameters["Suffix(guard)"],
        damage: parameters["Suffix(damage)"],
        evade: parameters["Suffix(evade)"],
        thrust: parameters["Suffix(thrust)"],
        swing: parameters["Suffix(swing)"],
        missile: parameters["Suffix(missile)"],
        skill: parameters["Suffix(skill)"],
        spell: parameters["Suffix(spell)"],
        item: parameters["Suffix(item)"],
        escape: parameters["Suffix(escape)"],
        victory: parameters["Suffix(victory)"],
        dying: parameters["Suffix(dying)"],
        abnormal: parameters["Suffix(abnormal)"],
        sleep: parameters["Suffix(sleep)"],
        dead: parameters["Suffix(dead)"]
    };

    if (parameters["Loop(dead)"].toUpperCase() == "OFF")
        Sprite_Actor.MOTIONS["dead"]["loop"] = false;
    if (parameters["Loop(victory)"].toUpperCase() == "OFF")
        Sprite_Actor.MOTIONS["victory"]["loop"] = false;

    var animationDir = String(PluginManager.parameters('SSPlayerForRPGMV')['Animation File Path']
            || "img/animations/ssas")
            + "/";

    var _Sprite_Actor_createMainSprite = Sprite_Actor.prototype.createMainSprite;
    Sprite_Actor.prototype.createMainSprite = function () {
        _Sprite_Actor_createMainSprite.call(this);
        this._ssSprite = new SsSprite(null);
        this._mainSprite.addChild(this._ssSprite);
    };

    var _Sprite_Actor_setBattler = Sprite_Actor.prototype.setBattler;
    Sprite_Actor.prototype.setBattler = function (battler) {
        var changed = (battler !== this._actor);
        _Sprite_Actor_setBattler.call(this, battler);
        if (changed) {
            this._ssMotions = {};
            this.loadActorSsMotions(motion_suffixes);
        }
    };

    Sprite_Actor.prototype.loadActorSsMotions = function (motions) {
        for (var motion in motions) {
            this._ssMotions[motion] = null;
            this.loadSsMotion(this._actor.battlerName(), motion);
        }
    };

    Sprite_Actor.prototype.loadSsMotion = function (battlerName, motionSuffix) {
        var xhr = new XMLHttpRequest();
        var url = animationDir + battlerName + "_" + motionSuffix + ".json";
        xhr.open('GET', url);
        xhr.overrideMimeType('application/json');
        xhr.onload = function (motionSuffix) {
            if (xhr.status < 400) {
                var jsonData = JSON.parse(xhr.responseText)[0];
                var imageList = new SsImageList(jsonData.images, animationDir,
                    true);
                var animation = new SsAnimation(jsonData.animation, imageList);
                this._ssMotions[motionSuffix] = animation;
                // ロード完了コールバックがあれば実行
                if (typeof this.onSsMotionLoad === "function") {
                    this.onSsMotionLoad();
                }
            }
        } .bind(this, motionSuffix);
        xhr.send();
    };

    // 元スプライトのビットマップを無効化し、SsSpriteのモーション更新を行う
    Sprite_Actor.prototype.updateBitmap = function () {
        Sprite_Battler.prototype.updateBitmap.call(this);
        this._mainSprite.bitmap = null;
        this.updateSsMotion();
    };

    // オプションがONのとき、武器アニメーションを非表示に
    var _spriteActorSetupWeaponAnimation = Sprite_Actor.prototype.setupWeaponAnimation;
    Sprite_Actor.prototype.setupWeaponAnimation = function () {
        if (parameters["HideWeaponGraphics"].toUpperCase() === "OFF") {
            _spriteActorSetupWeaponAnimation.call(this);
        }
    };

    Sprite_Actor.prototype.updateSsMotion = function () {
        if (typeof this._motion === "object") {
            var motionName = "";
            for (var key in Sprite_Actor.MOTIONS) {
                if (this._motion === Sprite_Actor.MOTIONS[key])
                    motionName = key;
            }
            ;
            if (motionName === "") motionName = this._motion["index"];
            var newMotion = this._ssMotions[motionName];
            if (this._ssSprite.getAnimation() !== newMotion) {
                if (typeof this._ssMotions === "undefined")
                    return;
                this._ssSprite.setAnimation(newMotion);
                this._ssSprite.setLoop(Number(!this._motion["loop"]));
                if (this._motion["loop"] === false) {
                    this._ssSprite.setEndCallBack(function () {
                        this.refreshMotion();
                    } .bind(this));
                } else {
                    this._ssSprite.setEndCallBack(function () {
                    });
                }
                if (newMotion !== null)
                    this.onSsMotionLoad = null;
            }
        }
    };

    var _Sprite_Actor_refreshMotion = Sprite_Actor.prototype.refreshMotion;
    Sprite_Actor.prototype.refreshMotion = function () {
        if (BattleManager.isBattleEnd()) {
            return;
        }
        _Sprite_Actor_refreshMotion.call(this);
    };
})();<commit_msg>ループしないモーションが最後まで再生されないことがある不具合を修正<commit_after>//=============================================================================
// ChangeActorBattleAnimationToSsPlayer.js
//=============================================================================

/*:
 * @plugindesc Replace the actor's battle animations made by OPTPiX SpriteStudio.
 * @author Inaba Byakko
 *
 * @param Suffix(walk)
 * @desc An suffix of side view battler's image file name which means idling motion. Default value is "walk"
 * @default walk
 *
 * @param Suffix(wait)
 * @desc An suffix of side view battler's image file name which means physical ready motion. Default value is "wait"
 * @default wait
 *
 * @param Suffix(chant)
 * @desc An suffix of side view battler's image file name which means magical ready motion. Default value is "chant"
 * @default chant
 *
 * @param Suffix(guard)
 * @desc An suffix of side view battler's image file name which means guarding motion. Default value is "guard"
 * @default guard
 *
 * @param Suffix(damage)
 * @desc An suffix of side view battler's image file name which means damaged motion. Default value is "damage"
 * @default damage
 *
 * @param Suffix(evade)
 * @desc An suffix of side view battler's image file name which means evading motion. Default value is "evade"
 * @default evade
 *
 * @param Suffix(thrust)
 * @desc An suffix of side view battler's image file name which means stabbing motion. Default value is "thrust"
 * @default thrust
 *
 * @param Suffix(swing)
 * @desc An suffix of side view battler's image file name which means swinging motion. Default value is "swing"
 * @default swing
 *
 * @param Suffix(missile)
 * @desc An suffix of side view battler's image file name which means shooting motion. Default value is "missile"
 * @default missile
 *
 * @param Suffix(skill)
 * @desc An suffix of side view battler's image file name which means physical skill using motion. Default value is "skill"
 * @default skill
 *
 * @param Suffix(spell)
 * @desc An suffix of side view battler's image file name which means magical skill using motion. Default value is "spell"
 * @default spell
 *
 * @param Suffix(item)
 * @desc An suffix of side view battler's image file name which means item using motion. Default value is "item"
 * @default item
 *
 * @param Suffix(escape)
 * @desc An suffix of side view battler's image file name which means escaping motion. Default value is "escape"
 * @default escape
 *
 * @param Suffix(victory)
 * @desc An suffix of side view battler's image file name which means victory motion. Default value is "victory"
 * @default victory
 *
 * @param Suffix(dying)
 * @desc An suffix of side view battler's image file name which means idling motion with crisis. Default value is "dying"
 * @default dying
 *
 * @param Suffix(abnormal)
 * @desc An suffix of side view battler's image file name which means idling motion with abnormal state. Default value is "abnormal"
 * @default abnormal
 *
 * @param Suffix(sleep)
 * @desc An suffix of side view battler's image file name which means sleeping motion. Default value is "sleep"
 * @default sleep
 *
 * @param Suffix(dead)
 * @desc An suffix of side view battler's image file name which means dead motion. Default value is "dead"
 * @default dead
 *
 * @param HideWeaponGraphics
 * @desc Select whether you hide battler's weapon animation graphics(ON or OFF). Default value is "OFF"
 * @default OFF
 *
 * @param Loop(dead)
 * @desc Select whether you play dead motion repeatedly(ON or OFF). Default value is "ON"
 * @default ON
 *
 * @param Loop(victory)
 * @desc Select whether you play victory motion repeatedly(ON or OFF). Default value is "ON"
 * @default ON
 *
 * @help
 * ** INFORMATION **
 * This plug-in is depends on other plug-in "SsPlayerForRPGMV".
 * Please download from following URL and install above this plug-in.
 * https://github.com/InabaByakko/SSPlayerForRPGMV
 *
 * Plug-in commands:
 *   (none)
 */

/*:ja
 * @plugindesc サイドビュー戦闘時のアクター側アニメーションをSpriteStudioアニメーションに差し替えるプラグインです。
 * @author Inaba Byakko
 *
 * @param Suffix(walk)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、前進時のモーション名。デフォルトは"walk"
 * @default walk
 *
 * @param Suffix(wait)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、通常待機時のモーション名。デフォルトは"wait"
 * @default wait
 *
 * @param Suffix(chant)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、詠唱待機時のモーション名。デフォルトは"chant"
 * @default chant
 *
 * @param Suffix(guard)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、防御時のモーション名。デフォルトは"guard"
 * @default guard
 *
 * @param Suffix(damage)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、ダメージ時のモーション名。デフォルトは"damage"
 * @default damage
 *
 * @param Suffix(evade)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、回避時のモーション名。デフォルトは"evade"
 * @default evade
 *
 * @param Suffix(thrust)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、突き攻撃時のモーション名。デフォルトは"thrust"
 * @default thrust
 *
 * @param Suffix(swing)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、振り攻撃時のモーション名。デフォルトは"swing"
 * @default swing
 *
 * @param Suffix(missile)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、飛び道具攻撃時のモーション名。デフォルトは"missile"
 * @default missile
 *
 * @param Suffix(skill)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、汎用スキル発動時のモーション名。デフォルトは"skill"
 * @default skill
 *
 * @param Suffix(spell)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、魔法発動時のモーション名。デフォルトは"spell"
 * @default spell
 *
 * @param Suffix(item)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、アイテム使用時のモーション名。デフォルトは"item"
 * @default item
 *
 * @param Suffix(escape)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、逃げる時のモーション名。デフォルトは"escape"
 * @default escape
 *
 * @param Suffix(victory)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、勝利時のモーション名。デフォルトは"victory"
 * @default victory
 *
 * @param Suffix(dying)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、瀕死時のモーション名。デフォルトは"dying"
 * @default dying
 *
 * @param Suffix(abnormal)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、状態異常時のモーション名。デフォルトは"abnormal"
 * @default abnormal
 *
 * @param Suffix(sleep)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、睡眠時のモーション名。デフォルトは"sleep"
 * @default sleep
 *
 * @param Suffix(dead)
 * @desc SV戦闘キャラ画像ファイル名の後ろに付く、戦闘不能時のモーション名。デフォルトは"dead"
 * @default dead
 *
 * @param HideWeaponGraphics
 * @desc 攻撃中の武器アニメーションを非表示にするか（ON/OFF) 。デフォルトはOFF
 * @default OFF
 *
 * @param Loop(dead)
 * @desc 戦闘不能モーションを繰り返し再生するか（ON/OFF) 。デフォルトはON
 * @default ON
 *
 * @param Loop(victory)
 * @desc 勝利モーションを繰り返し再生するか（ON/OFF) 。デフォルトはON
 * @default ON
 *
 * @help
 * ※注意
 * 本プラグインの動作には、依存プラグイン「SsPlayerForRPGMV」
 * が必要です。下のURLからダウンロードの上、本プラグインより
 * 上の位置にインストールしてください。
 * https://github.com/InabaByakko/SSPlayerForRPGMV
 *
 * プラグインコマンド:
 *   （なし）
 */

(function () {

    // 依存プラグイン導入チェック
    if (typeof SsSprite !== "function") {
        throw new Error(
                "Dependency plug-in 'SsPlayerForRPGMV' is not installed.");
    }

    // 接尾語収集
    var parameters = PluginManager
            .parameters('ChangeActorBattleAnimationToSsPlayer');
    var motion_suffixes = {
        walk: parameters["Suffix(walk)"],
        wait: parameters["Suffix(wait)"],
        chant: parameters["Suffix(chant)"],
        guard: parameters["Suffix(guard)"],
        damage: parameters["Suffix(damage)"],
        evade: parameters["Suffix(evade)"],
        thrust: parameters["Suffix(thrust)"],
        swing: parameters["Suffix(swing)"],
        missile: parameters["Suffix(missile)"],
        skill: parameters["Suffix(skill)"],
        spell: parameters["Suffix(spell)"],
        item: parameters["Suffix(item)"],
        escape: parameters["Suffix(escape)"],
        victory: parameters["Suffix(victory)"],
        dying: parameters["Suffix(dying)"],
        abnormal: parameters["Suffix(abnormal)"],
        sleep: parameters["Suffix(sleep)"],
        dead: parameters["Suffix(dead)"]
    };

    if (parameters["Loop(dead)"].toUpperCase() == "OFF")
        Sprite_Actor.MOTIONS["dead"]["loop"] = false;
    if (parameters["Loop(victory)"].toUpperCase() == "OFF")
        Sprite_Actor.MOTIONS["victory"]["loop"] = false;

    var animationDir = String(PluginManager.parameters('SSPlayerForRPGMV')['Animation File Path']
            || "img/animations/ssas")
            + "/";

    var _Sprite_Actor_createMainSprite = Sprite_Actor.prototype.createMainSprite;
    Sprite_Actor.prototype.createMainSprite = function () {
        _Sprite_Actor_createMainSprite.call(this);
        this._ssSprite = new SsSprite(null);
        this._mainSprite.addChild(this._ssSprite);
    };

    var _Sprite_Actor_setBattler = Sprite_Actor.prototype.setBattler;
    Sprite_Actor.prototype.setBattler = function (battler) {
        var changed = (battler !== this._actor);
        _Sprite_Actor_setBattler.call(this, battler);
        if (changed) {
            this._ssMotions = {};
            this.loadActorSsMotions(motion_suffixes);
        }
    };

    Sprite_Actor.prototype.loadActorSsMotions = function (motions) {
        for (var motion in motions) {
            this._ssMotions[motion] = null;
            this.loadSsMotion(this._actor.battlerName(), motion);
        }
    };

    Sprite_Actor.prototype.loadSsMotion = function (battlerName, motionSuffix) {
        var xhr = new XMLHttpRequest();
        var url = animationDir + battlerName + "_" + motionSuffix + ".json";
        xhr.open('GET', url);
        xhr.overrideMimeType('application/json');
        xhr.onload = function (motionSuffix) {
            if (xhr.status < 400) {
                var jsonData = JSON.parse(xhr.responseText)[0];
                var imageList = new SsImageList(jsonData.images, animationDir,
                    true);
                var animation = new SsAnimation(jsonData.animation, imageList);
                this._ssMotions[motionSuffix] = animation;
                // ロード完了コールバックがあれば実行
                if (typeof this.onSsMotionLoad === "function") {
                    this.onSsMotionLoad();
                }
            }
        } .bind(this, motionSuffix);
        xhr.send();
    };

    // 元スプライトのビットマップを無効化し、SsSpriteのモーション更新を行う
    Sprite_Actor.prototype.updateBitmap = function () {
        Sprite_Battler.prototype.updateBitmap.call(this);
        this._mainSprite.bitmap = null;
        this.updateSsMotion();
    };

    // オプションがONのとき、武器アニメーションを非表示に
    var _spriteActorSetupWeaponAnimation = Sprite_Actor.prototype.setupWeaponAnimation;
    Sprite_Actor.prototype.setupWeaponAnimation = function () {
        if (parameters["HideWeaponGraphics"].toUpperCase() === "OFF") {
            _spriteActorSetupWeaponAnimation.call(this);
        }
    };

    Sprite_Actor.prototype.updateSsMotion = function () {
        if (typeof this._motion === "object") {
            var motionName = "";
            for (var key in Sprite_Actor.MOTIONS) {
                if (this._motion === Sprite_Actor.MOTIONS[key])
                    motionName = key;
            }
            ;
            if (motionName === "") motionName = this._motion["index"];
            var newMotion = this._ssMotions[motionName];
            if (this._ssSprite.getAnimation() !== newMotion) {
                if (typeof this._ssMotions === "undefined")
                    return;
                this._ssSprite.setAnimation(newMotion);
                this._ssSprite.setLoop(Number(!this._motion["loop"]));
                if (this._motion["loop"] === false) {
                    this._ssSprite.setEndCallBack(function () {
                        this.refreshMotion();
                    } .bind(this));
                } else {
                    this._ssSprite.setEndCallBack(function () {
                    });
                }
                if (newMotion !== null)
                    this.onSsMotionLoad = null;
            }
        }
    };

    Sprite_Actor.prototype.updateMotionCount = function () {
        if (this._motion && this._ssSprite.isPlaying()) {
            this._motionCount = this._ssSprite.getFrameNo();
        } else {
            this.refreshMotion();
        }
    };

    var _Sprite_Actor_refreshMotion = Sprite_Actor.prototype.refreshMotion;
    Sprite_Actor.prototype.refreshMotion = function () {
        if (BattleManager.isBattleEnd()) {
            return;
        }
        _Sprite_Actor_refreshMotion.call(this);
    };

})();<|endoftext|>


<commit_before>// Serialize and unserialize the order form in parts, storing them in LocalStorage key/value store

// Save the current state of the order form
function cacheOrderForm() {
  // TODO: Check to see if there's an order form already and fail if so
  localStorage.setItem('orderform', $("form[name=orderform]").serialize());

  return true;
}

// Restore a saved state of the order form
function restoreOrderForm() {
  // Give the user a notice that the file upload was not saved

  // First, ensure we have the proper number of line items
  var data = localStorage.getItem('orderform');

  $("form[name=orderform]").unserializeForm(data, {
    'callback'  : function(el, val) {
      // TODO: Build the form dynamically here
      $(el).val(val); // just set the element for now
    }
  });
}

// Clear out a saved order form
function clearStoredOrderForm() {
  localStorage.removeItem("justification");
  localStorage.removeItem("vendor");
  localStorage.removeItem("shipping");
}

// TODO: UI/UX to prompt when leaving/loading page
<commit_msg>Progress on dynamic un-serializing<commit_after>// Serialize and unserialize the order form in parts, storing them in LocalStorage key/value store

// Save the current state of the order form
function cacheOrderForm() {
  // TODO: Check to see if there's an order form already and fail if so
  localStorage.setItem('orderform', $("form[name=orderform]").serialize());

  return true;
}

// Restore a saved state of the order form
function restoreOrderForm() {
  // Give the user a notice that the file upload was not saved

  // First, ensure we have the proper number of line items
  var data = localStorage.getItem('orderform');

  $("form[name=orderform]").unserializeForm(data, {
    'callback'  : function(el, val) {
      // Do we need to build a dynamic form?
      var match = /items\[([0-9]+)\].quantity/i.exec(el)
      if(match != null) {
        // Set a line-item. Form only has three by default. Add one if we see items[3] or greater.
        // Note that one line-item is a group of a few elements that will trigger the callback.
        // Only respond to items[?].quantity (arbitrary. we could respond to any single one in the group)
        if(parseInt(match[1]) > 2) {
          // found a line item that requires we expand the DOM

          // FIXME: This isn't correct. If we see a items[54], we need to ensure there are 54, not simply add
          // one that will create items[3].
          $("#add-line-item").trigger('click');

        }
      }

      $(el).val(val); // presuming any dynamic bits were created, set the element
    }
  });
}

// Clear out a saved order form
function clearStoredOrderForm() {
  localStorage.removeItem("orderform");
}

// TODO: Save automatically every five seconds
<|endoftext|>


<commit_before>//	***********************************************
//	WINE LIFE
//	DISCOVER WINDOW  - DiscoverWindow.js
//
//	MEN+1
//	Programmer:  Matthew Johnson
//	***********************************************

function DiscoverWindow(title) {
	var global = require('ui/common/globals');
	// Creates the default window with global color scheme
	var self = global.createWindow(title);

// create an array of anonymous objects
// Create an array of explicitly defined custom TableViewRows
var tbl_data = [];
for (var i = 0; i < 10; i++) {
	var row = Ti.UI.createTableViewRow({
		hasChild:true,
		height:90

	});
	// This image will be the image of the wine
		var image = Ti.UI.createImageView({
  		height: 80,
  		width: 80,
  		left: 10,
  		top:5,
  		borderColor: 'black',
		borderWidth: 1,
  		contentMode: 'aspectfill',
  		clipsToBounds: false,
  		image:'/images/logo.png',
  		layout:'vertical'
	});

	// This is the Label for the location of the wine within the row
	var lbl_location = Ti.UI.createLabel({
		left:'40%',
		color:global.colors.dark,
		bottom:10,
		text: "Wine Location",
		font:{fontSize:18,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		touchEnabled:false
	});

		// This is the label of the type of wine within the row
	var lbl_type = Ti.UI.createLabel({
		left:'40%',
		color:global.colors.dark,
		text: 'Wine Type',
		bottom:lbl_location.top,
		font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		touchEnabled:false

	});

	// This is the Label for the location of the wine within the row
	var lbl_date = Ti.UI.createLabel({
		right:5,
		top:5,
		color:global.colors.dark,
		text: "Date",
		font:{fontSize:12,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		touchEnabled:false
	});

	row.add(image);
	row.add(lbl_location);
	row.add(lbl_type);
	row.add(lbl_date);

	row.addEventListener('click', function() {
	var win_review = require('ui/handheld/WineReview');
		self.containingTab.open(win_review());
	});

	tbl_data.push(row);
}
// This is the tableview
var table = Titanium.UI.createTableView({
	backgroundColor:'transparent',
	top:0,
	width:'100%',
	height:'73%',

	data:tbl_data
});

	self.add(table);

	// This is the browse by color button
	var btn_bbc = Ti.UI.createButton({
		height:'20%',
		width:'42%',
		left:20,
		color: global.colors.dark,
		bottom:10,
		borderColor: global.colors.dark,
		borderRadius: 5,
		borderWidth: 1,
		backgroundColor: global.colors.lightest,
		backgroundImage: 'none'

	});
	// This label is the text for the browse by color button
	var lbl_bbc = Titanium.UI.createLabel({
    color:'black',
    font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
    highlightedColor:global.colors.dark,
    text:'Browse by Color',
    textAlign:'center',
    touchEnabled:false,
    bottom:10,
    left:btn_bbc.left,
    height:btn_bbc.height,
    width:btn_bbc.width
});

	self.add(btn_bbc);
	self.add(lbl_bbc);

	// This is the browse by style button
	var btn_bbs = Ti.UI.createButton({
		height:'20%',
		width:'42%',
		right:20,
		textAlign:'center',
		color: global.colors.dark,
		bottom:10,
		borderColor: global.colors.dark,
		borderRadius: 5,
		borderWidth: 1,
		backgroundColor: global.colors.lightest,
		backgroundImage: 'none'

	});

		// This label is the text for the browse by style button
	var lbl_bbs = Titanium.UI.createLabel({
    color:'black',
    font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
    highlightedColor:global.colors.dark,
    text:'Browse by Style',
    textAlign:'center',
    touchEnabled:false,
    bottom:10,
    right:btn_bbs.right,
    height:btn_bbs.height,
    width:btn_bbs.width
});

	self.add(btn_bbs);
	self.add(lbl_bbs);

	// Listener for Browse by Color
	btn_bbc.addEventListener('click', function() {
	var win_bbc = require('ui/handheld/BrowseByColor');
		self.containingTab.open(win_bbc());
	});
	// Listener for Browse by style
	btn_bbs.addEventListener('click', function() {
	var win_bbs = require('ui/handheld/BrowseByStyle');
		self.containingTab.open(win_bbs());
	});

	global.outputHook(self);
	return self;
};

module.exports = DiscoverWindow;<commit_msg>merging master<commit_after>//	***********************************************
//	WINE LIFE
//	DISCOVER WINDOW  - DiscoverWindow.js
//
//	MEN+1
//	Programmer:  Matthew Johnson
//	***********************************************

function DiscoverWindow(title) {
	var global = require('ui/common/globals');
	// Creates the default window with global color scheme
	var self = global.createWindow(title);

// create an array of anonymous objects
// Create an array of explicitly defined custom TableViewRows
var tbl_data = [];
for (var i = 0; i < 10; i++) {
	var row = Ti.UI.createTableViewRow({
		hasChild:true,
		height:90

	});
	// This image will be the image of the wine
		var image = Ti.UI.createImageView({
  		height: 80,
  		width: 80,
  		left: 10,
  		top:5,
  		borderColor: 'black',
		borderWidth: 1,
  		contentMode: 'aspectfill',
  		clipsToBounds: false,
  		image:'/images/logo.png',
  		layout:'vertical'
	});

	// This is the Label for the location of the wine within the row
	var lbl_location = Ti.UI.createLabel({
		left:'40%',
		color:global.colors.dark,
		bottom:10,
		text: "Wine Location",
		font:{fontSize:18,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		touchEnabled:false
	});

		// This is the label of the type of wine within the row
	var lbl_type = Ti.UI.createLabel({
		left:'40%',
		color:global.colors.dark,
		text: 'Wine Type',
		bottom:lbl_location.top,
		font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		touchEnabled:false

	});

	// This is the Label for the location of the date within the row
	var lbl_date = Ti.UI.createLabel({
		right:5,
		top:5,
		color:global.colors.dark,
		text: "Date",
		font:{fontSize:12,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		touchEnabled:false
	});

	row.add(image);
	row.add(lbl_location);
	row.add(lbl_type);
	row.add(lbl_date);

	row.addEventListener('click', function() {
	var win_review = require('ui/handheld/WineReview');
		self.containingTab.open(win_review());
	});

	tbl_data.push(row);
}
// This is the tableview
var table = Titanium.UI.createTableView({
	backgroundColor:'transparent',
	top:0,
	width:'100%',
	height:'73%',

	data:tbl_data
});

	self.add(table);

	// This is the browse by color button
	var btn_bbc = Ti.UI.createButton({
		height:'20%',
		width:'42%',
		left:20,
		color: global.colors.dark,
		bottom:10,
		borderColor: global.colors.dark,
		borderRadius: 5,
		borderWidth: 1,
		backgroundColor: global.colors.lightest,
		backgroundImage: 'none'

	});
	// This label is the text for the browse by color button
	var lbl_bbc = Titanium.UI.createLabel({
    color:'black',
    font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
    highlightedColor:global.colors.dark,
    text:'Browse by Color',
    textAlign:'center',
    touchEnabled:false,
    bottom:10,
    left:btn_bbc.left,
    height:btn_bbc.height,
    width:btn_bbc.width
});

	self.add(btn_bbc);
	self.add(lbl_bbc);

	// This is the browse by style button
	var btn_bbs = Ti.UI.createButton({
		height:'20%',
		width:'42%',
		right:20,
		textAlign:'center',
		color: global.colors.dark,
		bottom:10,
		borderColor: global.colors.dark,
		borderRadius: 5,
		borderWidth: 1,
		backgroundColor: global.colors.lightest,
		backgroundImage: 'none'

	});

		// This label is the text for the browse by style button
	var lbl_bbs = Titanium.UI.createLabel({
    color:'black',
    font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
    highlightedColor:global.colors.dark,
    text:'Browse by Style',
    textAlign:'center',
    touchEnabled:false,
    bottom:10,
    right:btn_bbs.right,
    height:btn_bbs.height,
    width:btn_bbs.width
});

	self.add(btn_bbs);
	self.add(lbl_bbs);

	// Listener for Browse by Color
	btn_bbc.addEventListener('click', function() {
	var win_bbc = require('ui/handheld/BrowseByColor');
		self.containingTab.open(win_bbc());
	});
	// Listener for Browse by style
	btn_bbs.addEventListener('click', function() {
	var win_bbs = require('ui/handheld/BrowseByStyle');
		self.containingTab.open(win_bbs());
	});

	global.outputHook(self);
	return self;
};

module.exports = DiscoverWindow;<|endoftext|>