<commit_before>/* @flow strict-local */
import { Platform } from 'react-native';

import type { ThemeColors } from './theme';
import { BORDER_COLOR, CONTROL_SIZE } from './constants';

export const statics = {
  largerText: {
    fontSize: 20,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  settingsIcon: {
    width: 24,
    height: 24,
    margin: 8,
    fontSize: 24,
    textAlign: 'center',
    marginLeft: 8,
    marginRight: 16,
  },
  listItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingTop: 8,
    paddingBottom: 8,
    paddingLeft: 16,
    paddingRight: 16,
  },
  flexed: {
    flex: 1,
  },
  flexedLeftAlign: {
    flex: 1,
    justifyContent: 'flex-start',
  },
  rightItem: {
    marginLeft: 'auto',
  },
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  field: {
    flex: 1,
    flexDirection: 'row',
    height: CONTROL_SIZE,
    marginTop: 5,
    marginBottom: 5,
  },
  alignBottom: {
    flexDirection: 'column',
    justifyContent: 'flex-end',
  },
};

export default ({ color, backgroundColor }: ThemeColors) => ({
  color: {
    color,
  },
  backgroundColor: {
    backgroundColor,
  },
  input: {
    color,
    ...Platform.select({
      ios: {
        borderWidth: 1,
        borderColor: BORDER_COLOR,
        borderRadius: 2,
        padding: 8,
      },
    }),
  },
  background: {
    backgroundColor,
  },
  label: {
    color,
    fontSize: 15,
  },
  screen: {
    flex: 1,
    flexDirection: 'column',
    // alignItems: 'stretch',
    backgroundColor,
  },
});
<commit_msg>miscStyles [nfc]: Remove unused `color` in `miscStyles`.<commit_after>/* @flow strict-local */
import { Platform } from 'react-native';

import type { ThemeColors } from './theme';
import { BORDER_COLOR, CONTROL_SIZE } from './constants';

export const statics = {
  largerText: {
    fontSize: 20,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  settingsIcon: {
    width: 24,
    height: 24,
    margin: 8,
    fontSize: 24,
    textAlign: 'center',
    marginLeft: 8,
    marginRight: 16,
  },
  listItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingTop: 8,
    paddingBottom: 8,
    paddingLeft: 16,
    paddingRight: 16,
  },
  flexed: {
    flex: 1,
  },
  flexedLeftAlign: {
    flex: 1,
    justifyContent: 'flex-start',
  },
  rightItem: {
    marginLeft: 'auto',
  },
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  field: {
    flex: 1,
    flexDirection: 'row',
    height: CONTROL_SIZE,
    marginTop: 5,
    marginBottom: 5,
  },
  alignBottom: {
    flexDirection: 'column',
    justifyContent: 'flex-end',
  },
};

export default ({ color, backgroundColor }: ThemeColors) => ({
  backgroundColor: {
    backgroundColor,
  },
  input: {
    color,
    ...Platform.select({
      ios: {
        borderWidth: 1,
        borderColor: BORDER_COLOR,
        borderRadius: 2,
        padding: 8,
      },
    }),
  },
  background: {
    backgroundColor,
  },
  label: {
    color,
    fontSize: 15,
  },
  screen: {
    flex: 1,
    flexDirection: 'column',
    // alignItems: 'stretch',
    backgroundColor,
  },
});
<|endoftext|>


<commit_before>// @flow
import formRepository from '../../formRepository';
import { keyCode } from 'utils';

const classes = {
    disabled: 'editor_disabled disabled',
    readonly: 'editor_readonly readonly',
    hidden: 'editor_hidden',
    FOCUSED: 'editor_focused',
    EMPTY: 'editor_empty',
    ERROR: 'editor_error error',
    REQUIRED: 'required'
};

const onRender = function() {
    this.setValue(this.value);
    if (this.focusElement) {
        this.$el.on('focus', this.focusElement, this.onFocus);
        this.$el.on('blur', this.focusElement, this.onBlur);
        this.$el.on('keyup', this.focusElement, this.onKeyup);
    } else if (this.focusElement !== null) {
        this.$el.on('focus', this.onFocus);
        this.$el.on('blur', this.onBlur);
        this.$el.on('keyup', this.onKeyup);
    }

    if (this.enabled) {
        this.__setReadonlyFocusElement(this.readonly);
    } else {
        this.__setEnabledFocusElement(this.enabled);
    }

    // revalidate if model isInvalid
    if (this.model && this.model.validationResult) {
        this.validate();
    }
};

const onChange = function() {
    if (this.model && this.options.autocommit) {
        this.commit();
    }
    if (this.__validatedOnce) {
        if (this.form) {
            this.form.validate();
        } else {
            this.validate();
        }
    }
    this.__updateEmpty();
};

/**
 * @name BaseEditorView
 * @memberof module:core.form.editors.base
 * @class Base class for all editors in the library.
 * While implementing editors, inherit from one of the following classes which in turn are inherited from this one:

 *
BaseCollectionEditorView

 *
BaseEditorView

 * Possible events:

 *
'change' (thisEditorView) - fires when the value inside the editor is changed.
 * This event doesn't imply any change in model (!).

 *
'enabled' (enabled) - fires when the property enabled is changed.

 *
'readonly' (readonly) - fires when the property readonly is changed.

 *
'<key>:committed' (thisEditorView, model, value) - fires when the value is committed into the model.

 *
'value:committed' (thisEditorView, model, key, value) - fires when the value is committed into the model.

 *

 * @constructor
 * @extends Marionette.View
 * @param {Object} options Options object.
 * @param {Boolean} [options.autocommit=false] Indicates whether to call commit() method on the value change.
 * @param {Boolean} [options.forceCommit=false] Indicated whether to commit the value into the model if editors validation has failed (not recommended).
 * @param {Boolean} [options.enabled=true] The initial value of enabled flag. Can be changed later on by calling setEnabled() method.
 * @param {Boolean} [options.readonly=false] The initial value of readonly flag.
 *                                           Can be changed later on by calling setReadonly() method.
 * @param {Boolean} [options.model] A model which contains an attributes edited by this editor.
 *                                  Can only be used if the editor is created standalone (without a form).
 *                                   Must be used together with  key options.
 * @param {Boolean} [options.key] The name of an attribute in options.model edited by this editor.
 *                                Can only be used if the editor is created standalone (without a form).
 *                                Must be used together with  model options.
 * @param {Function[]} [options.validators] An array of validator function which look like the following:
 * function(value, formValues) -> ({type, message}|undefined)
 * */

const defaultOptions = {
    autocommit: false,
    enabled: true,
    readonly: false,
    hidden: false,
    forceCommit: false,
    validators: undefined,
    getFocusElementReadonly: readonly => readonly,
    getFocusElementTabindex: readonly => (readonly ? -1 : 0)
};

