<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Loadable from 'react-loadable';

import Spinner from '../Spinner';

const CODEMIRROR_BUFFER = 8;
const CODEMIRROR_LINE_HEIGHT = 17;
const CODEMIRROR_MIN_HEIGHT = 150;

const CODEMIRROR_CONFIG = {
  lineNumbers: true,
  tabSize: 2,
  mode: 'yaml',
  keyMap: 'sublime',
  theme: 'yaml',
  autoCloseBrackets: true,
  matchBrackets: true,
  showCursorWhenSelecting: true,
  viewportMargin: Infinity,
  gutters: ['CodeMirror-linenumbers'],
  extraKeys: {
    'Ctrl-Left': 'goSubwordLeft',
    'Ctrl-Right': 'goSubwordRight',
    'Alt-Left': 'goGroupLeft',
    'Alt-Right': 'goGroupRight'
  }
};

class FormYAMLEdtiorField extends React.Component {
  static propTypes = {
    name: PropTypes.string,
    value: PropTypes.string,
    CodeMirror: PropTypes.func
  };

  componentDidMount() {
    const { CodeMirror } = this.props;

    this.editor = CodeMirror.fromTextArea(
      this.input,
      CODEMIRROR_CONFIG
    );
  }

  componentWillUnmount() {
    if (this.editor) {
      this.editor.toTextArea();
      delete this.editor;
    }
  }

  render() {
    return (

        <textarea
          name={this.props.name}
          defaultValue={this.props.value}
          ref={(input) => this.input = input}
        />

    );
  }
}

const FormYAMLEdtiorFieldLoader = (props) => {
  // Here's a dynamic loader for editor that does some magical stuff. It tries
  // to attempt the size of the editor before we load it, this way the page
  // doesn't change in size after we load in Codemirror.
  const ApproximateHeightLoader = (loader) => {
    let contents;
    if (loader.error) {
      contents = (

          There was an error loading the editor. Please reload the page.

      );
    } else if (loader.pastDelay) {
      contents = (

          <Spinner /> Loading Editor…

      );
    } else {
      contents = null;
    }

    const lines = props.value.split("\n").length;
    let height = CODEMIRROR_BUFFER + (lines * CODEMIRROR_LINE_HEIGHT);
    if (CODEMIRROR_MIN_HEIGHT > height) {
      height = CODEMIRROR_MIN_HEIGHT;
    }

    return (

        {contents}

    );
  };

  ApproximateHeightLoader.propTypes = {
    value: PropTypes.string
  };

  // This loads Codemirror and all of its addons.
  const LoadableCodeMirror = Loadable.Map({
    loader: {
      CodeMirror: () => (
        import('./codemirror').then((module) => (
          // HACK: Add a "zero" delay after the module has
          // loaded, to allow their styles to take effect
          new Promise((resolve) => {
            setTimeout(() => resolve(module.default), 0);
          })
        ))
      )
    },

    loading() {
      return (
        <ApproximateHeightLoader />
      );
    },

    render(loaded, props) {
      return (
        <FormYAMLEdtiorField
          CodeMirror={loaded.CodeMirror}
          name={props.name}
          value={props.value}
        />
      );
    }
  });

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

FormYAMLEdtiorFieldLoader.propTypes = {
  name: PropTypes.string,
  value: PropTypes.string
};

export default FormYAMLEdtiorFieldLoader;
<commit_msg>Fixed eslint errors<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Loadable from 'react-loadable';

import Spinner from '../Spinner';

const CODEMIRROR_BUFFER = 8;
const CODEMIRROR_LINE_HEIGHT = 17;
const CODEMIRROR_MIN_HEIGHT = 150;

const CODEMIRROR_CONFIG = {
  lineNumbers: true,
  tabSize: 2,
  mode: 'yaml',
  keyMap: 'sublime',
  theme: 'yaml',
  autoCloseBrackets: true,
  matchBrackets: true,
  showCursorWhenSelecting: true,
  viewportMargin: Infinity,
  gutters: ['CodeMirror-linenumbers'],
  extraKeys: {
    'Ctrl-Left': 'goSubwordLeft',
    'Ctrl-Right': 'goSubwordRight',
    'Alt-Left': 'goGroupLeft',
    'Alt-Right': 'goGroupRight'
  }
};

class FormYAMLEdtiorField extends React.Component {
  static propTypes = {
    name: PropTypes.string,
    value: PropTypes.string,
    CodeMirror: PropTypes.func
  };

  componentDidMount() {
    const { CodeMirror } = this.props;

    this.editor = CodeMirror.fromTextArea(
      this.input,
      CODEMIRROR_CONFIG
    );
  }

  componentWillUnmount() {
    if (this.editor) {
      this.editor.toTextArea();
      delete this.editor;
    }
  }

  render() {
    return (

        <textarea
          name={this.props.name}
          defaultValue={this.props.value}
          ref={(input) => this.input = input}
        />

    );
  }
}

const FormYAMLEdtiorFieldLoader = (props) => {
  // Here's a dynamic loader for editor that does some magical stuff. It tries
  // to attempt the size of the editor before we load it, this way the page
  // doesn't change in size after we load in Codemirror.
  const ApproximateHeightLoader = (loader) => {
    let contents;
    if (loader.error) {
      contents = (

          There was an error loading the editor. Please reload the page.

      );
    } else if (loader.pastDelay) {
      contents = (

          <Spinner /> Loading Editor…

      );
    } else {
      contents = null;
    }

    const lines = props.value.split("\n").length;
    let height = CODEMIRROR_BUFFER + (lines * CODEMIRROR_LINE_HEIGHT);
    if (CODEMIRROR_MIN_HEIGHT > height) {
      height = CODEMIRROR_MIN_HEIGHT;
    }

    return (

        {contents}

    );
  };

  ApproximateHeightLoader.propTypes = {
    value: PropTypes.string
  };

  // This loads Codemirror and all of its addons.
  const LoadableCodeMirror = Loadable.Map({
    loader: {
      CodeMirror: () => (
        import('./codemirror').then((module) => (
          // HACK: Add a "zero" delay after the module has
          // loaded, to allow their styles to take effect
          new Promise((resolve) => {
            setTimeout(() => resolve(module.default), 0);
          })
        ))
      )
    },

    loading() {
      return (
        <ApproximateHeightLoader />
      );
    },

    render(loaded, props) {
      return (
        <FormYAMLEdtiorField
          CodeMirror={loaded.CodeMirror}
          name={props.name}
          value={props.value}
        />
      );
    }
  });

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

FormYAMLEdtiorFieldLoader.propTypes = {
  name: PropTypes.string,
  value: PropTypes.string
};

export default FormYAMLEdtiorFieldLoader;
<|endoftext|>


<commit_before>import lodash from 'lodash';
import Alert from 'react-s-alert';
import { getTokenFromLocalStorage } from '@src/utils/auth/authHelpers';

const checkHttpStatus = (response) => {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }

    const error = new Error(response.statusText);
    error.response = response;

    throw error;
};

const parseJSON = (response) => response.json();

const getRequestOptions = (customOptions = {}) => {
    const defaultFetchOptions = {
        method: 'get',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }
    };

    const token = getTokenFromLocalStorage();

    if (token) {
        defaultFetchOptions.headers.Authorization = `Bearer ${token}`;
    }

    const result = lodash.merge({}, defaultFetchOptions, customOptions);

    // In case of file uploads, its neccessary to delete `Content-Type`
    // so browser sets it implicitly along with `boundary`
    if (result.headers['Content-Type'] === '') {
        delete result.headers['Content-Type'];
    }

    return result;
};

export default function callApi({ path, options }) {
    return new Promise((resolve, reject) => {
        const rejectWithError = (message = 'An unexpected error has occured') => {
            Alert.error(message);
            reject(message);
        };

        fetch(process.env.REACT_APP_BACKEND_URL + path, getRequestOptions(options))
            .then(checkHttpStatus)
            .then(parseJSON)
            .then(({ data }) => {
                resolve(data);
            })
            .catch(({ response }) => {
                if (!response) {
                    rejectWithError();
                }
                else {
                    response.json()
                        .then(({ message }) => rejectWithError(message))
                        .catch(() => rejectWithError());
                }
            });
    });
};
<commit_msg>remove promise antipattern<commit_after>import lodash from 'lodash';
import Alert from 'react-s-alert';
import { getTokenFromLocalStorage } from '@src/utils/auth/authHelpers';

const checkHttpStatus = (response) => {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }

    const error = new Error(response.statusText);
    error.response = response;

    throw error;
};

const parseJSON = (response) => response.json();

const getRequestOptions = (customOptions = {}) => {
    const defaultFetchOptions = {
        method: 'get',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }
    };

    const token = getTokenFromLocalStorage();

    if (token) {
        defaultFetchOptions.headers.Authorization = `Bearer ${token}`;
    }

    const result = lodash.merge({}, defaultFetchOptions, customOptions);

    // In case of file uploads, its neccessary to delete `Content-Type`
    // so browser sets it implicitly along with `boundary`
    if (result.headers['Content-Type'] === '') {
        delete result.headers['Content-Type'];
    }

    return result;
};

export default function callApi({ path, options }) {
    const throwError = (message = 'An unexpected error has occured') => {
        Alert.error(message);
        throw new Error(message);
    };

    return fetch(process.env.REACT_APP_BACKEND_URL + path, getRequestOptions(options))
        .then(checkHttpStatus)
        .then(parseJSON)
        .then(({ data }) => data)
        .catch(({ response }) => {
            if (!response) {
                return throwError();
            }
            else {
                return response.json()
                    .then(({ message }) => Promise.reject(message))
                    .catch((err) => throwError(err));
            }
        });
};
<|endoftext|>


<commit_before>// Note the new way of requesting CoffeeScript since 1.7.x
require('coffee-script/register');
// This bootstraps your Gulp's main file
require('./gulpfile.coffee');
<commit_msg>remove unneeded gulpfile.js<commit_after><|endoftext|>


<commit_before>var common     = require('../../common');
var connection = common.createConnection();
var assert     = require('assert');

// usually default MAX_PREPARED_STATEMENTS on server is 16384
// check close() actually works by preparing more then MAX
// (connection has only one prepared ata a time)
var max = 170;
var start = process.hrtime();
function prepare(i) {
  connection.prepare('select 1+' + i, function(err, stmt) {
    stmt.close();
    if (!err) {
      if (i > max) {
        var end = process.hrtime(start);
        var ns = end[0]*1e9+end[1];
        console.log(max*1e9/ns + ' prepares/sec');
        return connection.end();
      }
      setTimeout(function() {prepare(i+1)}, 2);
      return;
    }
    assert(0, 'Error in prepare!');
  });
}
connection.query('SET GLOBAL max_prepared_stmt_count=10', function(err) {
  if (err) throw err;
  prepare(1);
});
<commit_msg>bump max statements<commit_after>var common     = require('../../common');
var connection = common.createConnection();
var assert     = require('assert');