export default {
    create(viewClass: Marionette.View | Marionette.CollectionView) {
        return {
            classes,

            hasFocus: false,

            constructor(options: Object = {}) {
                this.onFocus = this.onFocus.bind(this);
                this.onBlur = this.onBlur.bind(this);
                this.checkChange = this.checkChange.bind(this);
                this.onKeyup = this.onKeyup.bind(this);

                //Set initial value
                if (options.model) {
                    this.model = options.model;
                    this.value = this.model.get(options.key);
                } else if (options.value !== undefined) {
                    this.value = options.value;
                }

                if (this.value === undefined) {
                    this.value = null;
                }

                this.key = options.key;
                this.form = options.form;

                this.__validatedOnce = false;

                this.on('render', this.__onEditorRender.bind(this));
                this.on('change', onChange.bind(this));

                const fn = this.setValue;
                this.setValue = function() {
                    fn.apply(this, arguments);
                    if (this.$el) {
                        this.__updateEmpty();
                    }
                };

                this.options = _.defaults({}, options, defaultOptions, this.options);

                this.validators = this.options.validators;
                this.enabled = this.options.enabled;
                this.readonly = this.options.readonly;
                this.hidden = this.options.hidden;

                viewClass.prototype.constructor.apply(this, arguments);

                const isEmpty = this.isEmptyValue();

                const classState = {
                    disabled: !this.enabled,
                    readonly: this.readonly,
                    hidden: this.hidden,
                    EMPTY: isEmpty,
                    REQUIRED: this.options.required && isEmpty
                };

                const classList = Object.entries(classes).reduce((classesList, [key, classString]) => {
                    if (classState[key]) {
                        classesList.push(...classString.split(' '));
                    }
                    return classesList;
                }, []);

                if (classList.length) {
                    this.el.classList.add(...classList);
                }

                if (this.id) {
                    this.el.setAttribute('id', this.id);
                }

                if (this.model) {
                    this.listenTo(this.model, `change:${this.key}`, this.updateValue);
                    this.listenTo(this.model, 'sync', this.updateValue);
                    this.listenTo(this.model, 'validate:force', (e = {}) => {
                        e.validationResult = this.validate();
                    });
                }
            },

            __onEditorRender: onRender,

            __updateEmpty(isEmpty = this.isEmptyValue()) {
                if (this.options.required) {
                    this.__toggleRequiredClass(isEmpty);
                }
                this.$el.toggleClass(classes.EMPTY, Boolean(isEmpty));
            },

            __toggleRequiredClass(required) {
                this.$el.toggleClass(this.classes.REQUIRED, Boolean(required));
            },

            __applyOptions(options, defaults) {
                this.__applyDefaults(options, defaults);
                this.__applyClass();
            },

            __applyDefaults(options, defaults) {
                const defOps = typeof defaults === 'function' ? defaults(options) : defaults;
                this.options = _.defaults({}, options, defOps, this.options);
            },

            __applyClass() {
                if (this.options.class) {
                    this.el.classList.add(...this.options.class.split(' ').filter(className => className));
                }
            },

            setRequired(required = this.options.required) {
                this.options.required = required;
                if (required) {
                    this.__updateEmpty();
                } else {
                    this.__toggleRequiredClass(false);
                }
            },

            /**
             * Manually updated editor's internal value with the value from this.model.get(this.key).
             * Shouldn't be called normally. The method is called internally on model's change event.
             * */
            updateValue(model, value, options) {
                if (options.isEditorSetValue) {
                    return;
                }
                this.setValue(this.getModelValue());
                this.validate();
            },

            /**
             * Retrieves actual value of the bound attribute from the model.
             * @return {*}
             * */
            getModelValue() {
                return !this.model ? undefined : this.model.get(this.key);
            },

            __getFocusElement() {
                if (this.focusElement) {
                    return this.__focusElement || (this.__focusElement = this.$el.find(this.focusElement));
                }
                return this.$el;
            },

            __setEnabledFocusElement(enabled) {
                if (this.focusElement === null) {
                    return;
                }
                this.__getFocusElement().prop('disabled', !enabled);
            },

            __setReadonlyFocusElement(readonly) {
                if (this.focusElement === null) {
                    return;
                }
                if (this.getEnabled()) {
                    const focusElement = this.__getFocusElement();
                    focusElement.prop('readonly', this.options.getFocusElementReadonly(readonly));
                    focusElement.prop('tabindex', this.options.getFocusElementTabindex(readonly));
                }
            },

            __triggerChange(...args: Array<any>) {
                this.trigger('change', this, ...args);
            },

            /**
             * Returns internal editor's value.
             * @return {*}
             */
            getValue() {
                return this.value;
            },

            /**
             * Sets new internal editor's value.
             * @param {*} value The new value.
             */
            setValue(value: Number | String) {
                this.value = value;
            },

            setPermissions(enabled: Boolean, readonly: Boolean) {
                this.__setEnabled(enabled);
                this.__setReadonly(readonly);
            },

            /**
             * Sets a new value of enabled flag. While disabled, the editor's value cannot be changed or copied by the user.
             * It's implied that the value doesn't make sense.
             * @param {Boolean} enabled New flag value.
             */
            setEnabled(enabled: Boolean) {
                const readonly = this.getReadonly();
                this.setPermissions(enabled, readonly);
            },

            /**
             * Sets a new value of readonly flag. While readonly, the editor's value cannot be changed but can be copied by the user.
             * @param {Boolean} readonly New flag value.
             */
            setReadonly(readonly: Boolean) {
                const enabled = this.getEnabled();
                this.setPermissions(enabled, readonly);
            },

            /**
             * Sets a new value of hidden flag.
             * @param {Boolean} hidden New flag value.
             */
            setHidden(hidden: Boolean) {
                this.hidden = hidden;
                this.$el.toggleClass(classes.hidden, hidden);
            },

            __setEnabled(enabled: Boolean) {
                this.enabled = enabled;
                this.__setEnabledFocusElement(enabled);
                if (!this.enabled) {
                    this.el.classList.add(classes.disabled);
                } else {
                    this.el.classList.remove(classes.disabled);
                }
                this.trigger('enabled', enabled);
            },

            /**
             * Returns the value of `enabled` flag.
             * @return {Boolean}
             */
            getEnabled() {
                return this.enabled;
            },

            /**
             * Returns the value of `enabled` flag.
             * @return {Boolean}
             */
            getHidden() {
                return this.hidden;
            },

            __setReadonly(readonly: Boolean) {
                this.readonly = readonly;
                this.__setReadonlyFocusElement(readonly);
                if (this.readonly && this.getEnabled()) {
                    this.el.classList.add(classes.readonly);
                } else {
                    this.el.classList.remove(classes.readonly);
                }
                this.trigger('readonly', readonly);
            },

            /**
             * Returns the value of `readonly` flag.
             * @return {Boolean}
             */
            getReadonly() {
                return this.readonly;
            },

            getEditable() {
                return this.getEnabled() && !this.getReadonly();
            },

            /**
             * Sets the focus onto this editor.
             */
            focus() {
                //TODO if focusElement === null ?
                this.__getFocusElement().focus();
                this.hasFocus = true;
            },

            /**
             * Clears the focus.
             */
            blur() {
                //TODO if focusElement === null ?
                this.__getFocusElement().blur();
                this.hasFocus = false;
            },

            /**
             * Update the model with the internal editor's value.
             * @param {Object} [options] Options to pass to model.set().
             * @param {Boolean} [options.validate] Set to true to trigger built-in model validation.
             * @return {Object|undefined} Returns an error object { type, message } if validation fails
             * and options.forceCommit is turned off. undefined otherwise.
             */
            commit(options: Object = {}) {
                let error = this.validate(true);
                if (error && !this.options.forceCommit) {
                    return error;
                }

                this.listenToOnce(this.model, 'invalid', (model, e) => {
                    error = e;
                });

                this.model.set(this.key, this.getValue(), {
                    silent: false,
                    validate: options.validate === true,
                    isEditorSetValue: true
                });

                if (error && !this.options.forceCommit) {
                    return error;
                }
                this.trigger(`${this.key}:committed`, this, this.model, this.getValue());
                this.trigger('value:committed', this, this.model, this.key, this.getValue());
            },
            isEmptyValue() {
                return !this.getValue();
            },

            /**
             * Check validity with built-in validator functions (initially passed into constructor options).
             * @return {Object|undefined} Returns an error object { type, message } if validation fails. undefined otherwise.
             */
            validate(internal: Boolean) {
                let error = null;
                const value = this.getValue();
                const formValues = this.form ? this.form.getValue() : {};
                const validators = this.validators;
                const getValidator = this.getValidator;

                if (!internal) {
                    this.__validatedOnce = true;
                }

                if (validators) {
                    //Run through validators until an error is found
                    validators.every(validator => {
                        error = getValidator(validator)(value, formValues);
                        return !error;
                    });
                }

                if (this.isRendered() && !this.isDestroyed()) {
                    this.$el.toggleClass(classes.ERROR, !!error);
                }

                return error;
            },

            trigger(event: 'focus' | 'blur') {
                if (event === 'focus') {
                    this.hasFocus = true;
                } else if (event === 'blur') {
                    this.hasFocus = false;
                }

                return Marionette.View.prototype.trigger.apply(this, arguments);
            },

            getValidator(validator: string | Function) {
                const validators = formRepository.validators;

                //Convert regular expressions to validators
                if (_.isRegExp(validator)) {
                    return validators.regexp({ regexp: validator });
                }

                //Use a built-in validator if given a string
                if (typeof validator === 'string') {
                    if (!validators[validator]) {
                        throw new Error(`Validator "${validator}" not found`);
                    }

                    return validators[validator]();
                }

                //Functions can be used directly
                if (typeof validator === 'function') {
                    return validator;
                }

                //Use a customised built-in validator if given an object
                //noinspection JSUnresolvedVariable
                if (_.isObject(validator) && validator.type) {
                    const config = validator;

                    //noinspection JSUnresolvedVariable
                    return validators[config.type](config);
                }

                //Unknown validator type
                throw new Error('Invalid validator');
            },

            checkChange() {
                if (this.model) {
                    if (this.value !== this.model.get(this.key)) {
                        this.__triggerChange();
                    }
                }
            },

            onKeyup(event) {
                if (event.keyCode === keyCode.ENTER) {
                    this.checkChange();
                }
            },

            onFocus(event, options) {
                this.el.classList.add(classes.FOCUSED);
                //ToDo what for pass 'this' as first argument ?
                this.trigger('focus', this, event, options);
            },

            onBlur(event, options = {}) {
                if (options.triggerChange === undefined || options.triggerChange === true) {
                    this.checkChange();
                }
                this.el.classList.remove(classes.FOCUSED);
                this.trigger('blur', this, event, options);
            },

            renderIcons(...iconTemplates) {
                this.el.insertAdjacentHTML('beforeend', iconTemplates.join(' '));
            }
        };
    }
};
<commit_msg>Fix native js api.<commit_after>// @flow
import formRepository from '../../formRepository';
import { keyCode } from 'utils';

const classes = {
    editorDisabled: 'editor_disabled',
    disabled: 'disabled',
    readonly: 'readonly',
    editorReadonly: 'editor_readonly',
    hidden: 'editor_hidden',
    FOCUSED: 'editor_focused',
    EMPTY: 'editor_empty',
    ERROR: 'editor_error error',
    REQUIRED: 'required'
};

const onRender = function() {
    this.setValue(this.value);
    if (this.focusElement) {
        this.$el.on('focus', this.focusElement, this.onFocus);
        this.$el.on('blur', this.focusElement, this.onBlur);
        this.$el.on('keyup', this.focusElement, this.onKeyup);
    } else if (this.focusElement !== null) {
        this.$el.on('focus', this.onFocus);
        this.$el.on('blur', this.onBlur);
        this.$el.on('keyup', this.onKeyup);
    }

    if (this.enabled) {
        this.__setReadonlyFocusElement(this.readonly);
    } else {
        this.__setEnabledFocusElement(this.enabled);
    }

    // revalidate if model isInvalid
    if (this.model && this.model.validationResult) {
        this.validate();
    }
};

const onChange = function() {
    if (this.model && this.options.autocommit) {
        this.commit();
    }
    if (this.__validatedOnce) {
        if (this.form) {
            this.form.validate();
        } else {
            this.validate();
        }
    }
    this.__updateEmpty();
};

/**
 * @name BaseEditorView
 * @memberof module:core.form.editors.base
 * @class Base class for all editors in the library.
 * While implementing editors, inherit from one of the following classes which in turn are inherited from this one:

 *
BaseCollectionEditorView

 *
BaseEditorView

 * Possible events:

 *
'change' (thisEditorView) - fires when the value inside the editor is changed.
 * This event doesn't imply any change in model (!).

 *
'enabled' (enabled) - fires when the property enabled is changed.

 *
'readonly' (readonly) - fires when the property readonly is changed.

 *
'<key>:committed' (thisEditorView, model, value) - fires when the value is committed into the model.

 *
'value:committed' (thisEditorView, model, key, value) - fires when the value is committed into the model.

 *

 * @constructor
 * @extends Marionette.View
 * @param {Object} options Options object.
 * @param {Boolean} [options.autocommit=false] Indicates whether to call commit() method on the value change.
 * @param {Boolean} [options.forceCommit=false] Indicated whether to commit the value into the model if editors validation has failed (not recommended).
 * @param {Boolean} [options.enabled=true] The initial value of enabled flag. Can be changed later on by calling setEnabled() method.
 * @param {Boolean} [options.readonly=false] The initial value of readonly flag.
 *                                           Can be changed later on by calling setReadonly() method.
 * @param {Boolean} [options.model] A model which contains an attributes edited by this editor.
 *                                  Can only be used if the editor is created standalone (without a form).
 *                                   Must be used together with  key options.
 * @param {Boolean} [options.key] The name of an attribute in options.model edited by this editor.
 *                                Can only be used if the editor is created standalone (without a form).
 *                                Must be used together with  model options.
 * @param {Function[]} [options.validators] An array of validator function which look like the following:
 * function(value, formValues) -> ({type, message}|undefined)
 * */

const defaultOptions = {
    autocommit: false,
    enabled: true,
    readonly: false,
    hidden: false,
    forceCommit: false,
    validators: undefined,
    getFocusElementReadonly: readonly => readonly,
    getFocusElementTabindex: readonly => (readonly ? -1 : 0)
};

export default {
    create(viewClass: Marionette.View | Marionette.CollectionView) {
        return {
            classes,

            hasFocus: false,

            constructor(options: Object = {}) {
                this.onFocus = this.onFocus.bind(this);
                this.onBlur = this.onBlur.bind(this);
                this.checkChange = this.checkChange.bind(this);
                this.onKeyup = this.onKeyup.bind(this);

                //Set initial value
                if (options.model) {
                    this.model = options.model;
                    this.value = this.model.get(options.key);
                } else if (options.value !== undefined) {
                    this.value = options.value;
                }

                if (this.value === undefined) {
                    this.value = null;
                }

                this.key = options.key;
                this.form = options.form;

                this.__validatedOnce = false;

                this.on('render', this.__onEditorRender.bind(this));
                this.on('change', onChange.bind(this));

                const fn = this.setValue;
                this.setValue = function() {
                    fn.apply(this, arguments);
                    if (this.$el) {
                        this.__updateEmpty();
                    }
                };

                this.options = _.defaults({}, options, defaultOptions, this.options);

                this.validators = this.options.validators;
                this.enabled = this.options.enabled;
                this.readonly = this.options.readonly;
                this.hidden = this.options.hidden;

                viewClass.prototype.constructor.apply(this, arguments);

                const isEmpty = this.isEmptyValue();

                const classState = {
                    disabled: !this.enabled,
                    readonly: this.readonly,
                    hidden: this.hidden,
                    EMPTY: isEmpty,
                    REQUIRED: this.options.required && isEmpty
                };

                const classList = Object.entries(classes).reduce((classesList, [key, classString]) => {
                    if (classState[key]) {
                        classesList.push(...classString.split(' '));
                    }
                    return classesList;
                }, []);

                if (classList.length) {
                    this.el.classList.add(...classList);
                }

                if (this.id) {
                    this.el.setAttribute('id', this.id);
                }

                if (this.model) {
                    this.listenTo(this.model, `change:${this.key}`, this.updateValue);
                    this.listenTo(this.model, 'sync', this.updateValue);
                    this.listenTo(this.model, 'validate:force', (e = {}) => {
                        e.validationResult = this.validate();
                    });
                }
            },

            __onEditorRender: onRender,

            __updateEmpty(isEmpty = this.isEmptyValue()) {
                if (this.options.required) {
                    this.__toggleRequiredClass(isEmpty);
                }
                this.$el.toggleClass(classes.EMPTY, Boolean(isEmpty));
            },

            __toggleRequiredClass(required) {
                this.$el.toggleClass(this.classes.REQUIRED, Boolean(required));
            },

            __applyOptions(options, defaults) {
                this.__applyDefaults(options, defaults);
                this.__applyClass();
            },

            __applyDefaults(options, defaults) {
                const defOps = typeof defaults === 'function' ? defaults(options) : defaults;
                this.options = _.defaults({}, options, defOps, this.options);
            },

            __applyClass() {
                if (this.options.class) {
                    this.el.classList.add(...this.options.class.split(' ').filter(className => className));
                }
            },

            setRequired(required = this.options.required) {
                this.options.required = required;
                if (required) {
                    this.__updateEmpty();
                } else {
                    this.__toggleRequiredClass(false);
                }
            },

            /**
             * Manually updated editor's internal value with the value from this.model.get(this.key).
             * Shouldn't be called normally. The method is called internally on model's change event.
             * */
            updateValue(model, value, options) {
                if (options.isEditorSetValue) {
                    return;
                }
                this.setValue(this.getModelValue());
                this.validate();
            },

            /**
             * Retrieves actual value of the bound attribute from the model.
             * @return {*}
             * */
            getModelValue() {
                return !this.model ? undefined : this.model.get(this.key);
            },

            __getFocusElement() {
                if (this.focusElement) {
                    return this.__focusElement || (this.__focusElement = this.$el.find(this.focusElement));
                }
                return this.$el;
            },

            __setEnabledFocusElement(enabled) {
                if (this.focusElement === null) {
                    return;
                }
                this.__getFocusElement().prop('disabled', !enabled);
            },

            __setReadonlyFocusElement(readonly) {
                if (this.focusElement === null) {
                    return;
                }
                if (this.getEnabled()) {
                    const focusElement = this.__getFocusElement();
                    focusElement.prop('readonly', this.options.getFocusElementReadonly(readonly));
                    focusElement.prop('tabindex', this.options.getFocusElementTabindex(readonly));
                }
            },

            __triggerChange(...args: Array<any>) {
                this.trigger('change', this, ...args);
            },

            /**
             * Returns internal editor's value.
             * @return {*}
             */
            getValue() {
                return this.value;
            },

            /**
             * Sets new internal editor's value.
             * @param {*} value The new value.
             */
            setValue(value: Number | String) {
                this.value = value;
            },

            setPermissions(enabled: Boolean, readonly: Boolean) {
                this.__setEnabled(enabled);
                this.__setReadonly(readonly);
            },

            /**
             * Sets a new value of enabled flag. While disabled, the editor's value cannot be changed or copied by the user.
             * It's implied that the value doesn't make sense.
             * @param {Boolean} enabled New flag value.
             */
            setEnabled(enabled: Boolean) {
                const readonly = this.getReadonly();
                this.setPermissions(enabled, readonly);
            },

            /**
             * Sets a new value of readonly flag. While readonly, the editor's value cannot be changed but can be copied by the user.
             * @param {Boolean} readonly New flag value.
             */
            setReadonly(readonly: Boolean) {
                const enabled = this.getEnabled();
                this.setPermissions(enabled, readonly);
            },

            /**
             * Sets a new value of hidden flag.
             * @param {Boolean} hidden New flag value.
             */
            setHidden(hidden: Boolean) {
                this.hidden = hidden;
                this.$el.toggleClass(classes.hidden, hidden);
            },

            __setEnabled(enabled: Boolean) {
                this.enabled = enabled;
                this.__setEnabledFocusElement(enabled);
                if (!this.enabled) {
                    this.el.classList.add(classes.disabled, classes.editorDisabled);
                } else {
                    this.el.classList.remove(classes.disabled, classes.editorDisabled);
                }
                this.trigger('enabled', enabled);
            },

            /**
             * Returns the value of `enabled` flag.
             * @return {Boolean}
             */
            getEnabled() {
                return this.enabled;
            },

            /**
             * Returns the value of `enabled` flag.
             * @return {Boolean}
             */
            getHidden() {
                return this.hidden;
            },

            __setReadonly(readonly: Boolean) {
                this.readonly = readonly;
                this.__setReadonlyFocusElement(readonly);
                if (this.readonly && this.getEnabled()) {
                    this.el.classList.add(classes.readonly, classes.editorReadonly);
                } else {
                    this.el.classList.remove(classes.readonly, classes.editorReadonly);
                }
                this.trigger('readonly', readonly);
            },

            /**
             * Returns the value of `readonly` flag.
             * @return {Boolean}
             */
            getReadonly() {
                return this.readonly;
            },

            getEditable() {
                return this.getEnabled() && !this.getReadonly();
            },

            /**
             * Sets the focus onto this editor.
             */
            focus() {
                //TODO if focusElement === null ?
                this.__getFocusElement().focus();
                this.hasFocus = true;
            },

            /**
             * Clears the focus.
             */
            blur() {
                //TODO if focusElement === null ?
                this.__getFocusElement().blur();
                this.hasFocus = false;
            },

            /**
             * Update the model with the internal editor's value.
             * @param {Object} [options] Options to pass to model.set().
             * @param {Boolean} [options.validate] Set to true to trigger built-in model validation.
             * @return {Object|undefined} Returns an error object { type, message } if validation fails
             * and options.forceCommit is turned off. undefined otherwise.
             */
            commit(options: Object = {}) {
                let error = this.validate(true);
                if (error && !this.options.forceCommit) {
                    return error;
                }

                this.listenToOnce(this.model, 'invalid', (model, e) => {
                    error = e;
                });

                this.model.set(this.key, this.getValue(), {
                    silent: false,
                    validate: options.validate === true,
                    isEditorSetValue: true
                });

                if (error && !this.options.forceCommit) {
                    return error;
                }
                this.trigger(`${this.key}:committed`, this, this.model, this.getValue());
                this.trigger('value:committed', this, this.model, this.key, this.getValue());
            },
            isEmptyValue() {
                return !this.getValue();
            },

            /**
             * Check validity with built-in validator functions (initially passed into constructor options).
             * @return {Object|undefined} Returns an error object { type, message } if validation fails. undefined otherwise.
             */
            validate(internal: Boolean) {
                let error = null;
                const value = this.getValue();
                const formValues = this.form ? this.form.getValue() : {};
                const validators = this.validators;
                const getValidator = this.getValidator;

                if (!internal) {
                    this.__validatedOnce = true;
                }

                if (validators) {
                    //Run through validators until an error is found
                    validators.every(validator => {
                        error = getValidator(validator)(value, formValues);
                        return !error;
                    });
                }

                if (this.isRendered() && !this.isDestroyed()) {
                    this.$el.toggleClass(classes.ERROR, !!error);
                }

                return error;
            },

            trigger(event: 'focus' | 'blur') {
                if (event === 'focus') {
                    this.hasFocus = true;
                } else if (event === 'blur') {
                    this.hasFocus = false;
                }

                return Marionette.View.prototype.trigger.apply(this, arguments);
            },

            getValidator(validator: string | Function) {
                const validators = formRepository.validators;

                //Convert regular expressions to validators
                if (_.isRegExp(validator)) {
                    return validators.regexp({ regexp: validator });
                }

                //Use a built-in validator if given a string
                if (typeof validator === 'string') {
                    if (!validators[validator]) {
                        throw new Error(`Validator "${validator}" not found`);
                    }

                    return validators[validator]();
                }

                //Functions can be used directly
                if (typeof validator === 'function') {
                    return validator;
                }

                //Use a customised built-in validator if given an object
                //noinspection JSUnresolvedVariable
                if (_.isObject(validator) && validator.type) {
                    const config = validator;

                    //noinspection JSUnresolvedVariable
                    return validators[config.type](config);
                }

                //Unknown validator type
                throw new Error('Invalid validator');
            },

            checkChange() {
                if (this.model) {
                    if (this.value !== this.model.get(this.key)) {
                        this.__triggerChange();
                    }
                }
            },

            onKeyup(event) {
                if (event.keyCode === keyCode.ENTER) {
                    this.checkChange();
                }
            },

            onFocus(event, options) {
                this.el.classList.add(classes.FOCUSED);
                //ToDo what for pass 'this' as first argument ?
                this.trigger('focus', this, event, options);
            },

            onBlur(event, options = {}) {
                if (options.triggerChange === undefined || options.triggerChange === true) {
                    this.checkChange();
                }
                this.el.classList.remove(classes.FOCUSED);
                this.trigger('blur', this, event, options);
            },

            renderIcons(...iconTemplates) {
                this.el.insertAdjacentHTML('beforeend', iconTemplates.join(' '));
            }
        };
    }
};
<|endoftext|>