// usually default MAX_PREPARED_STATEMENTS on server is 16384
// check close() actually works by preparing more then MAX
// (connection has only one prepared ata a time)
var max = 500;
var start = process.hrtime();
function prepare(i) {
  connection.prepare('select 1+' + i, function(err, stmt) {
    stmt.close();
    if (!err) {
      if (i > max) {
        var end = process.hrtime(start);
        var ns = end[0]*1e9+end[1];
        console.log(max*1e9/ns + ' prepares/sec');
        return connection.end();
      }
      setTimeout(function() {prepare(i+1)}, 2);
      return;
    }
    assert(0, 'Error in prepare!');
  });
}
connection.query('SET GLOBAL max_prepared_stmt_count=10', function(err) {
  if (err) throw err;
  prepare(1);
});
<|endoftext|>


<commit_before>'use babel';

import _ from 'lodash';

const getTypTemplate = () => (
`/* @flow */
import type {
  ComponentType,
  ComponentPropsType,
  MapStateToPropsType,
  MapDispatchToPropsType
} from 'types/types';

export type OwnProps = {|
  className?: string,
|};

/* set to void if not used*/
export type StateProps = {|
  className: ?string,
|};

/* set to void if not used*/
export type DispatchProps = {|

|};

export type MapStateToProps = MapStateToPropsType<StateProps>;
export type MapDispatchToProps = MapDispatchToPropsType<DispatchProps>;
export type Props = ComponentPropsType<StateProps, DispatchProps>
export type Component = ComponentType<OwnProps>;

`
);

const getContainerTemplate = name => (
`/* @flow */
import { connect } from 'react-redux';
import ${name} from './${name}.cmp';

import type {
  OwnProps,
  MapStateToProps,
  MapDispatchToProps,
  Component
} from './${name}.typ';

const mapStateToProps: MapStateToProps = (state, ownProps: OwnProps) => ({
  className: ownProps.className,
});

const mapDispatchToProps: MapDispatchToProps = dispatch => ({

});

const connector = connect(mapStateToProps, mapDispatchToProps);
const component: Component = connector(${name});

export default component;
`
);

const getComponentTemplate = (name) => {
  const baseComponent = atom.config.get('davs-package.baseComponent');
  const importEntity = baseComponent === 'Entity';

  return (
`/* @flow */
import React from 'react';\
${importEntity ? '\nimport { Entity } from \'aframe-react\';' : ''}
import type { Props } from './${name}.typ';

const ${name} = (props: Props) => (
  <${baseComponent} className={\`${_.kebabCase(name)} \${props.className || ''}\`}>

  </${baseComponent}>
);

export default ${name};
`
  );
};

const getCssTemplate = name => (
`.${_.kebabCase(name)}{}
`
);

const getDuckTemplate = (name) => {
  const rootPath = atom.project.getPaths()[0];
  const projectName = rootPath.split('\\').pop();
  return (
`const ACTION = '${projectName}/${name}/ACTION';

const initialState = {};

const ${name} = (state = initialState, action = {}) => {
  switch (action.type) {
    case ACTION:
      return { ...state };
    default:
      return state;
  }
};

export const action = () => ({
  type: ACTION,
});

export default ${name};
`
  );
};

const getDuckSpecTemplate = name => (
`import * as duck from './${name}';

const reducer = duck.default;

describe('${name} duck', () => {
  const initialState = reducer(undefined, {});

  it('should exist', () => {
    expect(reducer).toBeDefined();
  });
  /*
  it('should return the initialState', () => {
    expect(initialState.<SOMETHING>).toBe(<SOMETHING>);
  });
  */

  /*
  describe('ACTIONS', () => {
    describe('<ACTION_NAME>', () => {
      const action = duck.<actionName>();
      const actionConst = duck.<ACTION_NAME>;

      it('should exist', () => {
        expect(duck.<actionName>).toBeDefined();
      });
      it('should generate the correct action', () => {
        const expectedAction = {
          type: actionConst,
        };
        expect(action).toEqual(expectedAction);
      });
      it('should be handled by the reducer', () => {
        const newState = reducer(initialState, action);
        expect(newState.<SOMETHING>).toBe(<SOMETHING>);
      });
    });
  });
  */

  /*
  describe('SELECTORS', () => {
    const state = {
      ${name}: {
        <SOMETHING>: <SOMETHING>,
      },
    };

    describe('<selectorName>', () => {
      const selector = duck.<selectorName>;

      it('should exist', () => {
        expect(selector).toBeDefined();
      });
      it('should select <SOMETHING>', () => {
        expect(selector(state)).toBe(<SOMETHING>);
      });
    });
  });
  */
});
`
);

const getServiceTemplate = name => (
`/* @flow */
/* const <serviceFunction> = () => <something> */

const ${name}Service = {
  /* <serviceFunction> */
};

export default ${name}Service;
`
);

const getServiceSpecTemplate = name => (
`import ${name}Service from './${name}';

describe('${name}Service', () => {
  it('should exist', () => {
    expect(${name}Service).toBeDefined();
  });

  /*
  describe('<serviceFunction>', () => {
    const <serviceFunction>' = geometryService.<serviceFunction>';

    it('should exist', () => {
      expect(<serviceFunction>).toBeDefined();
    });
  });
  */
});
`
);

const getTypeTemplate = name => (
`/* @flow */
export type ${name} = {|

|};
`
);

const templatesService = {
  getTypTemplate,
  getContainerTemplate,
  getComponentTemplate,
  getCssTemplate,
  getDuckTemplate,
  getDuckSpecTemplate,
  getServiceTemplate,
  getServiceSpecTemplate,
  getTypeTemplate,
};
export default templatesService;
<commit_msg>removed comments from typ files<commit_after>'use babel';

import _ from 'lodash';

const getTypTemplate = () => (
`/* @flow */
import type {
  ComponentType,
  ComponentPropsType,
  MapStateToPropsType,
  MapDispatchToPropsType
} from 'types/types';

export type OwnProps = {|
  className?: string,
|};

export type StateProps = {|
  className: ?string,
|};

export type DispatchProps = {|

|};

export type MapStateToProps = MapStateToPropsType<StateProps>;
export type MapDispatchToProps = MapDispatchToPropsType<DispatchProps>;
export type Props = ComponentPropsType<StateProps, DispatchProps>
export type Component = ComponentType<OwnProps>;

`
);

const getContainerTemplate = name => (
`/* @flow */
import { connect } from 'react-redux';
import ${name} from './${name}.cmp';

import type {
  OwnProps,
  MapStateToProps,
  MapDispatchToProps,
  Component
} from './${name}.typ';

const mapStateToProps: MapStateToProps = (state, ownProps: OwnProps) => ({
  className: ownProps.className,
});

const mapDispatchToProps: MapDispatchToProps = dispatch => ({

});

const connector = connect(mapStateToProps, mapDispatchToProps);
const component: Component = connector(${name});

export default component;
`
);

const getComponentTemplate = (name) => {
  const baseComponent = atom.config.get('davs-package.baseComponent');
  const importEntity = baseComponent === 'Entity';

  return (
`/* @flow */
import React from 'react';\
${importEntity ? '\nimport { Entity } from \'aframe-react\';' : ''}
import type { Props } from './${name}.typ';

const ${name} = (props: Props) => (
  <${baseComponent} className={\`${_.kebabCase(name)} \${props.className || ''}\`}>

  </${baseComponent}>
);

export default ${name};
`
  );
};

const getCssTemplate = name => (
`.${_.kebabCase(name)}{}
`
);

const getDuckTemplate = (name) => {
  const rootPath = atom.project.getPaths()[0];
  const projectName = rootPath.split('\\').pop();
  return (
`const ACTION = '${projectName}/${name}/ACTION';

const initialState = {};

const ${name} = (state = initialState, action = {}) => {
  switch (action.type) {
    case ACTION:
      return { ...state };
    default:
      return state;
  }
};

export const action = () => ({
  type: ACTION,
});

export default ${name};
`
  );
};

const getDuckSpecTemplate = name => (
`import * as duck from './${name}';

const reducer = duck.default;

describe('${name} duck', () => {
  const initialState = reducer(undefined, {});

  it('should exist', () => {
    expect(reducer).toBeDefined();
  });
  /*
  it('should return the initialState', () => {
    expect(initialState.<SOMETHING>).toBe(<SOMETHING>);
  });
  */

  /*
  describe('ACTIONS', () => {
    describe('<ACTION_NAME>', () => {
      const action = duck.<actionName>();
      const actionConst = duck.<ACTION_NAME>;

      it('should exist', () => {
        expect(duck.<actionName>).toBeDefined();
      });
      it('should generate the correct action', () => {
        const expectedAction = {
          type: actionConst,
        };
        expect(action).toEqual(expectedAction);
      });
      it('should be handled by the reducer', () => {
        const newState = reducer(initialState, action);
        expect(newState.<SOMETHING>).toBe(<SOMETHING>);
      });
    });
  });
  */

  /*
  describe('SELECTORS', () => {
    const state = {
      ${name}: {
        <SOMETHING>: <SOMETHING>,
      },
    };

    describe('<selectorName>', () => {
      const selector = duck.<selectorName>;

      it('should exist', () => {
        expect(selector).toBeDefined();
      });
      it('should select <SOMETHING>', () => {
        expect(selector(state)).toBe(<SOMETHING>);
      });
    });
  });
  */
});
`
);

const getServiceTemplate = name => (
`/* @flow */
/* const <serviceFunction> = () => <something> */

const ${name}Service = {
  /* <serviceFunction> */
};

export default ${name}Service;
`
);

const getServiceSpecTemplate = name => (
`import ${name}Service from './${name}';

describe('${name}Service', () => {
  it('should exist', () => {
    expect(${name}Service).toBeDefined();
  });

  /*
  describe('<serviceFunction>', () => {
    const <serviceFunction>' = geometryService.<serviceFunction>';

    it('should exist', () => {
      expect(<serviceFunction>).toBeDefined();
    });
  });
  */
});
`
);

const getTypeTemplate = name => (
`/* @flow */
export type ${name} = {|

|};
`
);

const templatesService = {
  getTypTemplate,
  getContainerTemplate,
  getComponentTemplate,
  getCssTemplate,
  getDuckTemplate,
  getDuckSpecTemplate,
  getServiceTemplate,
  getServiceSpecTemplate,
  getTypeTemplate,
};
export default templatesService;
<|endoftext|>


<commit_before>var reddit = global.reddit;

// reddit._addSimpleRequest = function(name, endpoint, method, args, constArgs, callback)
// reddit._addListingRequest = function(name, endpoint, path, args, cb)

reddit._addSimpleRequest("block", "block", "POST", ["id"], null, "_noResponse");

reddit.prototype.message = function(options, callback) {
	var self = this;
	this._apiRequest("compose", {"method": "POST", "form": {
		"api_type": "json",
		"iden": (options.captcha) ? self._captchaIdent : undefined,
		"captcha": options.captcha,
		"to": options.to,
		"subject": options.subject,
		"text": options.text
	}}, function(err, response, body) {
		self._multipleErrors(err, body, callback);
	});
};

reddit.prototype.markRead = function(ids, callback) {
	if(typeof ids == 'object') {
		ids = ids.join(',');
	}

	var self = this;
	this._apiRequest("read_message", {"method": "POST", "form": {"id": ids}}, function(err, response, body) {
		self._noResponse(err, body, callback);
	});
};

reddit.prototype.markUnread = function(ids, callback) {
	if(typeof ids == 'object') {
		ids = ids.join(',');
	}

	var self = this;
	this._apiRequest("unread_message", {"method": "POST", "form": {"id": ids}}, function(err, response, body) {
		self._noResponse(err, body, callback);
	});
};

reddit._addListingRequest("inbox", "inbox.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("unread", "unread.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("sent", "sent.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("messages", "messages.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("commentReplies", "comments.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("postReplies", "selfreply.json", "/message", ["mark", "mid"]);<commit_msg>Added mentions method<commit_after>var reddit = global.reddit;

// reddit._addSimpleRequest = function(name, endpoint, method, args, constArgs, callback)
// reddit._addListingRequest = function(name, endpoint, path, args, cb)

reddit._addSimpleRequest("block", "block", "POST", ["id"], null, "_noResponse");

reddit.prototype.message = function(options, callback) {
	var self = this;
	this._apiRequest("compose", {"method": "POST", "form": {
		"api_type": "json",
		"iden": (options.captcha) ? self._captchaIdent : undefined,
		"captcha": options.captcha,
		"to": options.to,
		"subject": options.subject,
		"text": options.text
	}}, function(err, response, body) {
		self._multipleErrors(err, body, callback);
	});
};

reddit.prototype.markRead = function(ids, callback) {
	if(typeof ids == 'object') {
		ids = ids.join(',');
	}

	var self = this;
	this._apiRequest("read_message", {"method": "POST", "form": {"id": ids}}, function(err, response, body) {
		self._noResponse(err, body, callback);
	});
};

reddit.prototype.markUnread = function(ids, callback) {
	if(typeof ids == 'object') {
		ids = ids.join(',');
	}

	var self = this;
	this._apiRequest("unread_message", {"method": "POST", "form": {"id": ids}}, function(err, response, body) {
		self._noResponse(err, body, callback);
	});
};

reddit._addListingRequest("inbox", "inbox.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("unread", "unread.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("sent", "sent.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("messages", "messages.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("commentReplies", "comments.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("postReplies", "selfreply.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("mentions", "mentions.json", "/message", ["mark", "mid"]);<|endoftext|>


<commit_before>var Class = require('../utils/Class');
var Extend = require('../utils/object/Extend');
var EventDispatcher = require('../events/EventDispatcher');
var NOOP = require('../utils/NOOP');
/*!
 * @author Pavle Goloskokovic <pgoloskokovic@gmail.com> (http://prunegames.com)
 */
var BaseSound = new Class({
    /**
     * @class Phaser.Sound.BaseSound
     * @constructor
     * @param {ISoundManager} manager - Reference to the current sound manager instance.
     * @param {string} key - Asset key for the sound.
     * @param {ISoundConfig} [config] - An optional config object containing default sound settings.
     */
    initialize: function BaseSound(manager, key, config) {
        /**
         * Local reference to the sound manager.
         *
         * @private
         * @property {Phaser.Sound.BaseSoundManager} manager
         */
        this.manager = manager;
        /**
         * Asset key for the sound.
         *
         * @readonly
         * @property {string} key
         */
        this.key = key;
        /**
         * Event dispatcher used to handle all sound instance relevant events.
         *
         * @readonly
         * @property {Phaser.Events.EventDispatcher}
         */
        this.events = new EventDispatcher();
        /**
         * Flag indicating if sound is currently playing.
         *
         * @readonly
         * @property {boolean} isPlaying
         */
        this.isPlaying = false;
        /**
         * Flag indicating if sound is currently paused.
         *
         * @readonly
         * @property {boolean} isPaused
         */
        this.isPaused = false;
        /**
         * A property that holds the value of sound's actual playback rate,
         * after its rate and detune values has been combined with global
         * rate and detune values.
         *
         * @readonly
         * @property {number} totalRate
         */
        this.totalRate = 1;
        /**
         * A value representing the duration, in seconds.
         * It could be total sound duration or a marker duration.
         *
         * @readonly
         * @property {number} duration
         */
        this.duration = this.duration || 0;
        /**
         * The total duration of the sound in seconds.
         *
         * @readonly
         * @property {number}
         */
        this.totalDuration = this.totalDuration || 0;
        /**
         * A config object used to store default sound settings' values.
         * Default values will be set by properties' setters.
         *
         * @private
         * @property {ISoundConfig} config
         */
        this.config = {
            /**
             * Initializing delay config setting
             */
            delay: 0
        };
        /**
         * Reference to the currently used config.
         * It could be default config or marker config.
         *
         * @private
         * @property {ISoundConfig} currentConfig
         */
        this.currentConfig = this.config;
        /**
         * Boolean indicating whether the sound is muted or not.
         * Gets or sets the muted state of this sound.
         *
         * @property {boolean} mute
         */
        this.mute = false;
        /**
         * Gets or sets the volume of this sound,
         * a value between 0 (silence) and 1 (full volume).
         *
         * @property {number} volume
         */
        this.volume = 1;
        /**
         * Defines the speed at which the audio asset will be played.
         * Value of 1.0 plays the audio at full speed, 0.5 plays the audio
         * at half speed and 2.0 doubles the audio's playback speed.
         * This value gets multiplied by global rate to have the final playback speed.
         *
         * @property {number} rate
         */
        this.rate = 1;
        /**
         * Represents detuning of sound in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
         * The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
         *
         * @property {number} detune
         */
        this.detune = 0;
        /**
         * Property representing the position of playback for this sound, in seconds.
         * Setting it to a specific value moves current playback to that position.
         * The value given is clamped to the range 0 to current marker duration.
         * Setting seek of a stopped sound has no effect.
         *
         * @property {number} seek
         */
        this.seek = 0;
        /**
         * Flag indicating whether or not the sound or current sound marker will loop.
         *
         * @property {boolean} loop
         */
        this.loop = false;
        this.config = Extend(this.config, config);
        /**
         * Object containing markers definitions.
         *
         * @readonly
         * @property {{}} markers
         */
        this.markers = {};
        /**
         * Currently playing marker.
         * 'null' if whole sound is playing.
         *
         * @readonly
         * @property {ISoundMarker} currentMarker
         */
        this.currentMarker = null;
        /**
         * Flag indicating if destroy method was called on this sound.
         *
         * @private
         * @property {boolean} pendingRemove
         */
        this.pendingRemove = false;
    },
    /**
     * Adds a marker into the current sound. A marker is represented by name, start time, duration, and optionally config object.
     * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback.
     *
     * @method Phaser.Sound.BaseSound#addMarker
     * @param {ISoundMarker} marker - Marker object
     * @returns {boolean} Whether the marker was added successfully
     */
    addMarker: function (marker) {
        if (!marker) {
            console.error('addMarker - Marker object has to be provided!');
            return false;
        }
        if (!marker.name || typeof marker.name !== 'string') {
            console.error('addMarker - Marker has to have a valid name!');
            return false;
        }
        if (this.markers[marker.name]) {
            console.error('addMarker - Marker with name \'' + marker.name + '\' already exists for sound \'' + this.key + '\'!');
            return false;
        }
        marker = Extend(true, {
            name: '',
            start: 0,
            duration: this.totalDuration,
            config: {
                mute: false,
                volume: 1,
                rate: 1,
                detune: 0,
                seek: 0,
                loop: false,
                delay: 0
            }
        }, marker);
        this.markers[marker.name] = marker;
        return true;
    },
    updateMarker: function (marker) {
        if (!marker) {
            console.error('updateMarker - Marker object has to be provided!');
            return false;
        }
        if (!marker.name || typeof marker.name !== 'string') {
            console.error('updateMarker - Marker has to have a valid name!');
            return false;
        }
        if (!this.markers[marker.name]) {
            console.error('updateMarker - Marker with name \'' + marker.name + '\' does not exist for sound \'' + this.key + '\'!');
            return false;
        }
        this.markers[marker.name] = Extend(true, this.markers[marker.name], marker);
        return true;
    },
    removeMarker: function (markerName) {
        var marker = this.markers[markerName];
        if (!marker) {
            console.error('removeMarker - Marker with name \'' + marker.name + '\' does not exist for sound \'' + this.key + '\'!');
            return null;
        }
        this.markers[markerName] = null;
        return marker;
    },
    play: function (markerName, config) {
        if (markerName === void 0) { markerName = ''; }
        if (typeof markerName === 'object') {
            config = markerName;
            markerName = '';
        }
        if (typeof markerName !== 'string') {
            console.error('Sound marker name has to be a string!');
            return null;
        }
        if (!markerName) {
            this.currentMarker = null;
            this.currentConfig = this.config;
            this.duration = this.totalDuration;
        }
        else {
            if (!this.markers[markerName]) {
                console.error('No marker with name \'' + markerName + '\' found for sound \'' + this.key + '\'!');
                return null;
            }
            this.currentMarker = this.markers[markerName];
            this.currentConfig = this.currentMarker.config;
            this.duration = this.currentMarker.duration;
        }
        this.resetConfig();
        this.currentConfig = Extend(this.currentConfig, config);
        this.isPlaying = true;
        this.isPaused = false;
        return this;
    },
    pause: function () {
        if (this.isPaused || !this.isPlaying) {
            return false;
        }
        this.isPlaying = false;
        this.isPaused = true;
        return true;
    },
    resume: function () {
        if (!this.isPaused || this.isPlaying) {
            return false;
        }
        this.isPlaying = true;
        this.isPaused = false;
        return true;
    },
    stop: function () {
        if (!this.isPaused && !this.isPlaying) {
            return false;
        }
        this.isPlaying = false;
        this.isPaused = false;
        this.resetConfig();
        return true;
    },
    /**
     * @protected
     */
    applyConfig: function () {
        this.mute = this.currentConfig.mute;
        this.volume = this.currentConfig.volume;
        this.rate = this.currentConfig.rate;
        this.detune = this.currentConfig.detune;
        this.loop = this.currentConfig.loop;
    },
    /**
     * @protected
     */
    resetConfig: function () {
        this.currentConfig.seek = 0;
        this.currentConfig.delay = 0;
    },
    /**
     * @protected
     */
    update: NOOP,
    destroy: function () {
        if (this.pendingRemove) {
            return;
        }
        this.pendingRemove = true;
        this.manager = null;
        this.key = '';
        this.events.destroy();
        this.events = null;
        this.isPlaying = false;
        this.isPaused = false;
        this.config = null;
        this.currentConfig = null;
        this.markers = null;
        this.currentMarker = null;
    },
    /**
     * @protected
     */
    setRate: function () {
        var cent = 1.0005777895065548; // Math.pow(2, 1/1200);
        var totalDetune = this.currentConfig.detune + this.manager.detune;
        var detuneRate = Math.pow(cent, totalDetune);
        this.totalRate = this.currentConfig.rate * this.manager.rate * detuneRate;
    }
});
module.exports = BaseSound;
<commit_msg>Added updateMarker method docs<commit_after>var Class = require('../utils/Class');
var Extend = require('../utils/object/Extend');
var EventDispatcher = require('../events/EventDispatcher');
var NOOP = require('../utils/NOOP');
/*!
 * @author Pavle Goloskokovic <pgoloskokovic@gmail.com> (http://prunegames.com)
 */
var BaseSound = new Class({
    /**
     * @class Phaser.Sound.BaseSound
     * @constructor
     * @param {ISoundManager} manager - Reference to the current sound manager instance.
     * @param {string} key - Asset key for the sound.
     * @param {ISoundConfig} [config] - An optional config object containing default sound settings.
     */
    initialize: function BaseSound(manager, key, config) {
        /**
         * Local reference to the sound manager.
         *
         * @private
         * @property {Phaser.Sound.BaseSoundManager} manager
         */
        this.manager = manager;
        /**
         * Asset key for the sound.
         *
         * @readonly
         * @property {string} key
         */
        this.key = key;
        /**
         * Event dispatcher used to handle all sound instance relevant events.
         *
         * @readonly
         * @property {Phaser.Events.EventDispatcher}
         */
        this.events = new EventDispatcher();
        /**
         * Flag indicating if sound is currently playing.
         *
         * @readonly
         * @property {boolean} isPlaying
         */
        this.isPlaying = false;
        /**
         * Flag indicating if sound is currently paused.
         *
         * @readonly
         * @property {boolean} isPaused
         */
        this.isPaused = false;
        /**
         * A property that holds the value of sound's actual playback rate,
         * after its rate and detune values has been combined with global
         * rate and detune values.
         *
         * @readonly
         * @property {number} totalRate
         */
        this.totalRate = 1;
        /**
         * A value representing the duration, in seconds.
         * It could be total sound duration or a marker duration.
         *
         * @readonly
         * @property {number} duration
         */
        this.duration = this.duration || 0;
        /**
         * The total duration of the sound in seconds.
         *
         * @readonly
         * @property {number}
         */
        this.totalDuration = this.totalDuration || 0;
        /**
         * A config object used to store default sound settings' values.
         * Default values will be set by properties' setters.
         *
         * @private
         * @property {ISoundConfig} config
         */
        this.config = {
            /**
             * Initializing delay config setting
             */
            delay: 0
        };
        /**
         * Reference to the currently used config.
         * It could be default config or marker config.
         *
         * @private
         * @property {ISoundConfig} currentConfig
         */
        this.currentConfig = this.config;
        /**
         * Boolean indicating whether the sound is muted or not.
         * Gets or sets the muted state of this sound.
         *
         * @property {boolean} mute
         */
        this.mute = false;
        /**
         * Gets or sets the volume of this sound,
         * a value between 0 (silence) and 1 (full volume).
         *
         * @property {number} volume
         */
        this.volume = 1;
        /**
         * Defines the speed at which the audio asset will be played.
         * Value of 1.0 plays the audio at full speed, 0.5 plays the audio
         * at half speed and 2.0 doubles the audio's playback speed.
         * This value gets multiplied by global rate to have the final playback speed.
         *
         * @property {number} rate
         */
        this.rate = 1;
        /**
         * Represents detuning of sound in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
         * The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
         *
         * @property {number} detune
         */
        this.detune = 0;
        /**
         * Property representing the position of playback for this sound, in seconds.
         * Setting it to a specific value moves current playback to that position.
         * The value given is clamped to the range 0 to current marker duration.
         * Setting seek of a stopped sound has no effect.
         *
         * @property {number} seek
         */
        this.seek = 0;
        /**
         * Flag indicating whether or not the sound or current sound marker will loop.
         *
         * @property {boolean} loop
         */
        this.loop = false;
        this.config = Extend(this.config, config);
        /**
         * Object containing markers definitions.
         *
         * @readonly
         * @property {{}} markers
         */
        this.markers = {};
        /**
         * Currently playing marker.
         * 'null' if whole sound is playing.
         *
         * @readonly
         * @property {ISoundMarker} currentMarker
         */
        this.currentMarker = null;
        /**
         * Flag indicating if destroy method was called on this sound.
         *
         * @private
         * @property {boolean} pendingRemove
         */
        this.pendingRemove = false;
    },
    /**
     * Adds a marker into the current sound. A marker is represented by name, start time, duration, and optionally config object.
     * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback.
     *
     * @method Phaser.Sound.BaseSound#addMarker
     * @param {ISoundMarker} marker - Marker object
     * @returns {boolean} Whether the marker was added successfully
     */
    addMarker: function (marker) {
        if (!marker) {
            console.error('addMarker - Marker object has to be provided!');
            return false;
        }
        if (!marker.name || typeof marker.name !== 'string') {
            console.error('addMarker - Marker has to have a valid name!');
            return false;
        }
        if (this.markers[marker.name]) {
            console.error('addMarker - Marker with name \'' + marker.name + '\' already exists for sound \'' + this.key + '\'!');
            return false;
        }
        marker = Extend(true, {
            name: '',
            start: 0,
            duration: this.totalDuration,
            config: {
                mute: false,
                volume: 1,
                rate: 1,
                detune: 0,
                seek: 0,
                loop: false,
                delay: 0
            }
        }, marker);
        this.markers[marker.name] = marker;
        return true;
    },
    /**
     * Updates previously added marker.
     *
     * @method Phaser.Sound.BaseSound#updateMarker
     * @param {ISoundMarker} marker - Marker object with updated values.
     * @returns {boolean} Whether the marker was updated successfully.
     */
    updateMarker: function (marker) {
        if (!marker) {
            console.error('updateMarker - Marker object has to be provided!');
            return false;
        }
        if (!marker.name || typeof marker.name !== 'string') {
            console.error('updateMarker - Marker has to have a valid name!');
            return false;
        }
        if (!this.markers[marker.name]) {
            console.error('updateMarker - Marker with name \'' + marker.name + '\' does not exist for sound \'' + this.key + '\'!');
            return false;
        }
        this.markers[marker.name] = Extend(true, this.markers[marker.name], marker);
        return true;
    },
    removeMarker: function (markerName) {
        var marker = this.markers[markerName];
        if (!marker) {
            console.error('removeMarker - Marker with name \'' + marker.name + '\' does not exist for sound \'' + this.key + '\'!');
            return null;
        }
        this.markers[markerName] = null;
        return marker;
    },
    play: function (markerName, config) {
        if (markerName === void 0) { markerName = ''; }
        if (typeof markerName === 'object') {
            config = markerName;
            markerName = '';
        }
        if (typeof markerName !== 'string') {
            console.error('Sound marker name has to be a string!');
            return null;
        }
        if (!markerName) {
            this.currentMarker = null;
            this.currentConfig = this.config;
            this.duration = this.totalDuration;
        }
        else {
            if (!this.markers[markerName]) {
                console.error('No marker with name \'' + markerName + '\' found for sound \'' + this.key + '\'!');
                return null;
            }
            this.currentMarker = this.markers[markerName];
            this.currentConfig = this.currentMarker.config;
            this.duration = this.currentMarker.duration;
        }
        this.resetConfig();
        this.currentConfig = Extend(this.currentConfig, config);
        this.isPlaying = true;
        this.isPaused = false;
        return this;
    },
    pause: function () {
        if (this.isPaused || !this.isPlaying) {
            return false;
        }
        this.isPlaying = false;
        this.isPaused = true;
        return true;
    },
    resume: function () {
        if (!this.isPaused || this.isPlaying) {
            return false;
        }
        this.isPlaying = true;
        this.isPaused = false;
        return true;
    },
    stop: function () {
        if (!this.isPaused && !this.isPlaying) {
            return false;
        }
        this.isPlaying = false;
        this.isPaused = false;
        this.resetConfig();
        return true;
    },
    /**
     * @protected
     */
    applyConfig: function () {
        this.mute = this.currentConfig.mute;
        this.volume = this.currentConfig.volume;
        this.rate = this.currentConfig.rate;
        this.detune = this.currentConfig.detune;
        this.loop = this.currentConfig.loop;
    },
    /**
     * @protected
     */
    resetConfig: function () {
        this.currentConfig.seek = 0;
        this.currentConfig.delay = 0;
    },
    /**
     * @protected
     */
    update: NOOP,
    destroy: function () {
        if (this.pendingRemove) {
            return;
        }
        this.pendingRemove = true;
        this.manager = null;
        this.key = '';
        this.events.destroy();
        this.events = null;
        this.isPlaying = false;
        this.isPaused = false;
        this.config = null;
        this.currentConfig = null;
        this.markers = null;
        this.currentMarker = null;
    },
    /**
     * @protected
     */
    setRate: function () {
        var cent = 1.0005777895065548; // Math.pow(2, 1/1200);
        var totalDetune = this.currentConfig.detune + this.manager.detune;
        var detuneRate = Math.pow(cent, totalDetune);
        this.totalRate = this.currentConfig.rate * this.manager.rate * detuneRate;
    }
});
module.exports = BaseSound;
<|endoftext|>


<commit_before>import axios from 'axios'
import { getToken, isLogged } from '../services/auth'

const api = axios.create({
  baseURL: 'https://staging.ritoplz.com',
  headers: {
    Accept: 'application/json'
  }
})

api.interceptors.request.use(config => {
  const token = getToken()

  if (isLogged()) {
    config.headers['authorization'] = token
  }

  return config
})

api.interceptors.response.use(response => {
  if (response.data) {
    return response.data
  } else {
    return response
  }
}, error => {
  if (error.response && error.response.data) {
    return Promise.reject(error.response.data.error)
  } else {
    return Promise.reject(error)
  }
})

export default api
<commit_msg>Update api.js<commit_after>import axios from 'axios'
import { getToken, isLogged } from '../services/auth'

const api = axios.create({
  baseURL: 'https://api.ritoplz.com',
  headers: {
    Accept: 'application/json'
  }
})

api.interceptors.request.use(config => {
  const token = getToken()

  if (isLogged()) {
    config.headers['authorization'] = token
  }

  return config
})

api.interceptors.response.use(response => {
  if (response.data) {
    return response.data
  } else {
    return response
  }
}, error => {
  if (error.response && error.response.data) {
    return Promise.reject(error.response.data.error)
  } else {
    return Promise.reject(error)
  }
})

export default api
<|endoftext|>


<commit_before>/* global Matrix4x4 */

var QUAD_GEOMETRY = new Float32Array([
  0, 0, 0, 1,
  1, 1, 0, 1,
  0, 1, 0, 1,
  0, 0, 0, 1,
  1, 0, 0, 1,
  1, 1, 0, 1
]);

var TEST_COUNT = 100;

function generateTestGeometry() {
  var testGeometry = new Float32Array(TEST_COUNT * QUAD_GEOMETRY.length);

  var transform = new Matrix4x4();
  for (var i = 0; i < TEST_COUNT; i++) {
    var theta = i / TEST_COUNT * 2 * Math.PI;
    transform.identity();
    transform.rotateY(theta);

    for (var j = 0; j < QUAD_GEOMETRY.length; j += 4) {
      var destOffset = i * QUAD_GEOMETRY.length + j;
      transform.transformOffsetVec4(testGeometry, destOffset, QUAD_GEOMETRY, j);
    }
  }

  return testGeometry;
}
<commit_msg>add (incorrect) correction of sprites.js<commit_after>/* global Matrix4x4 */

var QUAD_GEOMETRY = new Float32Array([
  0, 0, 0, 1,
  1, 1, 0, 1,
  0, 1, 0, 1,
  0, 0, 0, 1,
  1, 0, 0, 1,
  1, 1, 0, 1
]);

var TEST_COUNT = 100;

function generateTestGeometry() {
  var testGeometry = new Float32Array(TEST_COUNT * 6 * 6);

  var transform = new Matrix4x4();
  for (var i = 0; i < TEST_COUNT; i++) {
    var theta = i / TEST_COUNT * 2 * Math.PI;
    transform.identity();
    transform.rotateY(theta);

    for (var j = 0; j < QUAD_GEOMETRY.length; j += 6) {
      // add transformed world coordinate and texture coordinate
      var destOffset = i * 6 * 6 + j;
      transform.transformOffsetVec4(testGeometry, destOffset, QUAD_GEOMETRY, j);
    }
  }

  return testGeometry;
}
<|endoftext|>


<commit_before>const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const TerserPlugin = require('terser-webpack-plugin')

const fileNameTemplate = '[name].[contenthash:8].[ext]'

const babelLoaderOptions = {
  compact: process.env.NODE_ENV === 'production',
  cacheDirectory: true,
  // Don't waste time on Gzipping the cache during dev
  cacheCompression: process.env.NODE_ENV === 'production',
}

/**
 * The thread-loader parallelizes code compilation, useful with babel since
 * it transpiles both application javascript and node_modules javascript
 */
function babel(options = {}) {
  return (context, { addLoader }) =>
    addLoader({
      // setting `test` defaults here, in case there is no `context.match` data
      test: /\.(js|jsx)$/,
      use: [
        {
          loader: 'thread-loader',
          options: {
            // Keep workers alive for more effective watch mode
            ...(process.env.NODE_ENV === 'development' && { poolTimeout: Infinity }),
          },
        },
        {
          loader: 'babel-loader',
          options: Object.assign(babelLoaderOptions, options),
        },
      ],
      ...context.match,
    })
}

/**
 * Extracts the css and puts it in the <head>
 */
function extractCss() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.css$/,
      use: [
        {
          loader: MiniCssExtractPlugin.loader,
        },
      ],
      ...context.match,
    })
}

/**
 * Images smaller than 10kb are loaded as a base64 encoded url instead of file url
 */
function imageLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.(gif|ico|jpg|jpeg|png|webp)$/,
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: fileNameTemplate,
      },
    })
}