<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var http = require('http'),
    log4js = require("log4js"),
    fs = require('fs'),
    path = require('path'),
    portchecker = require("../../ext-lib/portchecker"),
    url = require('url');

function ProxyManager(routerConfig) {
    this.routerJsonPath = routerConfig;
    this.logger = log4js.getLogger("ProxyManager");
    this.fileName = path.resolve(global.workingDirectory, "proxy.log");
    this.record = [];
}

ProxyManager.prototype.runRouterProxy = function(minPort, maxPort, host, callback) {
    var options, router, proxy, proxy_request,
        self = this,
        hd,
        i,
        objUrl;
    this.logger.info("Starting Proxy");
    try {

        if (self.routerJsonPath) {
            router = JSON.parse(fs.readFileSync(self.routerJsonPath, "utf-8"));
        } else {
            router = {};
        }

        this.logger.info("Proxy Router Config :" + JSON.stringify(router));

        portchecker.getFirstAvailable(minPort, maxPort, host, function(p, host) {
            if (p === -1) {
                callback("Error : No free ports found for Proxy Server on " + host + " between " + minPort + " and " + minPort);
            } else {

                self.proxyServer = http.createServer(function (request, response) {
                    var reqHost = request.headers['host'],
                        reqUrl = request.url,
                        reqHeaders = request.headers,
                        port = 80;
                    if (router[reqHost]) {
                        hd = router[reqHost].headers;
                        if (hd) {
                            for (i = 0; i < hd.length; i += 1) {
                                reqHeaders[hd[i].param] = hd[i].value;
                            }
                        }
                        if (router[reqHost].record) {
                            self.record.push({"url": reqUrl, "headers": request.headers, "method": request.method});
                        }
                        if (router[reqHost].newHost) {
                            reqUrl = reqUrl.replace(reqHost, router[reqHost].newHost);
                            reqHost = router[reqHost].newHost;
                        }
                    }

                    objUrl = url.parse(reqUrl);
                    if (objUrl.port) {
                        try {
                            if (port !== undefined) {
                                port = objUrl.port;
                            }
                        } catch (e) {
                            port = 80;
                        }
                    }

                    options = {
                        host: reqHost,
                        port: port,
                        path: reqUrl,
                        method: request.method,
                        headers: reqHeaders
                    };

                    proxy_request = http.request(options, function(proxy_response) {

                        proxy_response.addListener('data', function(chunk) {
                            response.write(chunk, 'binary');
                        });

                        proxy_response.addListener('end', function() {
                            response.end();
                        });

                        self.writeLog(port + ":" + reqUrl + ":" + proxy_response.statusCode);
                        response.writeHead(proxy_response.statusCode, proxy_response.headers);

                    });

                    request.addListener('data', function(chunk) {
                        proxy_request.write(chunk, 'binary');
                    });

                    request.addListener('end', function() {
                        proxy_request.end();
                    });

                    proxy_request.on('error', function (err, req, res) {
                        self.logger.warn("Proxy Error, Request URL : " + request.url);
                        response.writeHead(500, {
                            'Content-Type': 'text/plain'
                        });
                        response.end('Something went wrong: ' + JSON.stringify(err));
                    });

                }).listen(p);
                callback(host + ":" + p);
            }
        });
    } catch (e) {
        //console.log("Error :" + e.toString());
        callback("Error :" + e.toString());
    }
};

ProxyManager.prototype.writeLog = function (logLine) {
    //console.log(logLine);
    var stream = fs.createWriteStream(this.fileName);
    stream.once('open', function(fd) {
        stream.write(logLine + "\n");
    });

};

module.exports = ProxyManager;
<commit_msg>Refactored to keep getOtions() method out of runRouterProxy()<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var http = require('http'),
    log4js = require("log4js"),
    fs = require('fs'),
    path = require('path'),
    portchecker = require("../../ext-lib/portchecker"),
    url = require('url');

function ProxyManager(routerConfig) {
    this.routerJsonPath = routerConfig;
    this.logger = log4js.getLogger("ProxyManager");
    this.fileName = path.resolve(global.workingDirectory, "proxy.log");
    this.record = [];
}

function getOptions(router,request){

    var reqHost = request.headers['host'],
        reqUrl = request.url,
        reqHeaders = request.headers,
        port = 80,
        options,
        objUrl,
        i;

    if (router[reqHost]) {
        hd = router[reqHost].headers;
        if (hd) {
            for (i = 0; i < hd.length; i += 1) {
                reqHeaders[hd[i].param] = hd[i].value;
            }
        }
        if (router[reqHost].record) {
            self.record.push({"url": reqUrl, "headers": request.headers, "method": request.method});
        }
        if (router[reqHost].newHost) {
            reqUrl = reqUrl.replace(reqHost, router[reqHost].newHost);
            reqHost = router[reqHost].newHost;
        }
    }

    objUrl = url.parse(reqUrl);
    if (objUrl.port) {
        try {
            if (port !== undefined) {
                port = objUrl.port;
            }
        } catch (e) {
            port = 80;
        }
    }

    options = {
        host: reqHost,
        port: port,
        path: reqUrl,
        method: request.method,
        headers: reqHeaders
    };

    return options;

}

ProxyManager.prototype.runRouterProxy = function(minPort, maxPort, host, callback) {
    var options, router, proxy, proxy_request,
        self = this,
        hd,
        i,
        objUrl;
    this.logger.info("Starting Proxy");
    try {

        if (self.routerJsonPath) {
            router = JSON.parse(fs.readFileSync(self.routerJsonPath, "utf-8"));
        } else {
            router = {};
        }

        this.logger.info("Proxy Router Config :" + JSON.stringify(router));

        portchecker.getFirstAvailable(minPort, maxPort, host, function(p, host) {
            if (p === -1) {
                callback("Error : No free ports found for Proxy Server on " + host + " between " + minPort + " and " + minPort);
            } else {

                self.proxyServer = http.createServer(function (request, response) {

                    options = getOptions(router,request);

                    proxy_request = http.request(options, function(proxy_response) {

                        proxy_response.addListener('data', function(chunk) {
                            response.write(chunk, 'binary');
                        });

                        proxy_response.addListener('end', function() {
                            response.end();
                        });

                        self.writeLog(port + ":" + reqUrl + ":" + proxy_response.statusCode);
                        response.writeHead(proxy_response.statusCode, proxy_response.headers);

                    });

                    request.addListener('data', function(chunk) {
                        proxy_request.write(chunk, 'binary');
                    });

                    request.addListener('end', function() {
                        proxy_request.end();
                    });

                    proxy_request.on('error', function (err, req, res) {
                        self.logger.warn("Proxy Error, Request URL : " + request.url);
                        response.writeHead(500, {
                            'Content-Type': 'text/plain'
                        });
                        response.end('Something went wrong: ' + JSON.stringify(err));
                    });

                }).listen(p);
                callback(host + ":" + p);
            }
        });
    } catch (e) {
        //console.log("Error :" + e.toString());
        callback("Error :" + e.toString());
    }
};

ProxyManager.prototype.writeLog = function (logLine) {
    //console.log(logLine);
    var stream = fs.createWriteStream(this.fileName);
    stream.once('open', function(fd) {
        stream.write(logLine + "\n");
    });

};

module.exports = ProxyManager;<|endoftext|>


<commit_before>/**
 * File: AssetAdmin.js
 */

(function($) {
	/**
	 * Delete selected folders through "batch actions" tab.
	 */
	$(document).ready(function() {
		$('#Form_BatchActionsForm').entwine('ss').register(
			// TODO Hardcoding of base URL
			'admin/assets/batchactions/delete',
			function(ids) {
				var confirmed = confirm(
					ss.i18n.sprintf(
						ss.i18n._t('AssetAdmin.BATCHACTIONSDELETECONFIRM'),
						ids.length
					)
				);
				return (confirmed) ? ids : false;
			}
		);
	});

	$.entwine('ss', function($){

		/**
		 * Load folder detail view via controller methods
		 * rather than built-in GridField view (which is only geared towards showing files).
		 */
		$('.AssetAdmin.cms-edit-form .ss-gridfield-item').entwine({
			onclick: function(e) {
				// Let actions do their own thing
				if($(e.target).closest('.action').length) {
					this._super(e);
					return;
				}

				var grid = this.closest('.ss-gridfield');
				if(this.data('class') == 'Folder') {
					var url = grid.data('urlFolderTemplate').replace('%s', this.data('id'));
					$('.cms-container').loadPanel(url);
					return false;
				}
			}
		});

		$('.AssetAdmin.cms-edit-form .action.gridfield-button-delete').entwine({
			onclick: function(e) {
				var msg;
				if(this.closest('.ss-gridfield-item').data('class') == 'Folder') {
					msg = ss.i18n._t('AssetAdmin.ConfirmDelete');
				} else {
					msg = ss.i18n._t('TABLEFIELD.DELETECONFIRMMESSAGE');
				}
				if(!confirm(msg)) return false;

				this.getGridField().reload({data: [{name: this.attr('name'), value: this.val()}]});
				e.preventDefault();
				return false;
			}
		});

		$('.AssetAdmin.cms-edit-form :submit[name=action_delete]').entwine({
			onclick: function(e) {
				if(!confirm(ss.i18n._t('AssetAdmin.ConfirmDelete'))) return false;
				else this._super(e);
			}
		});

		/**
		 * Prompt for a new foldername, rather than using dedicated form.
		 * Better usability, but less flexibility in terms of inputs and validation.
		 * Mainly necessary because AssetAdmin->AddForm() returns don't play nicely
		 * with the nested AssetAdmin->EditForm() DOM structures.
		 */
		$('.AssetAdmin .cms-add-folder-link').entwine({
			onclick: function(e) {
				var name = prompt(ss.i18n._t('Folder.Name'));
				if(!name) return false;

				this.closest('.cms-container').loadPanel(this.data('url') + '&Name=' + name);
				return false;
			}
		});

		/**
		 * Class: #Form_SyncForm
		 */
		$('#Form_SyncForm').entwine({

			/**
			 * Function: onsubmit
			 *
			 * Parameters:
			 *  (Event) e
			 */
			onsubmit: function(e) {
				var button = jQuery(this).find(':submit:first');
				button.addClass('loading');
				$.ajax({
					url: jQuery(this).attr('action'),
					data: this.serializeArray(),
					success: function() {
						button.removeClass('loading');
						// reload current form and tree
						var currNode = $('.cms-tree')[0].firstSelected();
						if(currNode) {
						  var url = $(currNode).find('a').attr('href');
							$('.cms-content').loadForm(url);
						}
						$('.cms-tree')[0].setCustomURL('admin/assets/getsubtree');
						$('.cms-tree')[0].reload({onSuccess: function() {
							// TODO Reset current tree node
						}});
					}
				});

				return false;
			}
		});
	});
}(jQuery));<commit_msg>MINOR Using loadPanel() rather than removed duplicate loadForm() method<commit_after>/**
 * File: AssetAdmin.js
 */