/**
 * Videos smaller than 10kb are loaded as a base64 encoded url instead of file url
 */
function videoLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.(mp4|webm)$/,
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: fileNameTemplate,
      },
    })
}

/**
 * Fonts are loaded as file urls
 */
function fontLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.(eot|ttf|otf|woff|woff2)(\?.*)?$/,
      loader: 'file-loader',
      options: {
        name: fileNameTemplate,
      },
    })
}

/**
 * Pdfs are loaded as file urls
 */
function pdfLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.pdf$/,
      loader: 'file-loader',
      options: {
        name: fileNameTemplate,
      },
    })
}

/**
 * GLSLify is a node-style module system for WebGL shaders,
 * allowing you to install GLSL modules from npm and use them in your shaders
 */
function glslifyLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.(glsl|frag|vert)$/,
      use: ['raw-loader', 'glslify-loader'],
    })
}

/**
 * Parse .csv files with PapaParse and return it in a JSON format
 */
function csvLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.csv$/,
      loader: 'csv-loader',
      options: {
        dynamicTyping: true,
        header: true,
        skipEmptyLines: true,
      },
    })
}

// Allows you to use two kinds of imports for SVG:
// import logoUrl from './logo.svg'; gives you the URL.
// import { ReactComponent as Logo } from './logo.svg'; gives you a component.
function reactSvgLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.svg$/,
      issuer: {
        test: /\.(js|jsx|ts|tsx)$/,
      },
      use: [
        {
          loader: 'babel-loader',
          options: babelLoaderOptions,
        },
        {
          loader: '@svgr/webpack',
          options: {
            svgProps: {
              fill: 'currentColor',
            },
            titleProp: true,
            svgoConfig: {
              multipass: true,
              pretty: process.env.NODE_ENV === 'development',
              indent: 2,
              plugins: [
                { sortAttrs: true },
                { removeViewBox: false },
                { removeDimensions: true },
                { convertColors: { currentColor: true } },
                { cleanupIDs: { minify: false } },
              ],
            },
          },
        },
        {
          loader: 'url-loader',
          options: {
            limit: 10000,
            name: fileNameTemplate,
          },
        },
      ],
    })
}