(function($) {
	/**
	 * Delete selected folders through "batch actions" tab.
	 */
	$(document).ready(function() {
		$('#Form_BatchActionsForm').entwine('ss').register(
			// TODO Hardcoding of base URL
			'admin/assets/batchactions/delete',
			function(ids) {
				var confirmed = confirm(
					ss.i18n.sprintf(
						ss.i18n._t('AssetAdmin.BATCHACTIONSDELETECONFIRM'),
						ids.length
					)
				);
				return (confirmed) ? ids : false;
			}
		);
	});

	$.entwine('ss', function($){

		/**
		 * Load folder detail view via controller methods
		 * rather than built-in GridField view (which is only geared towards showing files).
		 */
		$('.AssetAdmin.cms-edit-form .ss-gridfield-item').entwine({
			onclick: function(e) {
				// Let actions do their own thing
				if($(e.target).closest('.action').length) {
					this._super(e);
					return;
				}

				var grid = this.closest('.ss-gridfield');
				if(this.data('class') == 'Folder') {
					var url = grid.data('urlFolderTemplate').replace('%s', this.data('id'));
					$('.cms-container').loadPanel(url);
					return false;
				}
			}
		});

		$('.AssetAdmin.cms-edit-form .action.gridfield-button-delete').entwine({
			onclick: function(e) {
				var msg;
				if(this.closest('.ss-gridfield-item').data('class') == 'Folder') {
					msg = ss.i18n._t('AssetAdmin.ConfirmDelete');
				} else {
					msg = ss.i18n._t('TABLEFIELD.DELETECONFIRMMESSAGE');
				}
				if(!confirm(msg)) return false;

				this.getGridField().reload({data: [{name: this.attr('name'), value: this.val()}]});
				e.preventDefault();
				return false;
			}
		});

		$('.AssetAdmin.cms-edit-form :submit[name=action_delete]').entwine({
			onclick: function(e) {
				if(!confirm(ss.i18n._t('AssetAdmin.ConfirmDelete'))) return false;
				else this._super(e);
			}
		});

		/**
		 * Prompt for a new foldername, rather than using dedicated form.
		 * Better usability, but less flexibility in terms of inputs and validation.
		 * Mainly necessary because AssetAdmin->AddForm() returns don't play nicely
		 * with the nested AssetAdmin->EditForm() DOM structures.
		 */
		$('.AssetAdmin .cms-add-folder-link').entwine({
			onclick: function(e) {
				var name = prompt(ss.i18n._t('Folder.Name'));
				if(!name) return false;

				this.closest('.cms-container').loadPanel(this.data('url') + '&Name=' + name);
				return false;
			}
		});

		/**
		 * Class: #Form_SyncForm
		 */
		$('#Form_SyncForm').entwine({

			/**
			 * Function: onsubmit
			 *
			 * Parameters:
			 *  (Event) e
			 */
			onsubmit: function(e) {
				var button = jQuery(this).find(':submit:first');
				button.addClass('loading');
				$.ajax({
					url: jQuery(this).attr('action'),
					data: this.serializeArray(),
					success: function() {
						button.removeClass('loading');
						// reload current form and tree
						var currNode = $('.cms-tree')[0].firstSelected();
						if(currNode) {
						  var url = $(currNode).find('a').attr('href');
							$('.cms-content').loadPanel(url);
						}
						$('.cms-tree')[0].setCustomURL('admin/assets/getsubtree');
						$('.cms-tree')[0].reload({onSuccess: function() {
							// TODO Reset current tree node
						}});
					}
				});

				return false;
			}
		});
	});
}(jQuery));<|endoftext|>


<commit_before>var frames = require("ui/frame");
var main_view_model_1 = require("./main-view-model");
function pageLoaded(args) {
    var page = args.object;
    page.bindingContext = new main_view_model_1.MainViewModel();
}
exports.pageLoaded = pageLoaded;
function statusItemTap(args) {
    exports.selectedStatusItem = args.view.bindingContext;
    frames.topmost().navigate("./views/status/status-details-page");
}
exports.statusItemTap = statusItemTap;
function incidentsItemTap(args) {
    exports.selectedIncidentItem = args.view.bindingContext;
    frames.topmost().navigate("./views/incidents/incidents-details-page");
}
exports.incidentsItemTap = incidentsItemTap;
function blogItemTap(args) {
    exports.selectedBlogItem = args.view.bindingContext;
    frames.topmost().navigate("./views/news/news-details-page");
}
exports.blogItemTap = blogItemTap;
function notificationItemTap(args) {
    exports.selectedNotificationItem = args.view.bindingContext;
    frames.topmost().navigate("./views/notifications/notifications-details-page");
}
exports.notificationItemTap = notificationItemTap;
<commit_msg>Main-page compile<commit_after>var frames = require("ui/frame");
var main_view_model_1 = require("./main-view-model");
var local_notifications_1 = require("./services/notifications/local-notifications");
var push_notifications_1 = require("./services/notifications/push-notifications");
push_notifications_1.PushNotificationsService.register(function (message, title) {
    local_notifications_1.NotificationsService.raiseNotification(message, title);
});
function pageLoaded(args) {
    var page = args.object;
    page.bindingContext = new main_view_model_1.MainViewModel();
}
exports.pageLoaded = pageLoaded;
function statusItemTap(args) {
    exports.selectedStatusItem = args.view.bindingContext;
    frames.topmost().navigate("./views/status/status-details-page");
}
exports.statusItemTap = statusItemTap;
function incidentsItemTap(args) {
    exports.selectedIncidentItem = args.view.bindingContext;
    frames.topmost().navigate("./views/incidents/incidents-details-page");
}
exports.incidentsItemTap = incidentsItemTap;
function blogItemTap(args) {
    exports.selectedBlogItem = args.view.bindingContext;
    frames.topmost().navigate("./views/news/news-details-page");
}
exports.blogItemTap = blogItemTap;
function notificationItemTap(args) {
    exports.selectedNotificationItem = args.view.bindingContext;
    frames.topmost().navigate("./views/notifications/notifications-details-page");
}
exports.notificationItemTap = notificationItemTap;
<|endoftext|>


<commit_before>const path = require('path');
const { readdirSync } = require('fs');

const allWidgets = readdirSync(path.resolve(__dirname, 'src/components'));

module.exports = {
  mode: 'production',
  entry: {
    VeritoneApp: path.resolve(__dirname, 'src/shared/VeritoneApp.js'),
    // one entry for each widget
    ...allWidgets.reduce(
      (result, widgetName) => ({
        ...result,
        [widgetName]: path.resolve(
          __dirname,
          `src/components/${widgetName}/index.js`
        )
      }),
      {}
    )
  },
  output: {
    library: '[name]',
    libraryTarget: 'umd',
    libraryExport: 'default', // root export is widget's "export default"
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist/umd')
  },
  module: {
    // noParse: [],
    rules: [
      // JavaScript / ES6
      {
        test: /\.jsx?$/,
        include: path.resolve('./src'),
        loader: 'babel-loader'
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[local]--[hash:base64:5]'
            }
          },
          'sass-loader'
        ],
        include: path.resolve('./src')
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg)$/,
        loader: 'url-loader',
        query: {
          limit: 8192,
          name: 'images/[name].[ext]?[hash]'
        }
      }
    ]
  }
};
<commit_msg>fix script tag build for new export format<commit_after>const path = require('path');
const { readdirSync } = require('fs');

const allWidgets = readdirSync(path.resolve(__dirname, 'src/components'));

module.exports = {
  mode: 'production',
  entry: {
    VeritoneApp: path.resolve(__dirname, 'src/shared/VeritoneApp.js'),
    // one entry for each widget
    ...allWidgets.reduce(
      (result, widgetName) => ({
        ...result,
        [widgetName]: path.resolve(
          __dirname,
          `src/components/${widgetName}/index.js`
        )
      }),
      {}
    )
  },
  output: {
    library: '[name]',
    libraryTarget: 'umd',
    // libraryExport: 'default', // root export is widget's "export default"
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist/umd')
  },
  module: {
    // noParse: [],
    rules: [
      // JavaScript / ES6
      {
        test: /\.jsx?$/,
        include: path.resolve('./src'),
        loader: 'babel-loader'
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[local]--[hash:base64:5]'
            }
          },
          'sass-loader'
        ],
        include: path.resolve('./src')
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg)$/,
        loader: 'url-loader',
        query: {
          limit: 8192,
          name: 'images/[name].[ext]?[hash]'
        }
      }
    ]
  }
};
<|endoftext|>