/**
 * Url-loader for svgs in css
 */
function cssSvgLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.svg$/,
      issuer: {
        test: /\.css$/,
      },
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: fileNameTemplate,
      },
    })
}

/**
 * Suppot .json5 files https://json5.org/
 */
function json5Loader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.json5$/,
      loader: 'json5-loader',
    })
}

/**
 * You will be able to import starting from the src folder so you don't have to ../../../
 */
function resolveSrc() {
  return (context, { merge }) =>
    merge({
      resolve: {
        modules: ['node_modules', 'src'],
      },
    })
}

/**
 * Import also typescript without specifying the extension
 */
function resolveTs() {
  return (context, { merge }) =>
    merge({
      resolve: {
        extensions: ['.ts', '.tsx'],
      },
    })
}

/**
 * Terser is a mantained fork of uglify-js
 * https://twitter.com/devongovett/status/1013127516943314944
 */
function terser(options) {
  return (context, { merge }) =>
    merge({
      optimization: {
        minimizer: [new TerserPlugin(options)],
      },
    })
}

/**
 * Add entryPoint at beginning of 'entry' array
 */
function prependEntry(entry) {
  const blockFunction = (context, util) => {
    if (!context.entriesToPrepend) context.entriesToPrepend = []
    context.entriesToPrepend.unshift(entry)
    return config => config
  }
  return Object.assign(blockFunction, {
    post: prependEntryPostHook,
  })
}
function prependEntryPostHook(context, util) {
  return config => {
    config.entry.main.unshift(...context.entriesToPrepend)
    return config
  }
}

module.exports = {
  fileNameTemplate,
  babel,
  extractCss,
  imageLoader,
  videoLoader,
  fontLoader,
  pdfLoader,
  glslifyLoader,
  csvLoader,
  reactSvgLoader,
  cssSvgLoader,
  json5Loader,
  resolveSrc,
  resolveTs,
  terser,
  prependEntry,
}
<commit_msg>🐛  Fix bug with svg loader<commit_after>const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const TerserPlugin = require('terser-webpack-plugin')

const fileNameTemplate = '[name].[contenthash:8].[ext]'

const babelLoaderOptions = {
  compact: process.env.NODE_ENV === 'production',
  cacheDirectory: true,
  // Don't waste time on Gzipping the cache during dev
  cacheCompression: process.env.NODE_ENV === 'production',
}

/**
 * The thread-loader parallelizes code compilation, useful with babel since
 * it transpiles both application javascript and node_modules javascript
 */
function babel(options = {}) {
  return (context, { addLoader }) =>
    addLoader({
      // setting `test` defaults here, in case there is no `context.match` data
      test: /\.(js|jsx)$/,
      use: [
        {
          loader: 'thread-loader',
          options: {
            // Keep workers alive for more effective watch mode
            ...(process.env.NODE_ENV === 'development' && { poolTimeout: Infinity }),
          },
        },
        {
          loader: 'babel-loader',
          options: Object.assign(babelLoaderOptions, options),
        },
      ],
      ...context.match,
    })
}

/**
 * Extracts the css and puts it in the <head>
 */
function extractCss() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.css$/,
      use: [
        {
          loader: MiniCssExtractPlugin.loader,
        },
      ],
      ...context.match,
    })
}

/**
 * Images smaller than 10kb are loaded as a base64 encoded url instead of file url
 */
function imageLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.(gif|ico|jpg|jpeg|png|webp)$/,
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: fileNameTemplate,
      },
    })
}

/**
 * Videos smaller than 10kb are loaded as a base64 encoded url instead of file url
 */
function videoLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.(mp4|webm)$/,
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: fileNameTemplate,
      },
    })
}

/**
 * Fonts are loaded as file urls
 */
function fontLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.(eot|ttf|otf|woff|woff2)(\?.*)?$/,
      loader: 'file-loader',
      options: {
        name: fileNameTemplate,
      },
    })
}

/**
 * Pdfs are loaded as file urls
 */
function pdfLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.pdf$/,
      loader: 'file-loader',
      options: {
        name: fileNameTemplate,
      },
    })
}

/**
 * GLSLify is a node-style module system for WebGL shaders,
 * allowing you to install GLSL modules from npm and use them in your shaders
 */
function glslifyLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.(glsl|frag|vert)$/,
      use: ['raw-loader', 'glslify-loader'],
    })
}

/**
 * Parse .csv files with PapaParse and return it in a JSON format
 */
function csvLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.csv$/,
      loader: 'csv-loader',
      options: {
        dynamicTyping: true,
        header: true,
        skipEmptyLines: true,
      },
    })
}

// Allows you to use two kinds of imports for SVG:
// import logoUrl from './logo.svg'; gives you the URL.
// import { ReactComponent as Logo } from './logo.svg'; gives you a component.
function reactSvgLoader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.svg$/,
      issuer: {
        test: /\.(js|jsx|ts|tsx)$/,
      },
      use: [
        // TODO this is probably not needed
        // {
        //   loader: 'babel-loader',
        //   options: babelLoaderOptions,
        // },
        {
          loader: '@svgr/webpack',
          options: {
            svgProps: {
              fill: 'currentColor',
            },
            titleProp: true,
            svgoConfig: {
              multipass: true,
              pretty: process.env.NODE_ENV === 'development',
              indent: 2,
              plugins: [
                { sortAttrs: true },
                { removeViewBox: false },
                { removeDimensions: true },
                { convertColors: { currentColor: true } },
                { cleanupIDs: { minify: false } },
              ],
            },
          },
        },
        {
          loader: 'url-loader',
          options: {
            limit: 10000,
            name: fileNameTemplate,
          },
        },
      ],
    })
}

/**
 * Url-loader for svgs in css
 */