<commit_before>if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') {
	console.error('Class ss.i18n not defined');
} else {
	ss.i18n.addDictionary('de_DE', {
		'CMSMAIN.WARNINGSAVEPAGESBEFOREADDING' : "Sie müssen diese Seite speichern bevor Unterseiten hingefügt werden können",
		'CMSMAIN.CANTADDCHILDREN' : "Unterseiten nicht erlaubt",
		'CMSMAIN.ERRORADDINGPAGE' : 'Fehler beim Hinzufügen der Seite',
		'CMSMAIN.FILTEREDTREE' : 'Gefilterter Seitenbaum zeigt nur Änderungen',
		'CMSMAIN.ERRORFILTERPAGES' : 'Konnte Seitenbaum nicht filtern
%s',
		'CMSMAIN.ERRORUNFILTER' : 'Konnte Filterung des Seitenbaumes nicht aufheben
%s',
		'CMSMAIN.ERRORUNFILTER' : 'Filterung des Seitenbaumes zurückgesetzt',
		'CMSMAIN.PUBLISHINGPAGES' : 'Publiziere Seiten...',
		'CMSMAIN.SELECTONEPAGE' : "Bitte mindestens eine Seite auswählen",
		'CMSMAIN.ERRORPUBLISHING' : 'Fehler beim Veröffentlichen der Seiten',
		'CMSMAIN.REALLYDELETEPAGES' : "Wollen Sie wirklich %s Seiten löschen?",
		'CMSMAIN.DELETINGPAGES' : 'Lösche Seiten...',
		'CMSMAIN.ERRORDELETINGPAGES': 'Fehler beim Löschen der Seiten',
		'CMSMAIN.PUBLISHING' : 'Veröffentliche...',
		'CMSMAIN.RESTORING': 'Wiederherstellen...',
		'CMSMAIN.ERRORREVERTING': 'Fehler beim Wiederherstellen des Live-Inhaltes',
		'CMSMAIN.SAVING' : 'Sichern...',
		'ModelAdmin.SAVED': "Gespeichert",
		'ModelAdmin.REALLYDELETE': "Wirklich löschen?",
		'ModelAdmin.DELETED': "Gelöscht",
		'LeftAndMain.PAGEWASDELETED': "Diese Seite wurde gelöscht."
	});
}<commit_msg>MINOR German translations for cms javascript (#5921, thanks bartlomiej) (from r110435)<commit_after>if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') {
	console.error('Class ss.i18n not defined');
} else {
	ss.i18n.addDictionary('de_DE', {
		'CMSMAIN.WARNINGSAVEPAGESBEFOREADDING' : "Sie müssen diese Seite speichern bevor Unterseiten hingefügt werden können",
		'CMSMAIN.CANTADDCHILDREN' : "Unterseiten nicht erlaubt",
		'CMSMAIN.ERRORADDINGPAGE' : 'Fehler beim Hinzufügen der Seite',
		'CMSMAIN.FILTEREDTREE' : 'Gefilterter Seitenbaum zeigt nur Änderungen',
		'CMSMAIN.ERRORFILTERPAGES' : 'Konnte Seitenbaum nicht filtern
%s',
		'CMSMAIN.ERRORUNFILTER' : 'Konnte Filterung des Seitenbaumes nicht aufheben
%s',
		'CMSMAIN.ERRORUNFILTER' : 'Filterung des Seitenbaumes zurückgesetzt',
		'CMSMAIN.PUBLISHINGPAGES' : 'Publiziere Seiten...',
		'CMSMAIN.SELECTONEPAGE' : "Bitte mindestens eine Seite auswählen",
		'CMSMAIN.ERRORPUBLISHING' : 'Fehler beim Veröffentlichen der Seiten',
		'CMSMAIN.REALLYDELETEPAGES' : "Wollen Sie wirklich %s Seiten löschen?",
		'CMSMAIN.DELETINGPAGES' : 'Lösche Seiten...',
		'CMSMAIN.ERRORDELETINGPAGES': 'Fehler beim Löschen der Seiten',
		'CMSMAIN.PUBLISHING' : 'Veröffentliche...',
		'CMSMAIN.RESTORING': 'Wiederherstellen...',
		'CMSMAIN.ERRORREVERTING': 'Fehler beim Wiederherstellen des Live-Inhaltes',
		'CMSMAIN.SAVING' : 'Sichern...',
		'ModelAdmin.SAVED': "Gespeichert",
		'ModelAdmin.REALLYDELETE': "Wirklich löschen?",
		'ModelAdmin.DELETED': "Gelöscht",
		'ModelAdmin.VALIDATIONERROR': "Validationsfehler",
		'LeftAndMain.PAGEWASDELETED': "Diese Seite wurde gelöscht.",
		'LeftAndMain.CONFIRMUNSAVED': "Sind Sie sicher, dasß Sie die Seite verlassen möchten?\n\nWARNUNG: Ihre Änderungen werden nicht gespeichert.\n\nDrücken Sie \"OK\" um fortzufahren, oder \"Abbrechen\" um auf dieser Seite zu bleiben.",
		'WidgetAreaEditor.TOOMANY': 'Sie haben die maximale Anzahl an Widgets in diesem Bereich erreicht.'
	});
}<|endoftext|>


<commit_before>const Vue = require('vue')
const VueCompilerSfc = require('@vue/compiler-sfc')

module.exports.h = Vue.h
module.exports.createApp = Vue.createApp
module.exports.resolveComponent = Vue.resolveComponent
module.exports.isVue3 = true
module.exports.Vue2 = function () {}
module.exports.compileTemplate = template => VueCompilerSfc.compileTemplate(template).code
<commit_msg>fix cjs compileTemplate vue3<commit_after>const Vue = require('vue')
const VueCompilerSfc = require('@vue/compiler-sfc')

module.exports.h = Vue.h
module.exports.createApp = Vue.createApp
module.exports.resolveComponent = Vue.resolveComponent
module.exports.isVue3 = true
module.exports.Vue2 = function () {}
module.exports.compileTemplate = template =>
	VueCompilerSfc.compileTemplate({ source: template, filename: '<Example>.vue', id: '' }).code
<|endoftext|>


<commit_before>(function($) {
  var shareUrl = function( params ) {
    return 'https://plus.google.com/?' + jQuery.param(params);
  },

  findLinkParams = function( entry ) {
    var link = entry.find('a.entry-title-link');
    return {
      title: link.text(),
      href: link.attr('href')
    }
  },

  createShareLink = function( actions ) {
    var entry = $(actions).closest('.entry');

    if ( !actions.find('span.google-plus').length ) {
      var link = $('').html(
        $('', {
          target: '_blank',
          href: shareUrl(findLinkParams(entry))
        }).text('Share on Google+')
      );
      actions.append(link);
    }
  };

  $('body').delegate('div#entries', 'DOMNodeInserted', function(e) {
    var actions, target = $(e.target);
    if ( target.is('div.entry') ) {
      actions = target.find('div.entry-actions');
      if (actions.length > 0) {
        createShareLink( actions );
      }
    }
  });

  $('body').delegate('div.entry', 'DOMNodeInserted', function(e) {
    var target = $(e.target);
    if ( target.is('div.entry-actions') ) {
      createShareLink( target );
    }
  });

  $(document).bind('keydown', 'g', function() {
    var entry = $('div#current-entry');
    if ( entry.find('div.entry-actions').length > 0 ) {
      window.open(shareUrl(findLinkParams(entry)));
    }
  });

})(jQuery);
<commit_msg>Make the shorcut shift+g<commit_after>(function($) {
  var shareUrl = function( params ) {
    return 'https://plus.google.com/?' + jQuery.param(params);
  },

  findLinkParams = function( entry ) {
    var link = entry.find('a.entry-title-link');
    return {
      title: link.text(),
      href: link.attr('href')
    }
  },

  createShareLink = function( actions ) {
    var entry = $(actions).closest('.entry');

    if ( !actions.find('span.google-plus').length ) {
      var link = $('').html(
        $('', {
          target: '_blank',
          href: shareUrl(findLinkParams(entry))
        }).text('Share on Google+')
      );
      actions.append(link);
    }
  };

  $('body').delegate('div#entries', 'DOMNodeInserted', function(e) {
    var actions, target = $(e.target);
    if ( target.is('div.entry') ) {
      actions = target.find('div.entry-actions');
      if (actions.length > 0) {
        createShareLink( actions );
      }
    }
  });

  $('body').delegate('div.entry', 'DOMNodeInserted', function(e) {
    var target = $(e.target);
    if ( target.is('div.entry-actions') ) {
      createShareLink( target );
    }
  });

  $(document).bind('keydown', 'shift+g', function() {
    var entry = $('div#current-entry');
    if ( entry.find('div.entry-actions').length > 0 ) {
      window.open(shareUrl(findLinkParams(entry)));
    }
  });

})(jQuery);
<|endoftext|>


<commit_before>var path = require("path");
var pck = require("../package.json");
var webpack = require("webpack");
var util = require("util");

var fs = require("fs");
var license = fs.readFileSync(path.resolve(__dirname, "../LICENSE"), "utf8");
license = license.replace(/\n\n/g, "

");

var config = {
	entry : "./src/js/index.js",
	module : {
		loaders : [
			{
				test : /\.jsx?$/,
				include : [
					path.resolve(__dirname, "../src/js"),
					path.resolve(__dirname, "../node_modules/hammerjs")
				],
				loader : "babel"
			},
			{ test : /\.scss$/, loader : "style-loader!css-loader!postcss-loader!sass-loader" }
		],
		preLoaders : [
			{ test : /\.jsx$/, loader : "source-map-loader" }
		]
	},
	postcss : [ require("autoprefixer")({ browsers: ["> 5%"] }) ],
	plugins : [
		new webpack.DefinePlugin({
			__VERSION__ : JSON.stringify(pck.version),
			__LICENSE__ : JSON.stringify(license)
		})
	],
	watch : process.env.WATCH ? true : false
};

module.exports = config;
<commit_msg>adjusted autoprefixer browser version settings<commit_after>var path = require("path");
var pck = require("../package.json");
var webpack = require("webpack");
var util = require("util");

var fs = require("fs");
var license = fs.readFileSync(path.resolve(__dirname, "../LICENSE"), "utf8");
license = license.replace(/\n\n/g, "

");

var config = {
	entry : "./src/js/index.js",
	module : {
		loaders : [
			{
				test : /\.jsx?$/,
				include : [
					path.resolve(__dirname, "../src/js"),
					path.resolve(__dirname, "../node_modules/hammerjs")
				],
				loader : "babel"
			},
			{ test : /\.scss$/, loader : "style-loader!css-loader!postcss-loader!sass-loader" }
		],
		preLoaders : [
			{ test : /\.jsx$/, loader : "source-map-loader" }
		]
	},
	postcss : [
		require("autoprefixer")({ browsers: ["last 5 versions"] })
	],
	plugins : [
		new webpack.DefinePlugin({
			__VERSION__ : JSON.stringify(pck.version),
			__LICENSE__ : JSON.stringify(license)
		})
	],
	watch : process.env.WATCH ? true : false
};

module.exports = config;
<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var rarity = require('rarity');
var Anyfetch = require('anyfetch');

var util = require('../util.js');
var Token = require('../models/token.js');
var Childs = require('../Childs.js');

// This worker is used to manage a list of queues, it contain one task per user calling /update
module.exports = function usersQueueGenerator(server, config, workersFile, updateFile) {
  var log = require('../index.js').log;

  return function usersQueue(job, finalCb) {
    if(server.childs[job.data.anyfetchToken]) {
      return finalCb();
    }

    async.waterfall([
      function retrieveToken(cb) {
        Token.findOne({anyfetchToken: job.data.anyfetchToken}).exec(rarity.slice(2, cb));
      },
      function createQueue(token, cb) {
        if(!token) {
          // Token was probably revoked
          finalCb();
          return cb(null);
        }

        var isFirst = !token.cursor;
        var dateStartOfTasks = new Date();

        log.info({
          user: token.accountName,
        }, "Starting tasks");

        var jsonToken = token.toJSON();
        jsonToken.anyfetchApiUrl = job.data.anyfetchApiUrl;

        var data = {
          updateFile: updateFile,
          workersFile: workersFile,
          config: config,
          token: jsonToken
        };

        var queue = server.yaqsClient.createQueue(token.accountName);

        // Start the childs, and add listeners
        var childs = new Childs(config.concurrency || 1, __dirname + '/../child-process.js', data);

        childs.on('stop', function(forced) {
          log.info({
            user: token.accountName
          }, "End of tasks");

          childs.removeAllListeners();

          if(forced) {
            return finalCb();
          }

          delete server.childs[token.anyfetchToken];
          queue.remove(function(err) {
            if(err) {
              return finalCb(err);
            }

            var anyfetchClient = new Anyfetch(job.data.anyfetchToken);
            anyfetchClient.setApiUrl(job.data.anyfetchApiUrl);

            anyfetchClient.trackProviderUpdate({
              is_first: isFirst,
              time_spent_on_queue: dateStartOfTasks - token.lastUpdate,
              time_spentc_on_tasks: new Date() - dateStartOfTasks,
              total_time_spent: new Date() - token.lastUpdate
            }, util.logError);

            // Unlock the token
            token.isUpdating = false;
            token.save(finalCb);
          });
        });

        childs.on('message', function(data) {
          if(data.type === 'event') {
            if(data.event === 'failed') {
              util.logError(data.err, data.job);
            }

            data.job.queue = queue;
            server.usersQueue.emit('job.' + data.job.data.type + '.' + data.event, data.job, data.err);
          }
        });

        childs.start();

        childs.queue = queue;
        childs.anyfetchApiUrl = token.anyfetchApiUrl;

        server.childs[token.anyfetchToken] = childs;

        cb();
      }
    ], util.logError);
  };
};
<commit_msg>Update users-queue.js<commit_after>'use strict';

var async = require('async');
var rarity = require('rarity');
var Anyfetch = require('anyfetch');

var util = require('../util.js');
var Token = require('../models/token.js');
var Childs = require('../Childs.js');

// This worker is used to manage a list of queues, it contain one task per user calling /update
module.exports = function usersQueueGenerator(server, config, workersFile, updateFile) {
  var log = require('../index.js').log;

  return function usersQueue(job, finalCb) {
    if(server.childs[job.data.anyfetchToken]) {
      return finalCb();
    }

    async.waterfall([
      function retrieveToken(cb) {
        Token.findOne({anyfetchToken: job.data.anyfetchToken}).exec(rarity.slice(2, cb));
      },
      function createQueue(token, cb) {
        if(!token) {
          // Token was probably revoked
          finalCb();
          return cb(null);
        }

        var isFirst = !token.cursor;
        var dateStartOfTasks = new Date();

        log.info({
          user: token.accountName,
        }, "Starting tasks");

        var jsonToken = token.toJSON();
        jsonToken.anyfetchApiUrl = job.data.anyfetchApiUrl;

        var data = {
          updateFile: updateFile,
          workersFile: workersFile,
          config: config,
          token: jsonToken
        };

        var queue = server.yaqsClient.createQueue(token.accountName);

        // Start the childs, and add listeners
        var childs = new Childs(config.concurrency || 1, __dirname + '/../child-process.js', data);

        childs.on('stop', function(forced) {
          log.info({
            user: token.accountName
          }, "End of tasks");

          childs.removeAllListeners();

          if(forced) {
            return finalCb();
          }

          delete server.childs[token.anyfetchToken];
          queue.remove(function(err) {
            if(err) {
              return finalCb(err);
            }

            var anyfetchClient = new Anyfetch(job.data.anyfetchToken);
            anyfetchClient.setApiUrl(job.data.anyfetchApiUrl);

            anyfetchClient.trackProviderUpdate({
              is_first: isFirst,
              time_spent_on_queue: dateStartOfTasks - token.lastUpdate,
              time_spent_on_tasks: new Date() - dateStartOfTasks,
              total_time_spent: new Date() - token.lastUpdate
            }, util.logError);

            // Unlock the token
            token.isUpdating = false;
            token.save(finalCb);
          });
        });

        childs.on('message', function(data) {
          if(data.type === 'event') {
            if(data.event === 'failed') {
              util.logError(data.err, data.job);
            }

            data.job.queue = queue;
            server.usersQueue.emit('job.' + data.job.data.type + '.' + data.event, data.job, data.err);
          }
        });

        childs.start();

        childs.queue = queue;
        childs.anyfetchApiUrl = token.anyfetchApiUrl;

        server.childs[token.anyfetchToken] = childs;

        cb();
      }
    ], util.logError);
  };
};
<|endoftext|>


<commit_before>"use strict";

var Player = function(world, Bullet, audio) {
	this.world = world;
	this.audio = audio;
	this.idleLeftAnimation = new SpriteAnimation("connor/connorL", 2, 1, 32);
	this.idleRightAnimation = new SpriteAnimation("connor/connorR", 2, 1, 32);
	this.walkLeftAnimation = new SpriteAnimation("connor/connorL", 2, 3, 32);
	this.walkRightAnimation = new SpriteAnimation("connor/connorR", 2, 3, 32);
	this.shootLeftAnimation = new SpriteAnimation("connor/connorL", 1, 5, 32);
	this.shootRightAnimation = new SpriteAnimation("connor/connorR", 1, 5, 32);
	this.jumpLeftAnimation = new SpriteAnimation("connor/connorL", 1, 6, 32);
	this.jumpRightAnimation = new SpriteAnimation("connor/connorR", 1, 6, 32);
	this.width = 20;
	this.height = 38;
	this.x = this.world.width / 2;
	this.y = this.world.height - this.height;
	this.speed = 3;
	this.velX = 0;
	this.velY = 0;
	this.jumping = false;
	this.direction = "right";
	this.type = "player";
	this.Bullet = Bullet;
	this.shootLock = false;
	this.friction = 0.8;
	this.gravity = 0.3;
	this.state = this.idleRightAnimation;
	this.shootAudio = "pewPewBizNiss";
	this.jumpAudio = "jumpFins";
	this.alive = true;

	this.kills = 24;
	this.lives = 10;

	this.myHealth = new HealthBar (world, this, {
		x: 50,
		lives: this.lives
	});
};

var keydown = [];

Player.prototype.explode = function() {
	//alert("You died");
	if (this.kills > 1 && this.kills < 24) {
		this.kills--;
	} else {
		this.lives--;
		if (this.lives == 0) {
			this.alive = false;
		}
	}
};

Player.prototype.update = function() {
	// Jump
	if (keydown[38]) {
		if (!this.jumping) {
			this.jumping = true;
			this.velY = -this.speed * 2;
			this.audio[this.jumpAudio].stop();
			this.audio[this.jumpAudio].play();
		}
	}

	// Right
	if (keydown[39]) {
		if (this.velX < this.speed) {
			this.velX++;
			this.direction = "right";
		}
	}

	// Left
	if (keydown[37]) {
		if (this.velX > -this.speed) {
			this.velX--;
			this.direction = "left";
		}
	}

	// Shoot
	if (keydown[32]) {
		if (!this.shootLock) {
			this.shoot();
			this.shootLock = true;
			var that = this
			setTimeout(function() {
				that.shootLock = false;
			}, 300);
		}
	}

	this.velX *= this.friction;
	this.velY += this.gravity;

	this.x += this.velX;
	this.y += this.velY;

	if (this.x >= this.world.width - this.width) {
		this.x = this.world.width - this.width;
	} else if (this.x <= 0) {
		this.x = 0;
	}

	if (this.y >= this.world.height - this.height) {
		this.y = this.world.height - this.height;
		this.jumping = false;
	}

	if (this.jumping) {
		if (this.direction === "right") {
			this.state = this.jumpRightAnimation;
		} else {
			this.state = this.jumpLeftAnimation;
		}
	} else if (this.shootLock) {
		if (this.direction === "right") {
			this.state = this.shootRightAnimation;
		} else {
			this.state = this.shootLeftAnimation;
		}
	} else if (keydown[37]) {
		this.state = this.walkLeftAnimation;
	} else if (keydown[39]) {
		this.state = this.walkRightAnimation;
	} else {
		if (this.direction === "right") {
			this.state = this.idleRightAnimation;
		} else {
			this.state = this.idleLeftAnimation;
		}
	}

	if (this.kills >= 24) {
		this.myHealth.update(this.lives);
	}
};

Player.prototype.draw = function() {
	var that = this;
	if (this.alive) {
		this.state.draw(this.x, this.y, function(spriteName, x, y) {
			that.width = that.world.sprites[spriteName].width;
			that.world.drawSprite(spriteName, x, y, that.width, that.height);
		});
	} else {
		this.world.ctx.globalAlpha = 0.4;
		this.world.ctx.fillStyle = "#333";
		this.world.ctx.fillRect(0, 0, 600, 300);
		this.world.ctx.fillStyle = "#FFF";
		this.world.ctx.font = "50px Ubuntu Mono";
		this.world.ctx.fillText("Game Over", 300, 150);
	}
	//this.world.drawSprite(this.currentImage, this.x, this.y, this.width, this.height);
	//this.world.drawText("Happy Anniversary", 115, 90);
	if (this.kills < 24) {
		this.world.cropSprite("coverTurtleWithACrown", this.kills, this.kills, 384 - this.kills * 2, 46 - this.kills * 2, 115 + this.kills, 55 + this.kills, 384 - this.kills * 2, 46 - this.kills * 2);
	}

	if (this.kills >= 24 && this.alive) {
		this.myHealth.draw();
	}
};

Player.prototype.midpoint = function() {
	return {
		x: (this.x + this.width / 2),
		y: (this.y + this.height / 2)
	}
};

Player.prototype.shoot = function() {
	this.world.bullets.push (
		new this.Bullet(this.world, {
			x: this.midpoint().x,
			y: this.midpoint().y - 1,
			width: 9,
			height: 3,
			direction: this.direction,
			speed: 20,
			acceleration: 0.2,
			owner: this.type,
			kill: this
			//spriteName: 'playerBullet'
		}, this.audio
	));
	this.audio[this.shootAudio].stop();
	this.audio[this.shootAudio].play();
};

Player.prototype.kill = function() {
	if (this.kills < 24) {
		this.kills++;
	} /*
	else if (this.kills == 24) {
		this.myHealth = new HealthBar (world, this, {
			x: 50,
			lives: this.lives
		});
		this.kills++;
	}
	*/
};

document.body.addEventListener("keydown", function(e) {
	keydown[e.keyCode] = true;
});

document.body.addEventListener("keyup", function(e) {
	keydown[e.keyCode] = false;
});
<commit_msg>Update Player.js<commit_after>"use strict";

var Player = function(world, Bullet, audio) {
	this.world = world;
	this.audio = audio;
	this.idleLeftAnimation = new SpriteAnimation("connor/connorL", 2, 1, 32);
	this.idleRightAnimation = new SpriteAnimation("connor/connorR", 2, 1, 32);
	this.walkLeftAnimation = new SpriteAnimation("connor/connorL", 2, 3, 32);
	this.walkRightAnimation = new SpriteAnimation("connor/connorR", 2, 3, 32);
	this.shootLeftAnimation = new SpriteAnimation("connor/connorL", 1, 5, 32);
	this.shootRightAnimation = new SpriteAnimation("connor/connorR", 1, 5, 32);
	this.jumpLeftAnimation = new SpriteAnimation("connor/connorL", 1, 6, 32);
	this.jumpRightAnimation = new SpriteAnimation("connor/connorR", 1, 6, 32);
	this.width = 20;
	this.height = 38;
	this.x = this.world.width / 2;
	this.y = this.world.height - this.height;
	this.speed = 3;
	this.velX = 0;
	this.velY = 0;
	this.jumping = false;
	this.direction = "right";
	this.type = "player";
	this.Bullet = Bullet;
	this.shootLock = false;
	this.friction = 0.8;
	this.gravity = 0.3;
	this.state = this.idleRightAnimation;
	this.shootAudio = "pewPewBizNiss";
	this.jumpAudio = "jumpFins";
	this.alive = true;

	this.kills = 0;
	this.lives = 10;

	this.myHealth = new HealthBar (world, this, {
		x: 50,
		lives: this.lives
	});
};

var keydown = [];

Player.prototype.explode = function() {
	//alert("You died");
	if (this.kills > 1 && this.kills < 24) {
		this.kills--;
	} else {
		this.lives--;
		if (this.lives == 0) {
			this.alive = false;
		}
	}
};

Player.prototype.update = function() {
	// Jump
	if (keydown[38]) {
		if (!this.jumping) {
			this.jumping = true;
			this.velY = -this.speed * 2;
			this.audio[this.jumpAudio].stop();
			this.audio[this.jumpAudio].play();
		}
	}

	// Right
	if (keydown[39]) {
		if (this.velX < this.speed) {
			this.velX++;
			this.direction = "right";
		}
	}

	// Left
	if (keydown[37]) {
		if (this.velX > -this.speed) {
			this.velX--;
			this.direction = "left";
		}
	}

	// Shoot
	if (keydown[32]) {
		if (!this.shootLock) {
			this.shoot();
			this.shootLock = true;
			var that = this
			setTimeout(function() {
				that.shootLock = false;
			}, 300);
		}
	}

	this.velX *= this.friction;
	this.velY += this.gravity;

	this.x += this.velX;
	this.y += this.velY;

	if (this.x >= this.world.width - this.width) {
		this.x = this.world.width - this.width;
	} else if (this.x <= 0) {
		this.x = 0;
	}

	if (this.y >= this.world.height - this.height) {
		this.y = this.world.height - this.height;
		this.jumping = false;
	}

	if (this.jumping) {
		if (this.direction === "right") {
			this.state = this.jumpRightAnimation;
		} else {
			this.state = this.jumpLeftAnimation;
		}
	} else if (this.shootLock) {
		if (this.direction === "right") {
			this.state = this.shootRightAnimation;
		} else {
			this.state = this.shootLeftAnimation;
		}
	} else if (keydown[37]) {
		this.state = this.walkLeftAnimation;
	} else if (keydown[39]) {
		this.state = this.walkRightAnimation;
	} else {
		if (this.direction === "right") {
			this.state = this.idleRightAnimation;
		} else {
			this.state = this.idleLeftAnimation;
		}
	}

	if (this.kills >= 24) {
		this.myHealth.update(this.lives);
	}
};

Player.prototype.draw = function() {
	var that = this;
	if (this.alive) {
		this.state.draw(this.x, this.y, function(spriteName, x, y) {
			that.width = that.world.sprites[spriteName].width;
			that.world.drawSprite(spriteName, x, y, that.width, that.height);
		});
	} else {
		this.world.ctx.globalAlpha = 0.4;
		this.world.ctx.fillStyle = "#333";
		this.world.ctx.fillRect(0, 0, 600, 300);
		this.world.ctx.fillStyle = "#FFF";
		this.world.ctx.font = "50px Ubuntu Mono";
		this.world.ctx.fillText("Game Over", 300, 150);
	}
	//this.world.drawSprite(this.currentImage, this.x, this.y, this.width, this.height);
	//this.world.drawText("Happy Anniversary", 115, 90);
	if (this.kills < 24) {
		this.world.cropSprite("coverTurtleWithACrown", this.kills, this.kills, 384 - this.kills * 2, 46 - this.kills * 2, 115 + this.kills, 55 + this.kills, 384 - this.kills * 2, 46 - this.kills * 2);
	}

	if (this.kills >= 24 && this.alive) {
		this.myHealth.draw();
	}
};

Player.prototype.midpoint = function() {
	return {
		x: (this.x + this.width / 2),
		y: (this.y + this.height / 2)
	}
};

Player.prototype.shoot = function() {
	this.world.bullets.push (
		new this.Bullet(this.world, {
			x: this.midpoint().x,
			y: this.midpoint().y - 1,
			width: 9,
			height: 3,
			direction: this.direction,
			speed: 20,
			acceleration: 0.2,
			owner: this.type,
			kill: this
			//spriteName: 'playerBullet'
		}, this.audio
	));
	this.audio[this.shootAudio].stop();
	this.audio[this.shootAudio].play();
};

Player.prototype.kill = function() {
	if (this.kills < 24) {
		this.kills++;
	} /*
	else if (this.kills == 24) {
		this.myHealth = new HealthBar (world, this, {
			x: 50,
			lives: this.lives
		});
		this.kills++;
	}
	*/
};

document.body.addEventListener("keydown", function(e) {
	keydown[e.keyCode] = true;
});

document.body.addEventListener("keyup", function(e) {
	keydown[e.keyCode] = false;
});
<|endoftext|>


<commit_before>function loadImagesList(data, collectionId) {
  var html = templates.workEditImages(data);
  $('#images').replaceWith(html);
  initialiseImagesList(data, collectionId);
}

function refreshImagesList(data, collectionId) {
  var html = templates.workEditImages(data);
  $('#image-list').replaceWith($(html).find('#image-list'));
  initialiseImagesList(data, collectionId);
}

function initialiseImagesList(data, collectionId) {

  $(data.images).each(function (index, image) {
    var basePath = data.uri;
    var noExtension = image.uri.match(/^(.+?)(\.[^.]*$|$)/);
    var imageJson = noExtension[1] + '.json';

    $("#image-edit_" + index).click(function () {
      getPageResource(collectionId, imageJson,
        onSuccess = function (imageData) {
          loadImageBuilder(data, function () {
            Florence.Editor.isDirty = false;
            //refreshPreview();
            refreshImagesList(data, collectionId);
          }, imageData);
        })
    });

    $("#image-delete_" + index).click(function () {
      var result = confirm("Are you sure you want to delete this image?");
      if (result === true) {
        $("#image_" + index).remove();
        // delete any files associated with the image.

        getPageResource(collectionId, imageJson,
          onSuccess = function (imageData) {
            _.each(imageData.files, function(file) {
              var fileUri = basePath + '/' + file.filename;
              console.log('deleting ' + fileUri);
              deleteContent(collectionId, fileUri,
                onSuccess = function () {
                },
                onError = function (error) {
                  handleApiError(error);
                });
            });
          });

        // delete the image json file
        deleteContent(collectionId, imageJson,
          onSuccess = function () {
            // remove the image from the page json when its deleted
            data.images = _(data.images).filter(function (item) {
              return item.filename !== image.filename;
            });

            // save the updated page json
            postContent(collectionId, basePath, JSON.stringify(data),
              success = function () {
                Florence.Editor.isDirty = false;
                refreshImagesList(data, collectionId);
              },
              error = function (response) {
                handleApiError(response);
              }
            );
          }
        );
      }
    });
  });
}
<commit_msg>Delete image file when deleting whole image.<commit_after>function loadImagesList(data, collectionId) {
  var html = templates.workEditImages(data);
  $('#images').replaceWith(html);
  initialiseImagesList(data, collectionId);
}

function refreshImagesList(data, collectionId) {
  var html = templates.workEditImages(data);
  $('#image-list').replaceWith($(html).find('#image-list'));
  initialiseImagesList(data, collectionId);
}

function initialiseImagesList(data, collectionId) {

  $(data.images).each(function (index, image) {
    var basePath = data.uri;
    var noExtension = image.uri.match(/^(.+?)(\.[^.]*$|$)/);
    var imageJson = noExtension[1] + '.json';

    $("#image-edit_" + index).click(function () {
      getPageResource(collectionId, imageJson,
        onSuccess = function (imageData) {
          loadImageBuilder(data, function () {
            Florence.Editor.isDirty = false;
            //refreshPreview();
            refreshImagesList(data, collectionId);
          }, imageData);
        })
    });

    $("#image-delete_" + index).click(function () {
      var result = confirm("Are you sure you want to delete this image?");
      if (result === true) {
        $("#image_" + index).remove();
        // delete any files associated with the image.

        getPageResource(collectionId, imageJson,
          onSuccess = function (imageData) {
            if(imageData.files) {
              _.each(imageData.files, function (file) {
                var fileUri = basePath + '/' + file.filename;
                console.log('deleting ' + fileUri);
                deleteContent(collectionId, fileUri,
                  onSuccess = function () {
                  },
                  onError = function (error) {
                    handleApiError(error);
                  });
              });
            } else {
              console.log('deleting ' + image.uri);
              deleteContent(collectionId, image.uri,
                onSuccess = function () {
                },
                onError = function (error) {
                  handleApiError(error);
                });
            }
          });

        // delete the image json file
        deleteContent(collectionId, imageJson,
          onSuccess = function () {
            // remove the image from the page json when its deleted
            data.images = _(data.images).filter(function (item) {
              return item.filename !== image.filename;
            });

            // save the updated page json
            postContent(collectionId, basePath, JSON.stringify(data),
              success = function () {
                Florence.Editor.isDirty = false;
                refreshImagesList(data, collectionId);
              },
              error = function (response) {
                handleApiError(response);
              }
            );
          }
        );
      }
    });
  });
}
<|endoftext|>