function cssSvgLoader() {
  return (context, { addLoader }) =>
    addLoader({
      // This needs to be different form the reactSvgLoader, otherwise it will merge
      test: /(.*)\.svg$/,
      issuer: {
        test: /\.css$/,
      },
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: fileNameTemplate,
      },
    })
}

/**
 * Suppot .json5 files https://json5.org/
 */
function json5Loader() {
  return (context, { addLoader }) =>
    addLoader({
      test: /\.json5$/,
      loader: 'json5-loader',
    })
}

/**
 * You will be able to import starting from the src folder so you don't have to ../../../
 */
function resolveSrc() {
  return (context, { merge }) =>
    merge({
      resolve: {
        modules: ['node_modules', 'src'],
      },
    })
}

/**
 * Import also typescript without specifying the extension
 */
function resolveTs() {
  return (context, { merge }) =>
    merge({
      resolve: {
        extensions: ['.ts', '.tsx'],
      },
    })
}

/**
 * Terser is a mantained fork of uglify-js
 * https://twitter.com/devongovett/status/1013127516943314944
 */
function terser(options) {
  return (context, { merge }) =>
    merge({
      optimization: {
        minimizer: [new TerserPlugin(options)],
      },
    })
}

/**
 * Add entryPoint at beginning of 'entry' array
 */
function prependEntry(entry) {
  const blockFunction = (context, util) => {
    if (!context.entriesToPrepend) context.entriesToPrepend = []
    context.entriesToPrepend.unshift(entry)
    return config => config
  }
  return Object.assign(blockFunction, {
    post: prependEntryPostHook,
  })
}
function prependEntryPostHook(context, util) {
  return config => {
    config.entry.main.unshift(...context.entriesToPrepend)
    return config
  }
}

module.exports = {
  fileNameTemplate,
  babel,
  extractCss,
  imageLoader,
  videoLoader,
  fontLoader,
  pdfLoader,
  glslifyLoader,
  csvLoader,
  reactSvgLoader,
  cssSvgLoader,
  json5Loader,
  resolveSrc,
  resolveTs,
  terser,
  prependEntry,
}
<|endoftext|>


<commit_before>'use strict';

var Registry = require('../../registry');
var helpers = require('./helpers');

module.exports = function getLegendData(calcdata, opts) {
    var lgroupToTraces = {};
    var lgroups = [];
    var hasOneNonBlankGroup = false;
    var slicesShown = {};
    var lgroupi = 0;
    var maxNameLength = 0;
    var i, j;
    var initID = 0;
    function addOneItem(legendGroup, legendItem) {
        legendItem._initID = initID++;

        // each '' legend group is treated as a separate group
        if(legendGroup === '' || !helpers.isGrouped(opts)) {
            // TODO: check this against fullData legendgroups?
            var uniqueGroup = '~~i' + lgroupi;
            lgroups.push(uniqueGroup);
            lgroupToTraces[uniqueGroup] = [[legendItem]];
            lgroupi++;
        } else if(lgroups.indexOf(legendGroup) === -1) {
            lgroups.push(legendGroup);
            hasOneNonBlankGroup = true;
            lgroupToTraces[legendGroup] = [[legendItem]];
        } else {
            lgroupToTraces[legendGroup].push([legendItem]);
        }
    }

    // build an { legendgroup: [cd0, cd0], ... } object
    for(i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var cd0 = cd[0];
        var trace = cd0.trace;
        var lgroup = trace.legendgroup;

        if(!opts._inHover && (!trace.visible || !trace.showlegend)) continue;

        if(Registry.traceIs(trace, 'pie-like')) {
            if(!slicesShown[lgroup]) slicesShown[lgroup] = {};

            for(j = 0; j < cd.length; j++) {
                var labelj = cd[j].label;

                if(!slicesShown[lgroup][labelj]) {
                    addOneItem(lgroup, {
                        label: labelj,
                        color: cd[j].color,
                        i: cd[j].i,
                        trace: trace,
                        pts: cd[j].pts
                    });

                    slicesShown[lgroup][labelj] = true;
                    maxNameLength = Math.max(maxNameLength, (labelj || '').length);
                }
            }
        } else {
            addOneItem(lgroup, cd0);
            maxNameLength = Math.max(maxNameLength, (trace.name || '').length);
        }
    }

    // won't draw a legend in this case
    if(!lgroups.length) return [];

    // rearrange lgroupToTraces into a d3-friendly array of arrays
    var legendData;

    var shouldCollapse = !hasOneNonBlankGroup || !helpers.isGrouped(opts);
    legendData = shouldCollapse ? [[]] : [];
    for(i = 0; i < lgroups.length; i++) {
        var t = lgroupToTraces[lgroups[i]];
        if(shouldCollapse) {
            // collapse all groups into one if all groups are blank
            legendData[0].push(t[0]);
        } else {
            legendData.push(t);
        }
    }

    // sort considering trace.legendrank and legend.traceorder
    var dir = helpers.isReversed(opts) ? -1 : 1;
    var orderFn = function(a, b) {
        var A = a[0].trace;
        var B = b[0].trace;
        var delta = A.legendrank - B.legendrank;
        if(!delta) delta = A.index - B.index;
        if(!delta) delta = a[0]._initID - b[0]._initID;

        return dir * delta;
    };

    for(i = 0; i < legendData.length; i++) {
        legendData[i].sort(orderFn);
    }

    // number of legend groups - needed in legend/draw.js
    opts._lgroupsLength = legendData.length;
    // maximum name/label length - needed in legend/draw.js
    opts._maxNameLength = maxNameLength;

    return legendData;
};
<commit_msg>simplify and fixup legend sort<commit_after>'use strict';

var Registry = require('../../registry');
var helpers = require('./helpers');

module.exports = function getLegendData(calcdata, opts) {
    var lgroupToTraces = {};
    var lgroups = [];
    var hasOneNonBlankGroup = false;
    var slicesShown = {};
    var lgroupi = 0;
    var maxNameLength = 0;
    var i, j;
    var initID = 0;
    function addOneItem(legendGroup, legendItem) {
        legendItem._initID = initID++;

        // each '' legend group is treated as a separate group
        if(legendGroup === '' || !helpers.isGrouped(opts)) {
            // TODO: check this against fullData legendgroups?
            var uniqueGroup = '~~i' + lgroupi;
            lgroups.push(uniqueGroup);
            lgroupToTraces[uniqueGroup] = [legendItem];
            lgroupi++;
        } else if(lgroups.indexOf(legendGroup) === -1) {
            lgroups.push(legendGroup);
            hasOneNonBlankGroup = true;
            lgroupToTraces[legendGroup] = [legendItem];
        } else {
            lgroupToTraces[legendGroup].push(legendItem);
        }
    }

    // build an { legendgroup: [cd0, cd0], ... } object
    for(i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var cd0 = cd[0];
        var trace = cd0.trace;
        var lgroup = trace.legendgroup;

        if(!opts._inHover && (!trace.visible || !trace.showlegend)) continue;

        if(Registry.traceIs(trace, 'pie-like')) {
            if(!slicesShown[lgroup]) slicesShown[lgroup] = {};

            for(j = 0; j < cd.length; j++) {
                var labelj = cd[j].label;

                if(!slicesShown[lgroup][labelj]) {
                    addOneItem(lgroup, {
                        label: labelj,
                        color: cd[j].color,
                        i: cd[j].i,
                        trace: trace,
                        pts: cd[j].pts
                    });

                    slicesShown[lgroup][labelj] = true;
                    maxNameLength = Math.max(maxNameLength, (labelj || '').length);
                }
            }
        } else {
            addOneItem(lgroup, cd0);
            maxNameLength = Math.max(maxNameLength, (trace.name || '').length);
        }
    }

    // won't draw a legend in this case
    if(!lgroups.length) return [];

    // collapse all groups into one if all groups are blank
    var shouldCollapse = !hasOneNonBlankGroup || !helpers.isGrouped(opts);

    // rearrange lgroupToTraces into a d3-friendly array of arrays
    var legendData;

    legendData = [];
    for(i = 0; i < lgroups.length; i++) {
        var t = lgroupToTraces[lgroups[i]];
        if(shouldCollapse) {
            legendData.push(t[0]);
        } else {
            legendData.push(t);
        }
    }
    if(shouldCollapse) legendData = [legendData];

    // sort considering trace.legendrank and legend.traceorder
    var orderFn = function(a, b) {
        var A = a.trace;
        var B = b.trace;
        var delta = A.legendrank - B.legendrank;
        if(!delta) delta = A._initID - B._initID;

        return delta;
    };
    var rev = helpers.isReversed(opts);
    for(i = 0; i < legendData.length; i++) {
        legendData[i].sort(orderFn);
        if(rev) legendData[i].reverse();
    }

    var arr = [];
    for(i = 0; i < legendData.length; i++) {
        arr[i] = [];
        for(j = 0; j < legendData[i].length; j++) {
            arr[i][j] = [legendData[i][j]];
        }
    }
    legendData = arr;

    // number of legend groups - needed in legend/draw.js
    opts._lgroupsLength = legendData.length;
    // maximum name/label length - needed in legend/draw.js
    opts._maxNameLength = maxNameLength;

    return legendData;
};
<|endoftext|>


<commit_before>//a workaround for wrapper not finished loading before the content displays, the finish loading of wrapper hides the loader
DELAY_LOADING = true;

function AdminTool (userId) {
  this.requestsCounter = 0;
  this.userId = userId;
  this.userOrgs = [];
  this.ajaxRequests = [];
  this.ajaxAborted = false;
  this.arrData = {};
  this.patientsIdList = [];
  OrgTool.call(this);
};

/*
* extends OrgTool class
* see OT class definition in main.js should modularize it in the future so it can be instantiated/called safely
*
*/
AdminTool.prototype = Object.create(OrgTool.prototype);
AdminTool.prototype.fadeLoader = function() {
  DELAY_LOADING = false;
  setTimeout(function() { $("#loadingIndicator").fadeOut(); }, 1000);
};
AdminTool.prototype.setLoadingMessageVis = function(vis) {
  switch(vis) {
    case "hide":
      $("#adminTable .field-loading-indicator").fadeOut();
      break;
    case "show":
      $("#adminTable .field-loading-indicator").fadeIn();
      break;
  };
};
AdminTool.prototype.getPatientsIdList = function() {
  var self = this;
  if (self.patientsIdList.length == 0) {
    var all = $("#adminTable").bootstrapTable("getData");
    if (all) {
      all.forEach(function(o) {
        self.patientsIdList.push(o.id);
      });
    };
  };
  return self.patientsIdList;
};
AdminTool.prototype.getData = function(requests, callback) {
    var self = this;
    if (self.ajaxAborted) {
        return false;
    };
    if (!requests || requests.length == 0) {
        return false;
    };
    var userString = requests.shift();
    if (!hasValue(userString)) {
        return false;
    };
    /*
     *  load the data sequentially
     *  Note, NO concurrent ajax calls here,
     *  one request will wait after the previous one has finished
     */
    var ajaxRequest = $.ajax ({
                              type: "GET",
                              url: '/api/consent-assessment-status',
                              contentType: "application/json; charset=utf-8",
                              data: userString,
                              cache: false,
                              timeout: 25000,
                              dataType: 'json'
                          }).done(function(data) {
                                if (data && data.status) {
                                  data.status.forEach(function(status) {
                                      var c = status.consents;
                                      var a = "", s = "", prevItem = {};
                                      if (c) {
                                      c.forEach(function(item) {
                                          if (!item.consent.deleted && (!prevItem.consent_signed || (prevItem.assessment_status != item.assessment_status)
                                              || (String(prevItem.consent_signed).substring(0, 10) != String(item.consent.signed).substring(0, 10)))) {
                                              if (!(/null/.test(item.consent.agreement_url))) {
                                                var cl = "";
                                                var sd = tnthDates.formatDateString(item.consent.signed);
                                                var status = item.assessment_status;
                                                if (!item.consent.send_reminders) status = "withdrawn";
                                                switch(String(status).toLowerCase()) {
                                                    case "completed":
                                                      cl = "text-success";
                                                      break;
                                                    case "withdrawn":
                                                      cl = "text-muted";
                                                      break;
                                                    case "due":
                                                      cl = "text-warning";
                                                      break;
                                                    case "overdue":
                                                      cl = "text-danger";
                                                      break;
                                                };
                                                a += (a != "" ? "
" : "") + "" + status + "";
                                                s += (s != "" ? "
" : "") + sd;
                                                prevItem.assessment_status = item.assessment_status;
                                                prevItem.consent_signed = item.consent.signed;
                                              };
                                            };
                                        });
                                    };
                                    if (hasValue(status.user_id)) {
                                      /*
                                       * NOTE, need to get the row data here
                                       * data for all the fields are required for the method, updateByUniqueId
                                       */
                                      var rowData = $("#adminTable").bootstrapTable('getRowByUniqueId', status.user_id);
                                      rowData = rowData || {};
                                      /* update row data with updated assessment status */
                                      rowData["status"] = a;
                                      /* persist data here, help with debugging */
                                      self.arrData[status.user_id] = { id: status.user_id, row: rowData};
                                      $("#adminTable").bootstrapTable('updateByUniqueId', self.arrData[status.user_id]);

                                    };
                              });
                            };
                            if (requests.length > 0) {
                              self.getData(requests, callback);
                            }
                            else {
                              if (callback) setTimeout(function() { callback.call(self);}, 300);
                            };
                        }).fail(function(xhr) {
                            $("#admin-table-error-message").text("Server error occurred updating row data.  Server error code: " + xhr.status);
                        });
        self.ajaxRequests.push(ajaxRequest);
        return ajaxRequest;
};
AdminTool.prototype.loadData = function(list, callback) {
    var self = this;
    $("#admin-table-error-message").text("");
    if (list && list.length > 0) {
      self.getData(list, function() { if (callback) callback.call(self); });
    } else {
      if (callback) callback.call(self);
    };
};
AdminTool.prototype.updateData = function() {
  /* compile user IDs array from patients list ID */
  var arrUsers = this.getUserIdArray();
  var self = this;
  if (arrUsers.length > 0) {
     self.getData(arrUsers);
  };
};

AdminTool.prototype.abortRequests = function(callback) {
    var self = this;
   //NEED TO ABORT THE AJAX REQUESTS OTHERWISE CLICK EVENT IS DELAYED DUE TO NETWORK TIE-UP
   if (self.ajaxRequests.length > 0) {
      self.ajaxAborted = true;
      self.ajaxRequests.forEach(function(request, index, array) {
          try {
            if (request.readyState != 4) {
                request.abort();
            }
          } catch(e) {
          };
          if (index == array.length - 1) {
            $("#admin-table-error-message").text("");
            if (callback) setTimeout(function() { callback();}, 100);
          };
      });
    } else {
      if (callback) callback();
    };

};
AdminTool.prototype.getUserIdArray = function(_userIds) {
  var us = "", ct = 0, arrUsers = [];
  if (!_userIds) {
     _userIds = this.getPatientsIdList();
  };
  var max_ct = Math.max(_userIds.length/10, 10);

  for (var index = 0; index < _userIds.length; index++, ct++) {
     us += (us != ""?"&":"") + "user_id=" + _userIds[index];
     if (index == (_userIds.length - 1)) {
       arrUsers.push(us);
     } else if (ct >= max_ct) {
        arrUsers.push(us);
        us = "";
        ct = 0;
     };
  };
  return arrUsers;
};
AdminTool.prototype.setUserOrgs = function() {
  var self = this;
  if (!hasValue(this.userId)) return false;
  $.ajax ({
          type: "GET",
          async: false,
          url: '/api/demographics/'+this.userId
  }).done(function(data) {
    if (data && data.careProvider) {
      $.each(data.careProvider,function(i,val){
          var orgID = val.reference.split("/").pop();
          self.userOrgs.push(orgID);
          if (orgID == "0") $("#createUserLink").attr("disabled", true);
      });
    if (self.userOrgs.length == 0) $("#createUserLink").attr("disabled", true);
    };
  }).fail(function() {

  });
};
AdminTool.prototype.getUserOrgs = function() {
  if (this.userOrgs.length == 0) this.setUserOrgs(this.userId);
  return this.userOrgs;
};
AdminTool.prototype.initOrgsList = function(request_org_list, context) {
    //set user orgs
    var self = this;
    self.setUserOrgs();

    //check if the location contains filtered orgs list
    var iterated = /org_list/.test(location.href);

    var noPatientData = $("#admin-table-body").find("tr.no-records-found").length > 0;

    $.ajax ({
        type: "GET",
        url: '/api/organization'
    }).done(function(data) {

        /*
         * building an orgs array object for reference later
         */
        self.populateOrgsList(data.entry);
        /*
         * populate orgs dropdown UI
         */
        self.populateUI();

        /*
         * filter orgs UI based on user's orgs
         */
        if (!noPatientData) {
            var hbOrgs = self.getHereBelowOrgs(self.getUserOrgs());
	          self.filterOrgs(hbOrgs);
        };

        /* attach orgs related events to UI components */

        $("#dataDownloadModal").on('shown.bs.modal', function () {
              var parentOrgList = self.getUserTopLevelParentOrgs(self.getUserOrgs());
              console.dir(parentOrgList)
              if (parentOrgList && parentOrgList.length > 0) {
                 var instrumentList = self.getInstrumentList();
                 var instrumentItems = [];
                 parentOrgList.forEach(function(o) {
                    var il = instrumentList[o];
                    if (il) {
                      il.forEach(function(n) {
                        instrumentItems.push(n);
                      });
                    };
                 });
                 if (instrumentItems.length > 0) {
                    $(".instrument-container").hide();
                    instrumentItems.forEach(function(item) {
                      $("#" + item + "_container").show();
                    });
                 };
              };
              $("#patientsInstrumentList").addClass("ready");
        });

        var ofields = $("#userOrgs input[name='organization']");
        if (ofields.length > 0) {

          ofields.each(function() {
            if ((self.getHereBelowOrgs(self.getUserOrgs())).length == 1 ||
                (iterated && request_org_list && request_org_list[$(this).val()])) {
                $(this).prop("checked", true);
            }
            $(this).on("click touchstart", function(e) {
                e.stopPropagation();
                AT.abortRequests();
                var orgsList = [];
                $("#userOrgs input[name='organization']").each(function() {
                   if ($(this).is(":checked")) orgsList.push($(this).val());
                });
               if (orgsList.length > 0) {
                  location.replace("/" + context + "?org_list=" + orgsList.join(","));
               } else location.replace("/" + context);
            });
          });

          $("#org-menu").append("

<input type='checkbox' id='orglist-selectall-ckbox'> Select All   <input type='checkbox' id='orglist-clearall-ckbox'> Clear All   <input type='checkbox' id='orglist-close-ckbox'> Close
");
          $("#orglist-selectall-ckbox").on("click touchstart", function(e) {
              e.stopPropagation();
              var orgsList = [];
              $("#userOrgs input[name='organization']").each(function() {
                  if ($(this).is(":visible")) {
                    $(this).prop("checked", true);
                    orgsList.push($(this).val());
                  };
              });
              $("#orglist-clearall-ckbox").prop("checked", false);
              if (orgsList.length > 0) location.replace("/" + context + "?org_list=" + orgsList.join(","));
          });
          $("#orglist-clearall-ckbox").on("click touchstart", function(e) {
              e.stopPropagation();
              $("#userOrgs input[name='organization']").each(function() {
                  $(this).prop("checked", false);
              });
          });
          $("#orglist-close-ckbox").on("click touchstart", function(e) {
              e.stopPropagation();
              $("#orglistSelector").trigger("click");
              return false;
          });
        };

    }).fail(function() {
        //console.log("Problem retrieving data from server.");
        $("#org-menu").append("Error occurred retrieving data from server.");
    });

    //orglist-dropdown
    $('#orglist-dropdown').on('click touchstart', function () {
        setTimeout('__setOrgsMenuHeight(100); __clearFilterButtons();', 10);
    });

    if (noPatientData) $("#patientListExportDataContainer").hide();

    __setOrgsMenuHeight = function(padding) {
      if (!padding) padding = 100;
      var h = parseInt($("#fillOrgs").height());
      if (!isNaN(h) && h > 0) {
        $("#org-menu").height(h + padding);
        if ($("div.admin-table").height() < $("#org-menu").height()) {
            setTimeout('$("div.admin-table").height($("#org-menu").height() + ' + padding + ');', 0);
        };
      };
    };
    __clearFilterButtons = function() {
      $("#orglist-close-ckbox, #orglist-clearall-ckbox, #orglist-selectall-ckbox").prop("checked", false);
    };
};
AdminTool.prototype.getInstrumentList = function() {
  return {
    //CRV
    '10000': ['epic26', 'eproms_add', 'comorb'],
    //IRONMAN
    '20000': ['eortc', 'ironmisc', 'factfpsi', 'epic26', 'prems', 'irondemog']
  };
};

<commit_msg>more comments added<commit_after>//a workaround for wrapper not finished loading before the content displays, the finish loading of wrapper hides the loader
DELAY_LOADING = true;

function AdminTool (userId) {
  this.requestsCounter = 0;
  this.userId = userId;
  this.userOrgs = [];
  this.ajaxRequests = [];
  this.ajaxAborted = false;
  this.arrData = {};
  this.patientsIdList = [];
  OrgTool.call(this);
};

/*
* extends OrgTool class
* see OT class definition in main.js should modularize it in the future so it can be instantiated/called safely
*
*/
AdminTool.prototype = Object.create(OrgTool.prototype);
AdminTool.prototype.fadeLoader = function() {
  DELAY_LOADING = false;
  setTimeout(function() { $("#loadingIndicator").fadeOut(); }, 1000);
};
AdminTool.prototype.setLoadingMessageVis = function(vis) {
  switch(vis) {
    case "hide":
      $("#adminTable .field-loading-indicator").fadeOut();
      break;
    case "show":
      $("#adminTable .field-loading-indicator").fadeIn();
      break;
  };
};
AdminTool.prototype.getPatientsIdList = function() {
  var self = this;
  if (self.patientsIdList.length == 0) {
    var all = $("#adminTable").bootstrapTable("getData");
    if (all) {
      all.forEach(function(o) {
        self.patientsIdList.push(o.id);
      });
    };
  };
  return self.patientsIdList;
};
AdminTool.prototype.getData = function(requests, callback) {
    var self = this;
    if (self.ajaxAborted) {
        return false;
    };
    if (!requests || requests.length == 0) {
        return false;
    };
    var userString = requests.shift();
    if (!hasValue(userString)) {
        return false;
    };
    /*
     *  load the data sequentially
     *  Note, NO concurrent ajax calls here,
     *  one request will wait after the previous one has finished
     */
    var ajaxRequest = $.ajax ({
                              type: "GET",
                              url: '/api/consent-assessment-status',
                              contentType: "application/json; charset=utf-8",
                              data: userString,
                              cache: false,
                              timeout: 25000,
                              dataType: 'json'
                          }).done(function(data) {
                                if (data && data.status) {
                                  data.status.forEach(function(status) {
                                      var c = status.consents;
                                      var a = "", s = "", prevItem = {};
                                      if (c) {
                                      c.forEach(function(item) {
                                          if (!item.consent.deleted && (!prevItem.consent_signed || (prevItem.assessment_status != item.assessment_status)
                                              || (String(prevItem.consent_signed).substring(0, 10) != String(item.consent.signed).substring(0, 10)))) {
                                              if (!(/null/.test(item.consent.agreement_url))) {
                                                var cl = "";
                                                var sd = tnthDates.formatDateString(item.consent.signed);
                                                var status = item.assessment_status;
                                                if (!item.consent.send_reminders) status = "withdrawn";
                                                switch(String(status).toLowerCase()) {
                                                    case "completed":
                                                      cl = "text-success";
                                                      break;
                                                    case "withdrawn":
                                                      cl = "text-muted";
                                                      break;
                                                    case "due":
                                                      cl = "text-warning";
                                                      break;
                                                    case "overdue":
                                                      cl = "text-danger";
                                                      break;
                                                };
                                                a += (a != "" ? "
" : "") + "" + status + "";
                                                s += (s != "" ? "
" : "") + sd;
                                                prevItem.assessment_status = item.assessment_status;
                                                prevItem.consent_signed = item.consent.signed;
                                              };
                                            };
                                        });
                                    };
                                    if (hasValue(status.user_id)) {
                                      /*
                                       * NOTE, need to get the row data here
                                       * data for all the fields are required for the method, updateByUniqueId
                                       */
                                      var rowData = $("#adminTable").bootstrapTable('getRowByUniqueId', status.user_id);
                                      rowData = rowData || {};
                                      /* update row data with updated assessment status */
                                      rowData["status"] = a;
                                      /* persist data here, help with debugging */
                                      self.arrData[status.user_id] = { id: status.user_id, row: rowData};
                                      $("#adminTable").bootstrapTable('updateByUniqueId', self.arrData[status.user_id]);

                                    };
                              });
                            };
                            if (requests.length > 0) {
                              self.getData(requests, callback);
                            }
                            else {
                              if (callback) setTimeout(function() { callback.call(self);}, 300);
                            };
                        }).fail(function(xhr) {
                            $("#admin-table-error-message").text("Server error occurred updating row data.  Server error code: " + xhr.status);
                        });
        self.ajaxRequests.push(ajaxRequest);
        return ajaxRequest;
};
AdminTool.prototype.loadData = function(list, callback) {
    var self = this;
    $("#admin-table-error-message").text("");
    if (list && list.length > 0) {
      self.getData(list, function() { if (callback) callback.call(self); });
    } else {
      if (callback) callback.call(self);
    };
};
AdminTool.prototype.updateData = function() {
  /* compile user IDs array from patients list ID */
  var arrUsers = this.getUserIdArray();
  var self = this;
  if (arrUsers.length > 0) {
     self.getData(arrUsers);
  };
};

AdminTool.prototype.abortRequests = function(callback) {
    var self = this;
   //NEED TO ABORT THE AJAX REQUESTS OTHERWISE CLICK EVENT IS DELAYED DUE TO NETWORK TIE-UP
   if (self.ajaxRequests.length > 0) {
      self.ajaxAborted = true;
      self.ajaxRequests.forEach(function(request, index, array) {
          try {
            if (request.readyState != 4) {
                request.abort();
            }
          } catch(e) {
          };
          if (index == array.length - 1) {
            $("#admin-table-error-message").text("");
            if (callback) setTimeout(function() { callback();}, 100);
          };
      });
    } else {
      if (callback) callback();
    };

};
AdminTool.prototype.getUserIdArray = function(_userIds) {
  var us = "", ct = 0, arrUsers = [];
  if (!_userIds) {
     _userIds = this.getPatientsIdList();
  };
  var max_ct = Math.max(_userIds.length/10, 10);

  for (var index = 0; index < _userIds.length; index++, ct++) {
     us += (us != ""?"&":"") + "user_id=" + _userIds[index];
     if (index == (_userIds.length - 1)) {
       arrUsers.push(us);
     } else if (ct >= max_ct) {
        arrUsers.push(us);
        us = "";
        ct = 0;
     };
  };
  return arrUsers;
};
AdminTool.prototype.setUserOrgs = function() {
  var self = this;
  if (!hasValue(this.userId)) return false;
  $.ajax ({
          type: "GET",
          async: false,
          url: '/api/demographics/'+this.userId
  }).done(function(data) {
    if (data && data.careProvider) {
      $.each(data.careProvider,function(i,val){
          var orgID = val.reference.split("/").pop();
          self.userOrgs.push(orgID);
          if (orgID == "0") $("#createUserLink").attr("disabled", true);
      });
    if (self.userOrgs.length == 0) $("#createUserLink").attr("disabled", true);
    };
  }).fail(function() {

  });
};
AdminTool.prototype.getUserOrgs = function() {
  if (this.userOrgs.length == 0) this.setUserOrgs(this.userId);
  return this.userOrgs;
};
AdminTool.prototype.initOrgsList = function(request_org_list, context) {
    //set user orgs
    var self = this;
    self.setUserOrgs();

    //check if the location contains filtered orgs list
    var iterated = /org_list/.test(location.href);

    var noPatientData = $("#admin-table-body").find("tr.no-records-found").length > 0;

    $.ajax ({
        type: "GET",
        url: '/api/organization'
    }).done(function(data) {

        /*
         * building an orgs array object for reference later
         */
        self.populateOrgsList(data.entry);
        /*
         * populate orgs dropdown UI
         */
        self.populateUI();

        /*
         * filter orgs UI based on user's orgs
         */
        if (!noPatientData) {
            var hbOrgs = self.getHereBelowOrgs(self.getUserOrgs());
	          self.filterOrgs(hbOrgs);
        };

        /* attach orgs related events to UI components */

        $("#dataDownloadModal").on('shown.bs.modal', function () {
              var parentOrgList = self.getUserTopLevelParentOrgs(self.getUserOrgs());
              console.dir(parentOrgList)
              if (parentOrgList && parentOrgList.length > 0) {
                 var instrumentList = self.getInstrumentList();
                 var instrumentItems = [];
                 parentOrgList.forEach(function(o) {
                    var il = instrumentList[o];
                    if (il) {
                      il.forEach(function(n) {
                        instrumentItems.push(n);
                      });
                    };
                 });
                 if (instrumentItems.length > 0) {
                    $(".instrument-container").hide();
                    instrumentItems.forEach(function(item) {
                      $("#" + item + "_container").show();
                    });
                 };
              };
              $("#patientsInstrumentList").addClass("ready");
        });

        var ofields = $("#userOrgs input[name='organization']");
        if (ofields.length > 0) {

          ofields.each(function() {
            if ((self.getHereBelowOrgs(self.getUserOrgs())).length == 1 ||
                (iterated && request_org_list && request_org_list[$(this).val()])) {
                $(this).prop("checked", true);
            }
            $(this).on("click touchstart", function(e) {
                e.stopPropagation();
                AT.abortRequests();
                var orgsList = [];
                $("#userOrgs input[name='organization']").each(function() {
                   if ($(this).is(":checked")) orgsList.push($(this).val());
                });
               if (orgsList.length > 0) {
                  location.replace("/" + context + "?org_list=" + orgsList.join(","));
               } else location.replace("/" + context);
            });
          });

          $("#org-menu").append("

<input type='checkbox' id='orglist-selectall-ckbox'> Select All   <input type='checkbox' id='orglist-clearall-ckbox'> Clear All   <input type='checkbox' id='orglist-close-ckbox'> Close
");
          $("#orglist-selectall-ckbox").on("click touchstart", function(e) {
              e.stopPropagation();
              var orgsList = [];
              $("#userOrgs input[name='organization']").each(function() {
                  if ($(this).is(":visible")) {
                    $(this).prop("checked", true);
                    orgsList.push($(this).val());
                  };
              });
              $("#orglist-clearall-ckbox").prop("checked", false);
              if (orgsList.length > 0) location.replace("/" + context + "?org_list=" + orgsList.join(","));
          });
          $("#orglist-clearall-ckbox").on("click touchstart", function(e) {
              e.stopPropagation();
              $("#userOrgs input[name='organization']").each(function() {
                  $(this).prop("checked", false);
              });
          });
          $("#orglist-close-ckbox").on("click touchstart", function(e) {
              e.stopPropagation();
              $("#orglistSelector").trigger("click");
              return false;
          });
        };

    }).fail(function() {
        //console.log("Problem retrieving data from server.");
        $("#org-menu").append("Error occurred retrieving data from server.");
    });

    //orglist-dropdown
    $('#orglist-dropdown').on('click touchstart', function () {
        setTimeout('__setOrgsMenuHeight(100); __clearFilterButtons();', 10);
    });

    if (noPatientData) $("#patientListExportDataContainer").hide();

    /*
     * private functions used only within the context of the class
     */
    __setOrgsMenuHeight = function(padding) {
      if (!padding) padding = 100;
      var h = parseInt($("#fillOrgs").height());
      if (!isNaN(h) && h > 0) {
        $("#org-menu").height(h + padding);
        if ($("div.admin-table").height() < $("#org-menu").height()) {
            setTimeout('$("div.admin-table").height($("#org-menu").height() + ' + padding + ');', 0);
        };
      };
    };
    __clearFilterButtons = function() {
      $("#orglist-close-ckbox, #orglist-clearall-ckbox, #orglist-selectall-ckbox").prop("checked", false);
    };
};
AdminTool.prototype.getInstrumentList = function() {
  return {
    //CRV
    '10000': ['epic26', 'eproms_add', 'comorb'],
    //IRONMAN
    '20000': ['eortc', 'ironmisc', 'factfpsi', 'epic26', 'prems', 'irondemog']
  };
};

<|endoftext|>