<commit_before>'use strict';

/* eslint-env node, browser */

(function () {

    /**
     * @constructor RangeSelectionModel
     *
     * @desc This object models selection of "cells" within an abstract single-dimensional matrix.
     *
     * Disjoint selections can be built with calls to the following methods:
     * * {@link RangeSelectionModel#select|select(start, stop)} - Add a range to the matrix.
     * * {@link RangeSelectionModel#deselect|deselect(start, stop)} - Remove a range from the matrix.
     *
     * Two more methods are available:
     * * Test a cell to see if it {@link RangeSelectionModel#isSelected|isSelected(cell)}
     * * {@link RangeSelectionModel#clear|clear()} the matrix
     *
     * Internally, the selection is run-length-encoded. It is therefore a "sparse" matrix
     * with undefined bounds. A single data property called `selection` is an array that
     * contains all the "runs" (ranges) of selected cells albeit in no particular order.
     * This property should not normally need to be accessed directly.
     *
     * Note: This object should be instantiated with the `new` keyword.
     *
     * @returns {RangeSelectionModel} Self (i.e., `this` object).
     */
    function RangeSelectionModel() {
        /**
         * @name selection
         * @type {Array.Array.number}
         * @summary Unordered list of runs.
         * @desc A "run" is defined as an Array(2) where:
         * * element [0] is the beginning of the run
         * * element [1] is the end of the run (inclusive) and is always >= element [0]
         * The order of the runs within is undefined.
         * @memberOf RangeSelectionModel.prototype
         * @abstract
         */
        this.selection = [];
    }

    RangeSelectionModel.prototype = {

        /**
         * @summary Return the indexes that are selected.
         * @desc Return the indexes that are selected.
         * @returns {Array of Integers}.
         * @memberOf RangeSelectionModel.prototype
         */
        getSelections: function (){
            var result = [];
            this.selection.forEach(function (each) {
                for (var i = each[0]; i <= each[1]; i++) {
                    result.push(i);
                }
            });
            result.sort(function (a, b){
                return a - b;
            });
            return result;
        },

        /**
         * @summary Add a contiguous run of points to the selection.
         * @desc Insert a new run into `this.selection`.
         * The new run will be merged with overlapping and adjacent runs.
         *
         * The two parameters may be given in either order.
         * The start and stop elements in the resulting run will however always be ordered.
         * (However, note that the order of the runs within `this.selection` is itself always unordered.)
         *
         * Note that `this.selection` is updated in place, preserving validity of any external references.
         * @param {number} start - Start of run. May be greater than `stop`.
         * @param {number} [stop=stop] - End of run (inclusive). May be less than `start`.
         * @returns {RangeSelectionModel} Self (i.e., `this`), for chaining.
         * @memberOf RangeSelectionModel.prototype
         */
        select: function (start, stop) {
            var run = makeRun(start, stop);
            var splicer = [0, 1];
            this.selection.forEach(function (each) {
                if (overlaps(each, run) || abuts(each, run)) {
                    run = merge(each, run);
                } else {
                    splicer.push(each);
                }
            });
            splicer.push(run);
            splicer[1] = this.selection.length;
            this.selection.splice.apply(this.selection, splicer); // update in place to preserve external references
            return this;
        },

        /**
         * @summary Remove a contiguous run of points from the selection.
         * @desc Truncate and/or remove run(s) from `this.selection`.
         * Removing part of existing runs will (correctly) shorten them or break them into two fragments.
         *
         * The two parameters may be given in either order.
         *
         * Note that `this.selection` is updated in place, preserving validity of any external references.
         * @param {number} start - Start of run. May be greater than `stop`.
         * @param {number} [stop=stop] - End of run (inclusive). May be less than `start`.
         * @returns {RangeSelectionModel} Self (i.e., `this`), for chaining.
         * @memberOf RangeSelectionModel.prototype
         */
        deselect: function (start, stop) {
            var run = makeRun(start, stop);
            var splicer = [0, 0];
            this.selection.forEach(function (each) {
                if (overlaps(each, run)) {
                    var pieces = subtract(each, run);
                    splicer = splicer.concat(pieces);
                } else {
                    splicer.push(each);
                }
            });
            splicer[1] = this.selection.length;
            this.selection.splice.apply(this.selection, splicer); // update in place to preserve external references
            return this;
        },

        /**
         * @summary Determines if the given `cell` is selected.
         * @returns {boolean} `true` iff given `cell` is within any of the runs in `this.selection`.
         * @param {number} cell - The cell to test for inclusion in the selection.
         * @memberOf RangeSelectionModel.prototype
         */
        isSelected: function (cell) {
            return this.selection.some(function (each) {
                return each[0] <= cell && cell <= each[1];
            });
        },

        /**
         * @summary Empties `this.selection`, effectively removing all runs.
         * @returns {RangeSelectionModel} Self (i.e., `this`), for chaining.
         * @memberOf RangeSelectionModel.prototype
         */
        clear: function () {
            this.selection.length = 0;
            return this;
        }

    };

    /**
     * @private
     * @summary Preps `start` and `stop` params into order array
     * @function makeRun
     * @desc Utility function called by both `select()` and `deselect()`.
     * @param {number|number[]} start - Start of run. if array, `start` and `stop` are taken from first two elements.
     * @param {number} [stop=start] - End of run (inclusive).
     */
    function makeRun(start, stop) {
        return (
            start instanceof Array
                ? makeRun.apply(this, start) // extract params from given array
                : stop === undefined
                ? [ start, start ] // single param is a run that stops where it starts
                : start <= stop
                ? [ start, stop ]
                : [ stop, start ] // reverse descending params into ascending order
        );
    }

    /**
     * @private
     * @function overlaps
     * @returns {boolean} `true` iff `run1` overlaps `run2`
     * @summary Comparison operator that determines if given runs overlap with one another.
     * @desc Both parameters are assumed to be _ordered_ arrays.
     *
     * Overlap is defined to include the case where one run completely contains the other.
     *
     * Note: This operator is commutative.
     * @param {number[]} run1 - first run
     * @param {number[]} run2 - second run
     */
    function overlaps(run1, run2) {
        return (
            run1[0] <= run2[0] && run2[0] <= run1[1] || // run2's start is within run1 OR...
            run1[0] <= run2[1] && run2[1] <= run1[1] || // run2's stop is within run1 OR...
            run2[0] <  run1[0] && run1[1] <  run2[1]    // run2 completely contains run1
        );
    }

    /**
     * @private
     * @function abuts
     * @summary Comparison operator that determines if given runs are consecutive with one another.
     * @returns {boolean} `true` iff `run1` is consecutive with `run2`
     * @desc Both parameters are assumed to be _ordered_ arrays.
     *
     * Note: This operator is commutative.
     * @param {number[]} run1 - first run
     * @param {number[]} run2 - second run
     */
    function abuts(run1, run2) {
        return (
            run1[1] === run2[0] - 1 || // run1's top immediately precedes run2's start OR...
            run2[1] === run1[0] - 1    // run2's top immediately precedes run1's start
        );
    }

    /**
     * @private
     * @function subtract
     * @summary Operator that subtracts one run from another.
     * @returns {Array.Array.number} The remaining pieces of `minuend` after removing `subtrahend`.
     * @desc Both parameters are assumed to be _ordered_ arrays.
     *
     * This function _does not assumes_ that `overlap()` has already been called with the same runs and has returned `true`.
     *
     * Returned array contains 0, 1, or 2 runs which are the portion(s) of `minuend` that do _not_ include `subtrahend`.
     *
     * Caveat: This operator is *not* commutative.
     * @param {number[]} minuend - a run from which to "subtract" `subtrahend`
     * @param {number[]} subtrahend - a run to "subtracted" from `minuend`
     */
    function subtract(minuend, subtrahend) {
        var m0 = minuend[0];
        var m1 = minuend[1];
        var s0 = subtrahend[0];
        var s1 = subtrahend[1];
        var result = [];

        if (s0 <= m0 && s1 < m1) {
            //subtrahend extends before minuend: return remaining piece of `minuend`
            result.push([s1 + 1, m1]);
        } else if (s0 > m0 && s1 >= m1) {
            //subtrahend extends after minuend: return remaining piece of `minuend`
            result.push([m0, s0 - 1]);
        } else if (m0 < s0 && s1 < m1) {
            //completely inside: return 2 smaller pieces resulting from the hole
            result.push([m0, s0 - 1]);
            result.push([s1 + 1, m1]);
        } else if (s1 < m0 || s0 > m1) {
            // completely outside: return `minuend` untouched
            result.push(minuend);
        }

        //else subtrahend must completely overlap minuend so return no pieces

        return result;
    }

    // Local utility functions

    /**
     * @private
     * @function merge
     * @summary Operator that merges given runs.
     * @returns {number[]} A single merged run.
     * @desc Both parameters are assumed to be _ordered_ arrays.
     *
     * The runs are assumed to be overlapping or adjacent to one another.
     *
     * Note: This operator is commutative.
     * @param {number[]} run1 - a run to merge with `run2`
     * @param {number[]} run2 - a run to merge with `run1`
     */
    function merge(run1, run2) {
        var min = Math.min(Math.min.apply(Math, run1), Math.min.apply(Math, run2));
        var max = Math.max(Math.max.apply(Math, run1), Math.max.apply(Math, run2));
        return [min, max];
    }

    // External interface

    if (typeof module === 'object') {
        module.exports = RangeSelectionModel; // Node.js support
    } else {
        (window.fin = window.fin || {}).RangeSelectionModel = RangeSelectionModel; // window.fin support
    }

    // Do not remove enclosing IIFE which supplies local scope for window.fin support!

})();
<commit_msg>added isEmpty function<commit_after>'use strict';

/* eslint-env node, browser */

(function () {

    /**
     * @constructor RangeSelectionModel
     *
     * @desc This object models selection of "cells" within an abstract single-dimensional matrix.
     *
     * Disjoint selections can be built with calls to the following methods:
     * * {@link RangeSelectionModel#select|select(start, stop)} - Add a range to the matrix.
     * * {@link RangeSelectionModel#deselect|deselect(start, stop)} - Remove a range from the matrix.
     *
     * Two more methods are available:
     * * Test a cell to see if it {@link RangeSelectionModel#isSelected|isSelected(cell)}
     * * {@link RangeSelectionModel#clear|clear()} the matrix
     *
     * Internally, the selection is run-length-encoded. It is therefore a "sparse" matrix
     * with undefined bounds. A single data property called `selection` is an array that
     * contains all the "runs" (ranges) of selected cells albeit in no particular order.
     * This property should not normally need to be accessed directly.
     *
     * Note: This object should be instantiated with the `new` keyword.
     *
     * @returns {RangeSelectionModel} Self (i.e., `this` object).
     */
    function RangeSelectionModel() {
        /**
         * @name selection
         * @type {Array.Array.number}
         * @summary Unordered list of runs.
         * @desc A "run" is defined as an Array(2) where:
         * * element [0] is the beginning of the run
         * * element [1] is the end of the run (inclusive) and is always >= element [0]
         * The order of the runs within is undefined.
         * @memberOf RangeSelectionModel.prototype
         * @abstract
         */
        this.selection = [];
    }

    RangeSelectionModel.prototype = {

        isEmpty: function (){
            return this.selection.length === 0;
        },

        /**
         * @summary Return the indexes that are selected.
         * @desc Return the indexes that are selected.
         * @returns {Array of Integers}.
         * @memberOf RangeSelectionModel.prototype
         */
        getSelections: function (){
            var result = [];
            this.selection.forEach(function (each) {
                for (var i = each[0]; i <= each[1]; i++) {
                    result.push(i);
                }
            });
            result.sort(function (a, b){
                return a - b;
            });
            return result;
        },

        /**
         * @summary Add a contiguous run of points to the selection.
         * @desc Insert a new run into `this.selection`.
         * The new run will be merged with overlapping and adjacent runs.
         *
         * The two parameters may be given in either order.
         * The start and stop elements in the resulting run will however always be ordered.
         * (However, note that the order of the runs within `this.selection` is itself always unordered.)
         *
         * Note that `this.selection` is updated in place, preserving validity of any external references.
         * @param {number} start - Start of run. May be greater than `stop`.
         * @param {number} [stop=stop] - End of run (inclusive). May be less than `start`.
         * @returns {RangeSelectionModel} Self (i.e., `this`), for chaining.
         * @memberOf RangeSelectionModel.prototype
         */
        select: function (start, stop) {
            var run = makeRun(start, stop);
            var splicer = [0, 1];
            this.selection.forEach(function (each) {
                if (overlaps(each, run) || abuts(each, run)) {
                    run = merge(each, run);
                } else {
                    splicer.push(each);
                }
            });
            splicer.push(run);
            splicer[1] = this.selection.length;
            this.selection.splice.apply(this.selection, splicer); // update in place to preserve external references
            return this;
        },

        /**
         * @summary Remove a contiguous run of points from the selection.
         * @desc Truncate and/or remove run(s) from `this.selection`.
         * Removing part of existing runs will (correctly) shorten them or break them into two fragments.
         *
         * The two parameters may be given in either order.
         *
         * Note that `this.selection` is updated in place, preserving validity of any external references.
         * @param {number} start - Start of run. May be greater than `stop`.
         * @param {number} [stop=stop] - End of run (inclusive). May be less than `start`.
         * @returns {RangeSelectionModel} Self (i.e., `this`), for chaining.
         * @memberOf RangeSelectionModel.prototype
         */
        deselect: function (start, stop) {
            var run = makeRun(start, stop);
            var splicer = [0, 0];
            this.selection.forEach(function (each) {
                if (overlaps(each, run)) {
                    var pieces = subtract(each, run);
                    splicer = splicer.concat(pieces);
                } else {
                    splicer.push(each);
                }
            });
            splicer[1] = this.selection.length;
            this.selection.splice.apply(this.selection, splicer); // update in place to preserve external references
            return this;
        },

        /**
         * @summary Determines if the given `cell` is selected.
         * @returns {boolean} `true` iff given `cell` is within any of the runs in `this.selection`.
         * @param {number} cell - The cell to test for inclusion in the selection.
         * @memberOf RangeSelectionModel.prototype
         */
        isSelected: function (cell) {
            return this.selection.some(function (each) {
                return each[0] <= cell && cell <= each[1];
            });
        },

        /**
         * @summary Empties `this.selection`, effectively removing all runs.
         * @returns {RangeSelectionModel} Self (i.e., `this`), for chaining.
         * @memberOf RangeSelectionModel.prototype
         */
        clear: function () {
            this.selection.length = 0;
            return this;
        }

    };

    /**
     * @private
     * @summary Preps `start` and `stop` params into order array
     * @function makeRun
     * @desc Utility function called by both `select()` and `deselect()`.
     * @param {number|number[]} start - Start of run. if array, `start` and `stop` are taken from first two elements.
     * @param {number} [stop=start] - End of run (inclusive).
     */
    function makeRun(start, stop) {
        return (
            start instanceof Array
                ? makeRun.apply(this, start) // extract params from given array
                : stop === undefined
                ? [ start, start ] // single param is a run that stops where it starts
                : start <= stop
                ? [ start, stop ]
                : [ stop, start ] // reverse descending params into ascending order
        );
    }

    /**
     * @private
     * @function overlaps
     * @returns {boolean} `true` iff `run1` overlaps `run2`
     * @summary Comparison operator that determines if given runs overlap with one another.
     * @desc Both parameters are assumed to be _ordered_ arrays.
     *
     * Overlap is defined to include the case where one run completely contains the other.
     *
     * Note: This operator is commutative.
     * @param {number[]} run1 - first run
     * @param {number[]} run2 - second run
     */
    function overlaps(run1, run2) {
        return (
            run1[0] <= run2[0] && run2[0] <= run1[1] || // run2's start is within run1 OR...
            run1[0] <= run2[1] && run2[1] <= run1[1] || // run2's stop is within run1 OR...
            run2[0] <  run1[0] && run1[1] <  run2[1]    // run2 completely contains run1
        );
    }

    /**
     * @private
     * @function abuts
     * @summary Comparison operator that determines if given runs are consecutive with one another.
     * @returns {boolean} `true` iff `run1` is consecutive with `run2`
     * @desc Both parameters are assumed to be _ordered_ arrays.
     *
     * Note: This operator is commutative.
     * @param {number[]} run1 - first run
     * @param {number[]} run2 - second run
     */
    function abuts(run1, run2) {
        return (
            run1[1] === run2[0] - 1 || // run1's top immediately precedes run2's start OR...
            run2[1] === run1[0] - 1    // run2's top immediately precedes run1's start
        );
    }

    /**
     * @private
     * @function subtract
     * @summary Operator that subtracts one run from another.
     * @returns {Array.Array.number} The remaining pieces of `minuend` after removing `subtrahend`.
     * @desc Both parameters are assumed to be _ordered_ arrays.
     *
     * This function _does not assumes_ that `overlap()` has already been called with the same runs and has returned `true`.
     *
     * Returned array contains 0, 1, or 2 runs which are the portion(s) of `minuend` that do _not_ include `subtrahend`.
     *
     * Caveat: This operator is *not* commutative.
     * @param {number[]} minuend - a run from which to "subtract" `subtrahend`
     * @param {number[]} subtrahend - a run to "subtracted" from `minuend`
     */
    function subtract(minuend, subtrahend) {
        var m0 = minuend[0];
        var m1 = minuend[1];
        var s0 = subtrahend[0];
        var s1 = subtrahend[1];
        var result = [];

        if (s0 <= m0 && s1 < m1) {
            //subtrahend extends before minuend: return remaining piece of `minuend`
            result.push([s1 + 1, m1]);
        } else if (s0 > m0 && s1 >= m1) {
            //subtrahend extends after minuend: return remaining piece of `minuend`
            result.push([m0, s0 - 1]);
        } else if (m0 < s0 && s1 < m1) {
            //completely inside: return 2 smaller pieces resulting from the hole
            result.push([m0, s0 - 1]);
            result.push([s1 + 1, m1]);
        } else if (s1 < m0 || s0 > m1) {
            // completely outside: return `minuend` untouched
            result.push(minuend);
        }

        //else subtrahend must completely overlap minuend so return no pieces

        return result;
    }

    // Local utility functions

    /**
     * @private
     * @function merge
     * @summary Operator that merges given runs.
     * @returns {number[]} A single merged run.
     * @desc Both parameters are assumed to be _ordered_ arrays.
     *
     * The runs are assumed to be overlapping or adjacent to one another.
     *
     * Note: This operator is commutative.
     * @param {number[]} run1 - a run to merge with `run2`
     * @param {number[]} run2 - a run to merge with `run1`
     */
    function merge(run1, run2) {
        var min = Math.min(Math.min.apply(Math, run1), Math.min.apply(Math, run2));
        var max = Math.max(Math.max.apply(Math, run1), Math.max.apply(Math, run2));
        return [min, max];
    }

    // External interface

    if (typeof module === 'object') {
        module.exports = RangeSelectionModel; // Node.js support
    } else {
        (window.fin = window.fin || {}).RangeSelectionModel = RangeSelectionModel; // window.fin support
    }

    // Do not remove enclosing IIFE which supplies local scope for window.fin support!

})();
<|endoftext|>


<commit_before>var qajaxWrapper = require("../helpers/qajaxWrapper");

var config = require("../config/config");
var AppDispatcher = require("../AppDispatcher");
var AppsEvents = require("../events/AppsEvents");

var AppsActions = {
  requestApps: function () {
    this.request({
      url: `${config.apiURL}v2/apps`
    })
      .success(function (apps) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.REQUEST_APPS,
          data: apps
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.REQUEST_APPS_ERROR,
          data: error
        });
      });
  },
  requestApp: function (appId) {
    this.request({
      url: `${config.apiURL}v2/apps/${appId}?embed=app.taskStats`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.REQUEST_APP,
          data: app
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.REQUEST_APP_ERROR,
          data: error
        });
      });
  },
  createApp: function (newAppAttributes) {
    this.request({
      method: "POST",
      data: newAppAttributes,
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.CREATE_APP,
          data: app
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.CREATE_APP_ERROR,
          data: error
        });
      });
  },
  deleteApp: function (appId) {
    this.request({
      method: "DELETE",
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps/${appId}`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.DELETE_APP,
          data: app,
          appId: appId
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.DELETE_APP_ERROR,
          data: error
        });
      });
  },
  restartApp: function (appId) {
    this.request({
      method: "POST",
      data: {
        force: false
      },
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps/${appId}/restart`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.RESTART_APP,
          data: app,
          appId: appId
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.RESTART_APP_ERROR,
          data: error
        });
      });
  },
  scaleApp: function (appId, instances) {
    this.request({
      method: "PUT",
      data: {
        instances: instances
      },
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps/${appId}`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.SCALE_APP,
          data: app,
          appId: appId
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.SCALE_APP_ERROR,
          data: error
        });
      });
  },
  applySettingsOnApp: function (appId, settings, isEditing = false) {
    // Version key is not allowed and not needed on settings object
    delete settings.version;

    this.request({
      method: "PUT",
      data: settings,
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps/${appId}`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.APPLY_APP,
          data: app,
          appId: appId,
          isEditing: isEditing
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.APPLY_APP_ERROR,
          data: error,
          isEditing: isEditing
        });
      });
  },
  request: qajaxWrapper
};

module.exports = AppsActions;
<commit_msg>Don't modify app config directly in action<commit_after>var qajaxWrapper = require("../helpers/qajaxWrapper");

var config = require("../config/config");
var AppDispatcher = require("../AppDispatcher");
var AppsEvents = require("../events/AppsEvents");

var AppsActions = {
  requestApps: function () {
    this.request({
      url: `${config.apiURL}v2/apps`
    })
      .success(function (apps) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.REQUEST_APPS,
          data: apps
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.REQUEST_APPS_ERROR,
          data: error
        });
      });
  },
  requestApp: function (appId) {
    this.request({
      url: `${config.apiURL}v2/apps/${appId}?embed=app.taskStats`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.REQUEST_APP,
          data: app
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.REQUEST_APP_ERROR,
          data: error
        });
      });
  },
  createApp: function (newAppAttributes) {
    this.request({
      method: "POST",
      data: newAppAttributes,
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.CREATE_APP,
          data: app
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.CREATE_APP_ERROR,
          data: error
        });
      });
  },
  deleteApp: function (appId) {
    this.request({
      method: "DELETE",
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps/${appId}`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.DELETE_APP,
          data: app,
          appId: appId
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.DELETE_APP_ERROR,
          data: error
        });
      });
  },
  restartApp: function (appId) {
    this.request({
      method: "POST",
      data: {
        force: false
      },
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps/${appId}/restart`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.RESTART_APP,
          data: app,
          appId: appId
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.RESTART_APP_ERROR,
          data: error
        });
      });
  },
  scaleApp: function (appId, instances) {
    this.request({
      method: "PUT",
      data: {
        instances: instances
      },
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps/${appId}`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.SCALE_APP,
          data: app,
          appId: appId
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.SCALE_APP_ERROR,
          data: error
        });
      });
  },
  applySettingsOnApp: function (appId, settings, isEditing = false) {
    // Version key is not allowed and not needed on settings object
    var clonedSettings = Object.assign({}, settings);
    delete clonedSettings.version;

    this.request({
      method: "PUT",
      data: clonedSettings,
      headers: {
        "Content-Type": "application/json"
      },
      url: `${config.apiURL}v2/apps/${appId}`
    })
      .success(function (app) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.APPLY_APP,
          data: app,
          appId: appId,
          isEditing: isEditing
        });
      })
      .error(function (error) {
        AppDispatcher.dispatch({
          actionType: AppsEvents.APPLY_APP_ERROR,
          data: error,
          isEditing: isEditing
        });
      });
  },
  request: qajaxWrapper
};

module.exports = AppsActions;
<|endoftext|>


<commit_before>AnnotationsEventsController.AREA_MEASURING_TOOL = 'area_measuring_tool';

AnnotationsEventsController.prototype.initializeAreaMeasuringTool = function(path_config) {
    //by default, initialize dummy tool
    this.initializeDummyTool();

    if (!(AnnotationsEventsController.AREA_MEASURING_TOOL in this.initialized_tools)) {

        this.annotation_controller.area_ruler = undefined;
        this.annotation_controller.area_ruler_id = 'tmp_area_ruler';
        this.annotation_controller.area_ruler_config =
            (typeof path_config === 'undefined') ? {} : path_config;

        this.annotation_controller.area_ruler_out_id = undefined;
        this.annotation_controller.area_ruler_binding_shape_id = undefined;

        this.annotation_controller.updateAreaRulerConfig = function(ruler_config) {
            this.area_ruler_config = ruler_config;
        };

        this.annotation_controller.extendAreaRulerConfig = function(ruler_config) {
            this.area_ruler_config = $.extend({}, this.area_ruler_config, ruler_config);
        };

        this.annotation_controller.createAreaRulerPath = function (x, y) {
            this.drawPolygon(this.area_ruler_id, [], undefined, this.area_ruler_config, false);
            this.selectShape(this.area_ruler_id);
            this.area_ruler = this.getShape(this.area_ruler_id);
            this.area_ruler.addPoint(x, y);
            $("#" + this.area_ruler_out_id).trigger('area_ruler_created', [{'x': x, 'y': y}]);
            this.refreshView();
        };

        this.annotation_controller.addPointToAreaRuler = function (x, y) {
            this.area_ruler.addPoint(x, y);
            this.refreshView();
        };

        this.annotation_controller.clearAreaRuler = function (ruler_saved) {
            if (typeof this.area_ruler !== 'undefined') {
                this.deleteShape(this.area_ruler_id);
                this.area_ruler_id = undefined;
            }
            $("#" + this.area_ruler_out_id).trigger('area_ruler_cleared', [ruler_saved]);
        };

        this.annotation_controller.adaptRulerToShape = function () {
            var binding_shape = this.getShape(this.area_ruler_binding_shape_id);
            if (
                this.area_ruler.intersectsShape(binding_shape) === true ||
                this.area_ruler.containsShape(binding_shape) ||
                binding_shape.containsShape(this.area_ruler)
            ) {
                this.intersectShapes(this.area_ruler, binding_shape, true, false, true, true);
                this.area_ruler = this.getShape(this.area_ruler_id);
            } else {
                this.deleteShape(this.area_ruler_id);
                this.area_ruler = undefined;
                $("#" + this.area_ruler_out_id).trigger('area_ruler_empty_intersection');
            }
        };

        this.annotation_controller.getAreaRulerMeasure = function (decimal_digits) {
            if (typeof this.area_ruler !== 'undefined') {
                return this.area_ruler.getArea(this.image_mpp, decimal_digits);
            }
        };

        this.annotation_controller.serializeAreaRuler = function () {
            this.area_ruler.simplifyPath();
            // check if ruler needs to be adapted to a given shape
            if (typeof this.area_ruler_binding_shape_id !== 'undefined') {
                this.adaptRulerToShape();
            }
            // check if there is still an intersection
            if (typeof this.area_ruler !== 'undefined') {
                // serialize ruler in output field's data
                var $ruler_out = $("#" + this.area_ruler_out_id);
                var ruler_json = this.getShapeJSON(this.area_ruler_id);
                ruler_json.shape_id = this.getFirstAvailableLabel('area_ruler');
                $ruler_out.data('ruler_json', ruler_json);
            }
        };

        this.annotation_controller.updateAreaRulerOutputField = function () {
            var measure = this.getAreaRulerMeasure();
            var $ruler_out = $("#" + this.area_ruler_out_id);
            $ruler_out.data('measure', measure)
                .trigger('area_ruler_updated');
        };

        var aec = this;
        this.annotation_controller.bindToAreaRuler = function (switch_on_id, output_id) {
            if (typeof output_id === 'undefined') {
                throw new Error('Missing mandatory output element');
            }
            aec._bind_switch(switch_on_id, AnnotationsEventsController.AREA_MEASURING_TOOL);
            $("#" + switch_on_id).bind(
                'click',
                {'annotation_controller': this},
                function(event) {
                    event.data.annotation_controller.area_ruler_out_id = output_id;
                    $("#" + output_id).trigger('start_new_area_ruler');
                }
            );
        };

        this.annotation_controller.bindAreaRulerToShape = function(shape_id) {
            this.area_ruler_binding_shape_id = shape_id;
        };

        var area_ruler_tool = new paper.Tool();

        area_ruler_tool.annotations_controller = this.annotation_controller;

        area_ruler_tool.onMouseDown = function (event) {
            this.annotations_controller.createAreaRulerPath(event.point.x, event.point.y);
        };

        area_ruler_tool.onMouseDrag = function (event) {
            this.annotations_controller.addPointToAreaRuler(event.point.x, event.point.y);
        };

        area_ruler_tool.onMouseUp = function () {
            this.annotations_controller.serializeAreaRuler();
            this.annotations_controller.updateAreaRulerOutputField();
            this.annotations_controller.clearAreaRuler();
        };

        this.initialized_tools[AnnotationsEventsController.AREA_MEASURING_TOOL] = area_ruler_tool;

    } else {
        console.warn('Tool "' + AnnotationsEventsController.AREA_MEASURING_TOOL + '" already initialized');
    }
};<commit_msg>area measuring tool can be paused and resume like what can be done with freehand drawing tool<commit_after>AnnotationsEventsController.AREA_MEASURING_TOOL = 'area_measuring_tool';

AnnotationsEventsController.prototype.initializeAreaMeasuringTool = function(path_config) {
    //by default, initialize dummy tool
    this.initializeDummyTool();

    if (!(AnnotationsEventsController.AREA_MEASURING_TOOL in this.initialized_tools)) {

        this.annotation_controller.area_ruler = undefined;
        this.annotation_controller.area_ruler_id = 'tmp_area_ruler';
        this.annotation_controller.area_ruler_config =
            (typeof path_config === 'undefined') ? {} : path_config;
        this.annotation_controller.tmp_area_ruler_history = undefined;

        this.annotation_controller.area_ruler_out_id = undefined;
        this.annotation_controller.area_ruler_binding_shape_id = undefined;

        this.annotation_controller.updateAreaRulerConfig = function (ruler_config) {
            this.area_ruler_config = ruler_config;
        };

        this.annotation_controller.extendAreaRulerConfig = function (ruler_config) {
            this.area_ruler_config = $.extend({}, this.area_ruler_config, ruler_config);
        };

        this.annotation_controller.tmpAreaRulerExists = function () {
            return typeof this.area_ruler !== 'undefined';
        };

        this.annotation_controller.replaceLastAreaRulerPoint = function (event) {
            this.area_ruler.removePoint();
            this.addPointToAreaRuler(event.point.x, event.point.y);
        };

        this.annotation_controller.activateAreaRulerPreviewMode = function () {
            this.area_ruler_preview_mode_on = true;
        };

        this.annotation_controller.deactivateAreaRulerPreviewMode = function () {
            this.area_ruler_preview_mode_on = false;
            this.area_ruler.closePath();
            this.area_ruler.disableDashedBorder();
        };

        this.annotation_controller.areaRulerPreviewModeActive = function () {
            return this.area_ruler_preview_mode_on;
        };

        this.annotation_controller._setAreaRulerCheckpoint = function () {
            var shape_json = this.getShapeJSON(this.area_ruler_id);
            shape_json.segments.pop();
            this.tmp_area_ruler_history.push(JSON.stringify(shape_json));
        };

        this.annotation_controller.areaRulerHistoryExists = function () {
            return (typeof this.tmp_area_ruler_history !== 'undefined') && (this.tmp_area_ruler_history.length > 0);
        };

        this.annotation_controller.rollbackAreaRulerPath = function () {
            this.deleteShape(this.area_ruler_id, false);
            var stop_rollback = false;
            if (this.areaRulerHistoryExists()) {
                var prev_shape_json = JSON.parse(this.tmp_area_ruler_history.pop());
                this.drawShapeFromJSON(prev_shape_json, false);
                this.area_ruler = this.getShape(this.area_ruler_id);
                this.selectShape(this.area_ruler_id);
            } else {
                this.clearAreaRuler();
                stop_rollback = true;
            }
            this.refreshView();
            return stop_rollback;
        };

        this.annotation_controller._initAreaRuler = function (x, y, trigger_label) {
            this.selectShape(this.area_ruler_id);
            this.area_ruler = this.getShape(this.area_ruler_id);
            this.area_ruler.addPoint(x, y);
            $("#" +this.canvas_id).trigger(trigger_label, [{'x': x, 'y': y}]);
            this.refreshView();
        };

        this.annotation_controller.createAreaRulerPath = function (x, y) {
            this.tmp_area_ruler_history = [];
            this.drawPolygon(this.area_ruler_id, [], undefined, this.area_ruler_config, false);
            this._initAreaRuler(x, y, 'area_ruler_created');
        };

        this.annotation_controller.continueAreaRulerPath = function (x, y) {
            this._initAreaRuler(x, y, 'area_ruler_updated');
        };

        this.annotation_controller.addPointToAreaRuler = function (x, y) {
            this.area_ruler.addPoint(x, y);
            this.refreshView();
        };

        this.annotation_controller.pauseAreaRuler = function () {
            $("#" + this.area_ruler_out_id).trigger('area_ruler_paused', this.area_ruler_id);
        };

        this.annotation_controller.saveAreaRuler = function () {
            this.serializeAreaRuler();
            this.updateAreaRulerOutputField();
            this.clearAreaRuler(true);
        };

        this.annotation_controller.clearAreaRuler = function (ruler_saved) {
            if (typeof this.area_ruler !== 'undefined') {
                this.deleteShape(this.area_ruler_id);
                this.area_ruler_id = undefined;
                this.tmp_area_ruler_history = undefined;
                this.area_ruler = undefined;
            }
            $("#" + this.area_ruler_out_id).trigger('area_ruler_cleared', [ruler_saved]);
        };

        this.annotation_controller.adaptRulerToShape = function () {
            var binding_shape = this.getShape(this.area_ruler_binding_shape_id);
            if (
                this.area_ruler.intersectsShape(binding_shape) === true ||
                this.area_ruler.containsShape(binding_shape) ||
                binding_shape.containsShape(this.area_ruler)
            ) {
                this.intersectShapes(this.area_ruler, binding_shape, true, false, true, true);
                this.area_ruler = this.getShape(this.area_ruler_id);
            } else {
                this.deleteShape(this.area_ruler_id);
                this.area_ruler = undefined;
                $("#" + this.area_ruler_out_id).trigger('area_ruler_empty_intersection');
            }
        };

        this.annotation_controller.getAreaRulerMeasure = function (decimal_digits) {
            if (typeof this.area_ruler !== 'undefined') {
                return this.area_ruler.getArea(this.image_mpp, decimal_digits);
            }
        };

        this.annotation_controller.serializeAreaRuler = function () {
            this.area_ruler.simplifyPath();
            // check if ruler needs to be adapted to a given shape
            if (typeof this.area_ruler_binding_shape_id !== 'undefined') {
                this.adaptRulerToShape();
            }
            // check if there is still an intersection
            if (typeof this.area_ruler !== 'undefined') {
                // serialize ruler in output field's data
                var $ruler_out = $("#" + this.area_ruler_out_id);
                var ruler_json = this.getShapeJSON(this.area_ruler_id);
                ruler_json.shape_id = this.getFirstAvailableLabel('area_ruler');
                $ruler_out.data('ruler_json', ruler_json);
            }
        };

        this.annotation_controller.updateAreaRulerOutputField = function () {
            var measure = this.getAreaRulerMeasure();
            var $ruler_out = $("#" + this.area_ruler_out_id);
            $ruler_out.data('measure', measure)
                .trigger('area_ruler_updated');
        };

        var aec = this;
        this.annotation_controller.bindToAreaRuler = function (switch_on_id, output_id) {
            if (typeof output_id === 'undefined') {
                throw new Error('Missing mandatory output element');
            }
            aec._bind_switch(switch_on_id, AnnotationsEventsController.AREA_MEASURING_TOOL);
            $("#" + switch_on_id).bind(
                'click',
                {'annotation_controller': this},
                function(event) {
                    event.data.annotation_controller.area_ruler_out_id = output_id;
                    $("#" + output_id).trigger('start_new_area_ruler');
                }
            );
        };

        this.annotation_controller.bindAreaRulerToShape = function(shape_id) {
            this.area_ruler_binding_shape_id = shape_id;
        };

        var area_ruler_tool = new paper.Tool();

        area_ruler_tool.annotations_controller = this.annotation_controller;

        area_ruler_tool.onMouseDown = function (event) {
            if (this.annotations_controller.tmpAreaRulerExists()) {
                this.annotations_controller._setAreaRulerCheckpoint();
                this.annotations_controller.deactivateAreaRulerPreviewMode();
                this.annotations_controller.continueAreaRulerPath(event.point.x, event.point.y);
            } else {
                this.annotations_controller.createAreaRulerPath(event.point.x, event.point.y);
            }
        };

        area_ruler_tool.onMouseDrag = function (event) {
            this.annotations_controller.addPointToAreaRuler(event.point.x, event.point.y);
        };

        area_ruler_tool.onMouseUp = function () {
            this.annotations_controller.pauseAreaRuler();
        };

        area_ruler_tool.onMouseMove = function (event) {
            if (this.annotations_controller.areaRulerPreviewModeActive() &&
                $("#" + this.annotations_controller.canvas_id).is(':hover')) {
                this.annotations_controller.replaceLastAreaRulerPoint(event);
            }
        };

        var canvasMouseEnter = function (event) {
            var annotation_controller = event.data.annotation_controller;
            if (annotation_controller.areaRulerPreviewModeActive()) {
                annotation_controller.area_ruler.openPath();
                annotation_controller.area_ruler.deselect();
                annotation_controller.area_ruler.enableDashedBorder(100, 50);
            }
        };

        var canvasMouseLeave = function (event) {
            var annotation_controller = event.data.annotation_controller;
            if (annotation_controller.areaRulerPreviewModeActive()) {
                annotation_controller.area_ruler.removePoint();
                annotation_controller.area_ruler.closePath();
                annotation_controller.area_ruler.select();
                annotation_controller.area_ruler.disableDashedBorder();
            }
        };

        $("#" + this.annotation_controller.canvas_id)
            .mouseenter(
                { annotation_controller: this.annotation_controller },
                canvasMouseEnter
            )
            .mouseleave(
                { annotation_controller: this.annotation_controller },
                canvasMouseLeave
            );

        this.initialized_tools[AnnotationsEventsController.AREA_MEASURING_TOOL] = area_ruler_tool;

    } else {
        console.warn('Tool "' + AnnotationsEventsController.AREA_MEASURING_TOOL + '" already initialized');
    }
};<|endoftext|>


<commit_before>//function generateData() {

var constituencies = ["Belfast East", "Belfast North", "Belfast South", "Belfast West", "East Antrim", "East Londonderry", "Fermanagh and South Tyrone", "Foyle", "Lagan Valley", "Mid Ulster", "Newry and Armagh", "North Antrim", "North Down", "South Antrim", "South Down", "Strangford", "Upper Bann", "West Tyrone"];

var parties = [{
    name: "Alliance Party",
    short: "APNI",
    colour: "#ffe600"
}, {
    name: "Democratic Unionist Party",
    short: "DUP",
    colour: "#ff8000"
}, {
    name: "Independent",
    short: "IND",
    colour: "#669999"
}, {
    name: "Sinn Fein",
    short: "SF",
    colour: "#009900"
}, {
    name: "Social Democratic and Labour Party",
    short: "SDLP",
    colour: "#cc3300"
}, {
    name: "Traditional Unionist Voice",
    short: "TUV",
    colour: "#0000e6"
}, {
    name: "UK Independence Party",
    short: "UKIP",
    colour: "#cc00cc"
}, {
    name: "Ulster Unionist Party",
    short: "UUP",
    colour: "#62cae7"
}, {
    name: "People Before Profit Alliance",
    short: "PBP",
    colour: "#ff3399"
}, {
    name: "Workers Party",
    short: "WP",
    colour: "#ff0000"
}, {
    name: "Procapitalism",
    short: "CAP",
    colour: "#f633ff"
}, {
    name: "Socialist Party(NI)",
    short: "SP",
    colour: "#e60000"
}, {
    name: "British Nationalist Party",
    short: "BNP",
    colour: "#b7bdff"
}, {
    name: "Progressive Unionist Party",
    short: "PUP",
    colour: "#1e0082"
}]

var data = [];

$.each(constituencies, function(i, constituency) {
    var numElected = Math.floor(Math.random() * 7) + 2
    for (i = 1; i < numElected; i++) {
        var party = parties[Math.floor(Math.random() * parties.length)];
        data.push({
            constituency: constituency,
            candidate: "Joe Bloggs",
            party_name: party.name,
            party_short: party.short,
            party_colour: party.colour,
            count: i
        });
    };
});

$.get("website/json/spec.json", function(specData) {
    console.log("json received", specData);
    var spec = JSON5.parse(specData);
    console.log(spec);
    spec.data = [{"name": "results","values": data}];
    vg.parse.spec(spec, function(chart) {
        var view = chart({
                el: "#overview_matrix"
            })
            .on("mouseover", function(event, item) {
                if (item && item.datum.candidate) {
                    console.log(item);
                    $('#tooltip').show();
                    $('#tooltip').html(
                        "" + item.datum.candidate + "
" +
                        item.datum.party_name
                    );
                } else {
                    $('#tooltip').hide();
                }
            })
            .update();
    });
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function(jqXHR, textStatus) {
    console.log( "error:" + textStatus );
  });

//}<commit_msg>debugging<commit_after>//function generateData() {

var constituencies = ["Belfast East", "Belfast North", "Belfast South", "Belfast West", "East Antrim", "East Londonderry", "Fermanagh and South Tyrone", "Foyle", "Lagan Valley", "Mid Ulster", "Newry and Armagh", "North Antrim", "North Down", "South Antrim", "South Down", "Strangford", "Upper Bann", "West Tyrone"];

var parties = [{
    name: "Alliance Party",
    short: "APNI",
    colour: "#ffe600"
}, {
    name: "Democratic Unionist Party",
    short: "DUP",
    colour: "#ff8000"
}, {
    name: "Independent",
    short: "IND",
    colour: "#669999"
}, {
    name: "Sinn Fein",
    short: "SF",
    colour: "#009900"
}, {
    name: "Social Democratic and Labour Party",
    short: "SDLP",
    colour: "#cc3300"
}, {
    name: "Traditional Unionist Voice",
    short: "TUV",
    colour: "#0000e6"
}, {
    name: "UK Independence Party",
    short: "UKIP",
    colour: "#cc00cc"
}, {
    name: "Ulster Unionist Party",
    short: "UUP",
    colour: "#62cae7"
}, {
    name: "People Before Profit Alliance",
    short: "PBP",
    colour: "#ff3399"
}, {
    name: "Workers Party",
    short: "WP",
    colour: "#ff0000"
}, {
    name: "Procapitalism",
    short: "CAP",
    colour: "#f633ff"
}, {
    name: "Socialist Party(NI)",
    short: "SP",
    colour: "#e60000"
}, {
    name: "British Nationalist Party",
    short: "BNP",
    colour: "#b7bdff"
}, {
    name: "Progressive Unionist Party",
    short: "PUP",
    colour: "#1e0082"
}]

var data = [];

$.each(constituencies, function(i, constituency) {
    var numElected = Math.floor(Math.random() * 7) + 2
    for (i = 1; i < numElected; i++) {
        var party = parties[Math.floor(Math.random() * parties.length)];
        data.push({
            constituency: constituency,
            candidate: "Joe Bloggs",
            party_name: party.name,
            party_short: party.short,
            party_colour: party.colour,
            count: i
        });
    };
});

$.get("website/json/spec.json", function(specData) {
    console.log("json received", specData);
    var spec = JSON5.parse(specData);
    console.log(spec);
    spec.data = [{"name": "results","values": data}];
    vg.parse.spec(spec, function(chart) {
        var view = chart({
                el: "#overview_matrix"
            })
            .on("mouseover", function(event, item) {
                if (item && item.datum.candidate) {
                    console.log(item);
                    $('#tooltip').show();
                    $('#tooltip').html(
                        "" + item.datum.candidate + "
" +
                        item.datum.party_name
                    );
                } else {
                    $('#tooltip').hide();
                }
            })
            .update();
    });
},"text")
  .done(function() {
    console.log( "second success" );
  })
  .fail(function(jqXHR, textStatus) {
    console.log( "error:" + textStatus );
  });

//}<|endoftext|>


<commit_before>import { util, mixin, container } from 'uikit';

var {$, extend, isWithin, Observer, on, off, pointerDown, pointerMove, pointerUp} = util;

var win = $(window), doc = $(document.documentElement);

UIkit.component('sortable', {

    mixins: [mixin.class],

    props: {
        group: String,
        animation: Number,
        threshold: Number,
        clsItem: String,
        clsPlaceholder: String,
        clsDrag: String,
        clsDragState: String,
        clsBase: String,
        clsNoDrag: String,
        clsEmpty: String,
        clsCustom: String,
        handle: String
    },

    defaults: {
        group: false,
        animation: 150,
        threshold: 5,
        clsItem: 'uk-sortable-item',
        clsPlaceholder: 'uk-sortable-placeholder',
        clsDrag: 'uk-sortable-drag',
        clsDragState: 'uk-drag',
        clsBase: 'uk-sortable',
        clsNoDrag: 'uk-sortable-nodrag',
        clsEmpty: 'uk-sortable-empty',
        clsCustom: '',
        handle: false
    },

    ready() {

        ['init', 'start', 'move', 'end'].forEach(key => {
            let fn = this[key];
            this[key] = e => {
                e = e.originalEvent || e;
                this.scrollY = win.scrollTop();
                var {pageX, pageY} = e.touches && e.touches[0] || e;
                this.pos = {x: pageX, y: pageY};

                fn(e);
            }
        });

        on(this.$el, pointerDown, this.init);

        if (this.clsEmpty) {
            var empty = () => this.$el.toggleClass(this.clsEmpty, !this.$el.children().length);
            (new Observer(empty)).observe(this.$el[0], {childList: true});
            empty();
        }

    },

    methods: {

        init(e) {

            var target = $(e.target), placeholder = this.$el.children().has(e.target);

            if (!placeholder.length
                || target.is(':input')
                || this.handle && !isWithin(target, this.handle)
                || e.button && e.button !== 0
                || isWithin(target, `.${this.clsNoDrag}`)
            ) {
                return;
            }

            e.preventDefault();
            e.stopPropagation();

            this.touched = [this];
            this.placeholder = placeholder;
            this.origin = extend({target, index: this.placeholder.index()}, this.pos);

            doc.on(pointerMove, this.move);
            doc.on(pointerUp, this.end);
            win.on('scroll', this.scroll);

            if (!this.threshold) {
                this.start(e);
            }

        },

        start(e) {

            this.drag = $(this.placeholder[0].outerHTML.replace(/^<li/i, '<div').replace(/li>$/i, 'div>'))
                .attr('uk-no-boot', '')
                .addClass(`${this.clsDrag} ${this.clsCustom}`)
                .css({
                    boxSizing: 'border-box',
                    width: this.placeholder.outerWidth(),
                    height: this.placeholder.outerHeight(),
                    paddingLeft: this.placeholder.css('paddingLeft'),
                    paddingRight: this.placeholder.css('paddingRight'),
                    paddingTop: this.placeholder.css('paddingTop'),
                    paddingBottom: this.placeholder.css('paddingBottom')
                })
                .appendTo(container);

            this.drag.children().first().height(this.placeholder.children().height());

            var {left, top} = this.placeholder.offset();
            extend(this.origin, {left: left - this.pos.x, top: top - this.pos.y});

            this.placeholder.addClass(this.clsPlaceholder);
            this.$el.children().addClass(this.clsItem);
            doc.addClass(this.clsDragState);

            this.$el.trigger('start', [this, this.placeholder, this.drag]);

            this.move(e);
        },

        move(e) {

            if (!this.drag) {

                if (Math.abs(this.pos.x - this.origin.x) > this.threshold || Math.abs(this.pos.y - this.origin.y) > this.threshold) {
                    this.start(e);
                }

                return;
            }

            this.update();

            var target = e.type === 'mousemove' ? e.target : document.elementFromPoint(this.pos.x - document.body.scrollLeft, this.pos.y - document.body.scrollTop),
                sortable = getSortable(target),
                previous = getSortable(this.placeholder[0]),
                move = sortable !== previous;

            if (!sortable || isWithin(target, this.placeholder) || move && (!sortable.group || sortable.group !== previous.group)) {
                return;
            }

            target = sortable.$el.is(target.parentNode) && $(target) || sortable.$el.children().has(target);

            if (move) {
                previous.remove(this.placeholder);
            } else if (!target.length) {
                return;
            }

            sortable.insert(this.placeholder, target);

            if (this.touched.indexOf(sortable) === -1) {
                this.touched.push(sortable);
            }

        },

        scroll() {
            var scroll = win.scrollTop();
            if (scroll !== this.scrollY) {
                this.pos.y += scroll - this.scrollY;
                this.scrollY = scroll;
                this.update();
            }
        },

        end({type}) {

            doc.off(pointerMove, this.move);
            doc.off(pointerUp, this.end);
            win.off('scroll', this.scroll);

            if (isWithin(this.origin.target, 'a[href]')) {
                if (this.pos.x !== this.origin.x || this.pos.y !== this.origin.y) {

                    var timer = setTimeout(() => doc.trigger('click'), 0),
                        listener = e => {

                            e.preventDefault();
                            e.stopPropagation();

                            clearTimeout(timer);
                            off(doc, 'click', listener, true);
                        };

                        on(doc, 'click', listener, true);

                } else if (type !== 'mouseup') {
                    location.href = this.origin.target.closest('a[href]').attr('href');
                }
            }

            if (!this.drag) {
                return;
            }

            var sortable = getSortable(this.placeholder[0]);

            if (this === sortable) {
                if (this.origin.index !== this.placeholder.index()) {
                    this.$el.trigger('change', [this, this.placeholder, 'moved']);
                }
            } else {
                sortable.$el.trigger('change', [sortable, this.placeholder, 'added']);
                this.$el.trigger('change', [this, this.placeholder, 'removed']);
            }

            this.$el.trigger('stop', [this]);

            this.drag.remove();
            this.drag = null;

            this.touched.forEach(sortable => sortable.$el.children().removeClass(`${sortable.clsPlaceholder} ${sortable.clsItem}`));

            doc.removeClass(this.clsDragState);

        },

        update() {

            this.drag.offset({top: this.pos.y + this.origin.top, left: this.pos.x + this.origin.left});

            var top = this.drag.offset().top, bottom = top + this.drag.outerHeight();

            if (top > 0 && top < this.scrollY) {
                setTimeout(() => win.scrollTop(this.scrollY - 5), 5);
            } else if (bottom < doc[0].offsetHeight && bottom > window.innerHeight + this.scrollY) {
                setTimeout(() => win.scrollTop(this.scrollY + 5), 5);
            }
        },

        insert(element, target) {

            this.$el.children().addClass(this.clsItem);

            var insert = () => {

                if (target.length) {

                    if (!this.$el.has(element).length || element.prevAll().filter(target).length) {
                        element.insertBefore(target);
                    } else {
                        element.insertAfter(target);
                    }

                } else {
                    this.$el.append(element);
                }

                this.$updateParents();
            };

            if (this.animation) {
                this.animate(insert);
            } else {
                insert();
            }

        },

        remove(element) {

            if (!this.$el.has(element).length) {
                return;
            }

            var remove = () => {
                element.remove();
                this.$updateParents();
            };

            if (this.animation) {
                this.animate(remove);
            } else {
                remove();
            }

        },

        animate(action) {

            var props = [],
                children = this.$el.children().toArray().map(el => {
                    el = $(el);
                    props.push(extend({
                        position: 'absolute',
                        pointerEvents: 'none',
                        width: el.outerWidth(),
                        height: el.outerHeight()
                    }, el.position()));
                    return el;
                }),
                reset = {position: '', width: '', height: '', pointerEvents: '', top: '', left: ''};

            action();

            children.forEach(el => el.stop());
            this.$el.children().css(reset);
            this.$updateParents();
            this.$el.css('min-height', this.$el.height());

            var positions = children.map(el => el.position());
            $.when.apply($, children.map((el, i) => el.css(props[i]).animate(positions[i], this.animation).promise()))
                .then(() => {
                    this.$el.css('min-height', '').children().css(reset);
                    this.$updateParents();
                });

        }

    }

});

function getSortable(element) {
    return UIkit.getComponent(element, 'sortable') || element.parentNode && getSortable(element.parentNode);
}
<commit_msg>updated sortable<commit_after>import { util, mixin, container } from 'uikit';

var {$, extend, isWithin, Observer, on, off, pointerDown, pointerMove, pointerUp, requestAnimationFrame} = util;

var win = $(window), doc = $(document.documentElement);

UIkit.component('sortable', {

    mixins: [mixin.class],

    props: {
        group: String,
        animation: Number,
        threshold: Number,
        clsItem: String,
        clsPlaceholder: String,
        clsDrag: String,
        clsDragState: String,
        clsBase: String,
        clsNoDrag: String,
        clsEmpty: String,
        clsCustom: String,
        handle: String
    },

    defaults: {
        group: false,
        animation: 150,
        threshold: 5,
        clsItem: 'uk-sortable-item',
        clsPlaceholder: 'uk-sortable-placeholder',
        clsDrag: 'uk-sortable-drag',
        clsDragState: 'uk-drag',
        clsBase: 'uk-sortable',
        clsNoDrag: 'uk-sortable-nodrag',
        clsEmpty: 'uk-sortable-empty',
        clsCustom: '',
        handle: false
    },

    ready() {

        ['init', 'start', 'move', 'end'].forEach(key => {
            let fn = this[key];
            this[key] = e => {
                e = e.originalEvent || e;
                this.scrollY = window.scrollY;
                var {pageX, pageY} = e.touches && e.touches[0] || e;
                this.pos = {x: pageX, y: pageY};

                fn(e);
            }
        });

        on(this.$el, pointerDown, this.init);

        if (this.clsEmpty) {
            var empty = () => this.$el.toggleClass(this.clsEmpty, !this.$el.children().length);
            (new Observer(empty)).observe(this.$el[0], {childList: true});
            empty();
        }

    },

    methods: {

        init(e) {

            var target = $(e.target), placeholder = this.$el.children().has(e.target);

            if (!placeholder.length
                || target.is(':input')
                || this.handle && !isWithin(target, this.handle)
                || e.button && e.button !== 0
                || isWithin(target, `.${this.clsNoDrag}`)
            ) {
                return;
            }

            e.preventDefault();
            e.stopPropagation();

            this.touched = [this];
            this.placeholder = placeholder;
            this.origin = extend({target, index: this.placeholder.index()}, this.pos);

            doc.on(pointerMove, this.move);
            doc.on(pointerUp, this.end);
            win.on('scroll', this.scroll);

            if (!this.threshold) {
                this.start(e);
            }

        },

        start(e) {

            this.drag = $(this.placeholder[0].outerHTML.replace(/^<li/i, '<div').replace(/li>$/i, 'div>'))
                .attr('uk-no-boot', '')
                .addClass(`${this.clsDrag} ${this.clsCustom}`)
                .css({
                    boxSizing: 'border-box',
                    width: this.placeholder.outerWidth(),
                    height: this.placeholder.outerHeight(),
                    paddingLeft: this.placeholder.css('paddingLeft'),
                    paddingRight: this.placeholder.css('paddingRight'),
                    paddingTop: this.placeholder.css('paddingTop'),
                    paddingBottom: this.placeholder.css('paddingBottom')
                })
                .appendTo(container);

            this.drag.children().first().height(this.placeholder.children().height());

            var {left, top} = this.placeholder.offset();
            extend(this.origin, {left: left - this.pos.x, top: top - this.pos.y});

            this.placeholder.addClass(this.clsPlaceholder);
            this.$el.children().addClass(this.clsItem);
            doc.addClass(this.clsDragState);

            this.$el.trigger('start', [this, this.placeholder, this.drag]);

            this.move(e);
        },

        move(e) {

            if (!this.drag) {

                if (Math.abs(this.pos.x - this.origin.x) > this.threshold || Math.abs(this.pos.y - this.origin.y) > this.threshold) {
                    this.start(e);
                }

                return;
            }

            this.update();

            var target = e.type === 'mousemove' ? e.target : document.elementFromPoint(this.pos.x - document.body.scrollLeft, this.pos.y - document.body.scrollTop),
                sortable = getSortable(target),
                previous = getSortable(this.placeholder[0]),
                move = sortable !== previous;

            if (!sortable || isWithin(target, this.placeholder) || move && (!sortable.group || sortable.group !== previous.group)) {
                return;
            }

            target = sortable.$el.is(target.parentNode) && $(target) || sortable.$el.children().has(target);

            if (move) {
                previous.remove(this.placeholder);
            } else if (!target.length) {
                return;
            }

            sortable.insert(this.placeholder, target);

            if (this.touched.indexOf(sortable) === -1) {
                this.touched.push(sortable);
            }

        },

        scroll() {
            var scroll = window.scrollY;
            if (scroll !== this.scrollY) {
                this.pos.y += scroll - this.scrollY;
                this.scrollY = scroll;
                this.update();
            }
        },

        end({type}) {

            doc.off(pointerMove, this.move);
            doc.off(pointerUp, this.end);
            win.off('scroll', this.scroll);

            if (isWithin(this.origin.target, 'a[href]')) {
                if (this.pos.x !== this.origin.x || this.pos.y !== this.origin.y) {

                    var timer = setTimeout(() => doc.trigger('click'), 0),
                        listener = e => {

                            e.preventDefault();
                            e.stopPropagation();

                            clearTimeout(timer);
                            off(doc, 'click', listener, true);
                        };

                        on(doc, 'click', listener, true);

                } else if (type !== 'mouseup') {
                    location.href = this.origin.target.closest('a[href]').attr('href');
                }
            }

            if (!this.drag) {
                return;
            }

            var sortable = getSortable(this.placeholder[0]);

            if (this === sortable) {
                if (this.origin.index !== this.placeholder.index()) {
                    this.$el.trigger('change', [this, this.placeholder, 'moved']);
                }
            } else {
                sortable.$el.trigger('change', [sortable, this.placeholder, 'added']);
                this.$el.trigger('change', [this, this.placeholder, 'removed']);
            }

            this.$el.trigger('stop', [this]);

            this.drag.remove();
            this.drag = null;

            this.touched.forEach(sortable => sortable.$el.children().removeClass(`${sortable.clsPlaceholder} ${sortable.clsItem}`));

            doc.removeClass(this.clsDragState);

        },

        update() {

            if (!this.updating) {
                requestAnimationFrame(() => {

                    this.drag.offset({top: this.pos.y + this.origin.top, left: this.pos.x + this.origin.left});

                    var top = this.drag.offset().top, bottom = top + this.drag[0].offsetHeight;

                    if (top > 0 && top < this.scrollY) {
                        setTimeout(() => win.scrollTop(this.scrollY - 5), 5);
                    } else if (bottom < doc[0].offsetHeight && bottom > window.innerHeight + this.scrollY) {
                        setTimeout(() => win.scrollTop(this.scrollY + 5), 5);
                    }

                    this.updating = false;

                })
            }

            this.updating = true;

        },

        insert(element, target) {

            this.$el.children().addClass(this.clsItem);

            var insert = () => {

                if (target.length) {

                    if (!this.$el.has(element).length || element.prevAll().filter(target).length) {
                        element.insertBefore(target);
                    } else {
                        element.insertAfter(target);
                    }

                } else {
                    this.$el.append(element);
                }

                this.$updateParents();
            };

            if (this.animation) {
                this.animate(insert);
            } else {
                insert();
            }

        },

        remove(element) {

            if (!this.$el.has(element).length) {
                return;
            }

            var remove = () => {
                element.remove();
                this.$updateParents();
            };

            if (this.animation) {
                this.animate(remove);
            } else {
                remove();
            }

        },

        animate(action) {

            var props = [],
                children = this.$el.children().toArray().map(el => {
                    el = $(el);
                    props.push(extend({
                        position: 'absolute',
                        pointerEvents: 'none',
                        width: el.outerWidth(),
                        height: el.outerHeight()
                    }, el.position()));
                    return el;
                }),
                reset = {position: '', width: '', height: '', pointerEvents: '', top: '', left: ''};

            action();

            children.forEach(el => el.stop());
            this.$el.children().css(reset);
            this.$updateParents();
            this.$el.css('min-height', this.$el.height());

            var positions = children.map(el => el.position());
            $.when.apply($, children.map((el, i) => el.css(props[i]).animate(positions[i], this.animation).promise()))
                .then(() => {
                    this.$el.css('min-height', '').children().css(reset);
                    this.$updateParents();
                });

        }

    }

});

function getSortable(element) {
    return UIkit.getComponent(element, 'sortable') || element.parentNode && getSortable(element.parentNode);
}
<|endoftext|>


<commit_before>/* global BigScreen */

import Component from '@ember/component';
import { action } from '@ember/object';

export default Component.extend({
  tagName: '',

  toggle: action(function () {
    let element = this.fullscreenElement;
    BigScreen.toggle(document.querySelector(element));
  }),
});
<commit_msg>FullscreenButton: Convert to Glimmer component<commit_after>/* global BigScreen */

import { action } from '@ember/object';

import Component from '@glimmer/component';

export default class FullscreenButton extends Component {
  @action toggle() {
    let element = this.args.fullscreenElement;
    BigScreen.toggle(document.querySelector(element));
  }
}
<|endoftext|>


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

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2018 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/grafeas',
    theme: 'lumen'
  },
  markdown: {
    idInHeadings: true
  }
};
<commit_msg>chore: update jsdoc.js (#110)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/grafeas',
    theme: 'lumen',
    default: {
      "outputSourceFiles": false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<|endoftext|>


<commit_before>import Component from '@ember/component';
import { action } from '@ember/object';

import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Icon from 'ol/style/Icon';
import Style from 'ol/style/Style';

const START_ICON = new Icon({
  anchor: [0.5, 1],
  src: '/images/marker-green.png',
});

const END_ICON = new Icon({
  anchor: [0.5, 1],
  src: '/images/marker.png',
});

START_ICON.load();
END_ICON.load();

const START_STYLE = new Style({ image: START_ICON });
const END_STYLE = new Style({ image: END_ICON });

export default Component.extend({
  tagName: '',

  map: null,
  coordinates: null,

  init() {
    this._super(...arguments);

    this.layer = new VectorLayer({
      source: new VectorSource({
        useSpatialIndex: false,
      }),
      style(feature) {
        return feature.get('type') === 'end' ? END_STYLE : START_STYLE;
      },
      zIndex: 100,
    });

    this.map.addLayer(this.layer);

    this.updateSource();
  },

  willDestroy() {
    this._super(...arguments);
    this.map.removeLayer(this.layer);
  },

  @action
  updateSource() {
    let source = this.layer.getSource();

    source.clear();

    if (this.coordinates) {
      let startPoint = new Point(this.coordinates[0]);
      let endPoint = new Point(this.coordinates[this.coordinates.length - 1]);

      let startFeature = new Feature({ geometry: startPoint, type: 'start' });
      let endFeature = new Feature({ geometry: endPoint, type: 'end' });

      source.addFeature(startFeature);
      source.addFeature(endFeature);
    }
  },
});
<commit_msg>PhaseIconsLayer: Convert to Glimmer component<commit_after>import { action } from '@ember/object';
import Component from '@glimmer/component';

import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Icon from 'ol/style/Icon';
import Style from 'ol/style/Style';

const START_ICON = new Icon({
  anchor: [0.5, 1],
  src: '/images/marker-green.png',
});

const END_ICON = new Icon({
  anchor: [0.5, 1],
  src: '/images/marker.png',
});

START_ICON.load();
END_ICON.load();

const START_STYLE = new Style({ image: START_ICON });
const END_STYLE = new Style({ image: END_ICON });

export default class PhaseIconsLayer extends Component {
  layer = new VectorLayer({
    source: new VectorSource({
      useSpatialIndex: false,
    }),
    style(feature) {
      return feature.get('type') === 'end' ? END_STYLE : START_STYLE;
    },
    zIndex: 100,
  });

  constructor() {
    super(...arguments);
    this.args.map.addLayer(this.layer);
    this.updateSource();
  }

  willDestroy() {
    super.willDestroy(...arguments);
    this.args.map.removeLayer(this.layer);
  }

  @action
  updateSource() {
    let source = this.layer.getSource();

    source.clear();

    let { coordinates } = this.args;
    if (coordinates) {
      let startPoint = new Point(coordinates[0]);
      let endPoint = new Point(coordinates[coordinates.length - 1]);

      let startFeature = new Feature({ geometry: startPoint, type: 'start' });
      let endFeature = new Feature({ geometry: endPoint, type: 'end' });

      source.addFeature(startFeature);
      source.addFeature(endFeature);
    }
  }
}
<|endoftext|>


<commit_before>(function (window, document, undefined) {
	"use strict";

	angular.module('angularWidgets')
		.factory('widgetInputText', ['widgetBase', '$compile', '$interpolate', InputTextWidget])
		.directive('wgInputtext', ['widgetInputText', InputTextDirective]);

	function InputTextWidget(widgetBase, $compile, $interpolate) {

		AngularWidgets.configureWidget('inputtext', {
			onEnterKey: undefined
		});

		var widget = {};

		widget.template = '<input type="text" class="pui-inputtext ui-widget ui-state-default ui-corner-all" />';

		widget.buildWidget = function(scope, element, options) {
			return new widget.Inputtext(scope, element, options);
		};

		widget.Inputtext = widgetBase.createWidget({

			init: function(options) {

				var $this = this;

				this.determineOptions(options);

				this.element.attr({
					'ng-model': this.options.value,
					'name' : this.options.name || this.options.value.replace('\.', '_')
				});

				if (this.options.disabled) {

					this.element.attr('ng-disabled', this.options.disabled);

					this.scope.$watch(this.options.disabled, function (value) {
						$this.onChangeDisabled(value);
					});
				}
				else {
					this.onChangeDisabled(false);
				}

				$compile(this.element)(this.scope);

				this.element[0].removeAttribute('value');
				this.element[0].removeAttribute('disabled');

				//aria
				this.element.attr({
					'role': 'textbox',
					'aria-readonly': this.element.prop('readonly'),
					'aria-multiline': false
				});

				widgetBase.createBindAndAssignIfNecessary(this, "enable,disable,enableDisable,getValue");
			},

			determineOptions: function (options) {
				this.options = widgetBase.determineOptions(this.scope, AngularWidgets.getConfiguration().widgets.inputtext, options, ['onEnterKey'], ['disabled']);
			},

            bindEvents: function() {

                var $this = this;

				widgetBase.hoverAndFocus(this.element);

				widgetBase.handleOnEnterKey(this.scope, this.element, function() { $this.options.onEnterKey($this.bindInstance); });
			},

			unbindEvents: function() {

			},

			onChangeDisabled: function(disabled) {

				this.element.attr('aria-disabled', disabled);

                if (disabled) {
                    this.element
                        .addClass('ui-state-disabled')
                        .removeClass('ui-state-focus ui-state-hover');
                    this.unbindEvents();
                }
                else {
                    this.element.removeClass('ui-state-disabled');
                    this.bindEvents();
                }
			},

			enableDisable: function() {

                var disabled = widgetBase.getModelValue(this.scope, this.options.disabled);

                if (disabled) {
                    this.disable();
                }
                else {
                    this.enable();
                }
			},

			enable: function() {
                widgetBase.setModelValue(this.scope, this.options.disabled, false);
			},

			disable: function() {
                widgetBase.setModelValue(this.scope, this.options.disabled, true);
			},

			getValue: function() {
				return widgetBase.getModelValue(this.scope, this.options.value);
			}
		});

		/* TODO - Deprecated - autocomplete use that */
		widget.enableDisableStatic = function (inputElement, value) {
			if (value === true) {
				widgetBase.resetHoverAndFocus(inputElement);
				inputElement.addClass('ui-state-disabled');
				inputElement.attr('disabled','disabled');
			}
			else {
				inputElement.removeClass('ui-state-disabled');
				widgetBase.hoverAndFocus(inputElement);
				inputElement.removeAttr('disabled');
			}
		};

		return widget;
	}

	function InputTextDirective(widgetInputText) {
		return {
			restrict: 'E',
			scope: true,
			link: function(scope, element, attrs) {
				widgetInputText.buildWidget(scope, element, attrs);
			},
			replace: true,
			template: widgetInputText.template
		};
	}

}(window, document));<commit_msg>Correção do bug do onEnterKey do componente inputText.<commit_after>(function (window, document, undefined) {
	"use strict";

	angular.module('angularWidgets')
		.factory('widgetInputText', ['widgetBase', '$compile', '$interpolate', InputTextWidget])
		.directive('wgInputtext', ['widgetInputText', InputTextDirective]);

	function InputTextWidget(widgetBase, $compile, $interpolate) {

		AngularWidgets.configureWidget('inputtext', {
			onEnterKey: undefined
		});

		var widget = {};

		widget.template = '<input type="text" class="pui-inputtext ui-widget ui-state-default ui-corner-all" />';

		widget.buildWidget = function(scope, element, options) {
			return new widget.Inputtext(scope, element, options);
		};

		widget.Inputtext = widgetBase.createWidget({

			init: function(options) {

				var $this = this;

				this.determineOptions(options);

				this.element.attr({
					'ng-model': this.options.value,
					'name' : this.options.name || this.options.value.replace('\.', '_')
				});

				if (this.options.disabled) {

					this.element.attr('ng-disabled', this.options.disabled);

					this.scope.$watch(this.options.disabled, function (value) {
						$this.onChangeDisabled(value);
					});
				}
				else {
					this.onChangeDisabled(false);
				}

				$compile(this.element)(this.scope);

				this.element[0].removeAttribute('value');
				this.element[0].removeAttribute('disabled');

				//aria
				this.element.attr({
					'role': 'textbox',
					'aria-readonly': this.element.prop('readonly'),
					'aria-multiline': false
				});

				widgetBase.createBindAndAssignIfNecessary(this, "enable,disable,enableDisable,getValue");
			},

			determineOptions: function (options) {
				this.options = widgetBase.determineOptions(this.scope, AngularWidgets.getConfiguration().widgets.inputtext, options, [], ['disabled']);
			},

            bindEvents: function() {

                var $this = this;

				widgetBase.hoverAndFocus(this.element);

				if (this.options.onEnterKey) {
					widgetBase.handleOnEnterKey(this.scope, this.element, function() {
						$this.scope.$eval($this.options.onEnterKey);
					});
				}
			},

			unbindEvents: function() {

			},

			onChangeDisabled: function(disabled) {

				this.element.attr('aria-disabled', disabled);

                if (disabled) {
                    this.element
                        .addClass('ui-state-disabled')
                        .removeClass('ui-state-focus ui-state-hover');
                    this.unbindEvents();
                }
                else {
                    this.element.removeClass('ui-state-disabled');
                    this.bindEvents();
                }
			},

			enableDisable: function() {

                var disabled = widgetBase.getModelValue(this.scope, this.options.disabled);

                if (disabled) {
                    this.disable();
                }
                else {
                    this.enable();
                }
			},

			enable: function() {
                widgetBase.setModelValue(this.scope, this.options.disabled, false);
			},

			disable: function() {
                widgetBase.setModelValue(this.scope, this.options.disabled, true);
			},

			getValue: function() {
				return widgetBase.getModelValue(this.scope, this.options.value);
			}
		});

		/* TODO - Deprecated - autocomplete use that */
		widget.enableDisableStatic = function (inputElement, value) {
			if (value === true) {
				widgetBase.resetHoverAndFocus(inputElement);
				inputElement.addClass('ui-state-disabled');
				inputElement.attr('disabled','disabled');
			}
			else {
				inputElement.removeClass('ui-state-disabled');
				widgetBase.hoverAndFocus(inputElement);
				inputElement.removeAttr('disabled');
			}
		};

		return widget;
	}

	function InputTextDirective(widgetInputText) {
		return {
			restrict: 'E',
			scope: true,
			link: function(scope, element, attrs) {
				widgetInputText.buildWidget(scope, element, attrs);
			},
			replace: true,
			template: widgetInputText.template
		};
	}

}(window, document));<|endoftext|>


<commit_before>module.exports = {
  mixins: [__dirname],
  fragmentsFile: '<rootDir>/fragmentTypes.json',
  graphqlMockServerPath: '/graphql',
  shouldPrefetchOnServer: true,
  configSchema: {
    fragmentsFile: {
      type: 'string',
      absolutePath: true,
    },
    graphqlUri: {
      type: 'string',
      format: 'uri',
    },
    graphqlSchemaFile: {
      type: 'string',
      absolutePath: true,
    },
    graphqlMockSchemaFile: {
      type: 'string',
    },
    graphqlMockServerPath: {
      type: 'string',
    },
    shouldPrefetchOnServer: {
      type: 'boolean',
    },
  },
};
<commit_msg>fix(graphql): add graphqlUri to browser whitelist<commit_after>module.exports = {
  mixins: [__dirname],
  fragmentsFile: '<rootDir>/fragmentTypes.json',
  graphqlMockServerPath: '/graphql',
  shouldPrefetchOnServer: true,
  browserWhitelist: {
    graphqlUri: true,
  },
  configSchema: {
    fragmentsFile: {
      type: 'string',
      absolutePath: true,
    },
    graphqlUri: {
      type: 'string',
      format: 'uri',
    },
    graphqlSchemaFile: {
      type: 'string',
      absolutePath: true,
    },
    graphqlMockSchemaFile: {
      type: 'string',
    },
    graphqlMockServerPath: {
      type: 'string',
    },
    shouldPrefetchOnServer: {
      type: 'boolean',
    },
  },
};
<|endoftext|>


<commit_before>/* global alert */

// Common modules
import '../../common'

import htmlEncode from 'htmlencode'

const api = require('../../get-api-data')
const browser = require('../../browser')
const endpoints = require('../../api')
const location = require('../../location/locationSelector')
const templating = require('../../template-render')
const wp = require('../../wordpress')
const MapBuilder = require('../../models/accommodation/MapBuilder')

const initLocations = function (currentLocationId) {
  const ui = {
    form: document.querySelector('.js-change-location-form'),
    select: document.querySelector('.js-change-location-select')
  }

  ui.form.addEventListener('submit', function (e) {
    e.preventDefault()
    const reqLocation = ui.select.value
    if (reqLocation) {
      location.setCurrent(reqLocation)
      browser.redirect(`/${reqLocation}`)
    }
  })

  const redirectToHubPage = function (locationId) {
    location.setCurrent(locationId)
    browser.redirect(`/${locationId}`)
  }

  Array.from(document.querySelector('.js-change-location-select'))
  .filter((t) => t.tagName === 'OPTION')
  .find((o) => o.value === currentLocationId)
  .setAttribute('selected', 'selected')

  location.handler((result) => {
    if (result.length) {
      redirectToHubPage(result)
    }
  }, '.js-change-location-select')
}

const initNews = function (currentLocationId) {
  const reqPosts = 3
  wp
    .getPostsByLocation(currentLocationId, reqPosts, 0, true)
    .then((result) => {
      if (result.posts.length === reqPosts) {
        templating.renderTemplate('js-news-tpl', result, 'js-news-output')
      }
    })
}

const initFindHelp = function (currentLocation) {
  const ui = {
    form: document.querySelector('.js-find-help-form'),
    postcode: document.querySelector('.js-find-help-postcode')
  }

  ui.postcode.setAttribute('placeholder', `your postcode: eg ${currentLocation.postcode}`)
  ui.postcode.value = currentLocation.postcode

  ui.form.addEventListener('submit', function (e) {
    e.preventDefault()
    const reqLocation = ui.postcode.value
    location.setPostcode(reqLocation, () => {
      browser.redirect('/find-help/all-service-providers/')
    }, () => alert('We could not find your postcode, please try a nearby one'))
  })
}

const initStatistics = function (currentLocation) {
  const stats = [
    { field: 'totalServiceProviders', link: '/find-help/all-service-providers/', label: 'Organisations' },
    { field: 'totalPledges', link: 'https://charter.streetsupport.net/progress/', label: 'Pledges' },
    { field: 'totalVolunteers', link: '/give-help/volunteer/', label: 'Volunteers' },
    { field: 'totalNeeds', link: '/give-help/help/', label: 'Needs' }
  ]
  const requiredStats = currentLocation.homePageStats.length
    ? currentLocation.homePageStats
    : ['totalServiceProviders', 'totalNeeds', 'totalVolunteers']
  api
    .data(endpoints.statistics + currentLocation.id + '/latest')
    .then((result) => {
      const theData = {
        statistics: requiredStats
          .map((rs) => {
            const reqStat = stats.find((s) => s.field === rs)
            return {
              total: result.data[rs],
              link: reqStat.link,
              label: reqStat.label
            }
          })
      }

      templating.renderTemplate('js-statistics-tpl', theData, 'js-statistics-output')
    }, (_) => {
    })
}
window.initMap = () => { }

const initMap = function (currentLocation) {
  const endpoint = `${endpoints.serviceProviderLocations}?latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}&range=20000&pageSize=1000`

  const buildInfoWindowMarkup = (p) => {
    return `

                <button class="card__close js-popup-close" title="close">⨯</button>

${htmlEncode.htmlDecode(p.serviceProviderName)}

${htmlEncode.htmlDecode(p.serviceProviderSynopsis)}

                View details

`
  }
  const getLocation = (p) => {
    return { latitude: p.latitude, longitude: p.longitude }
  }
  const map = new MapBuilder()
  api
    .data(endpoint)
    .then((result) => {
      const zoom = currentLocation.id === 'bournemouth'
        ? 11 // stinky
        : 12
      map.init(result.data.items, currentLocation, null, buildInfoWindowMarkup, getLocation, { zoom })
    }, (_) => {
    })
}

const initSwep = function (currentLocationId) {
  api
  .data(endpoints.cities)
  .then((result) => {
    const city = result.data.find((c) => c.id === currentLocationId)
    if (city.swepIsAvailable) {
      templating.renderTemplate('js-swep-tpl', city, 'js-swep-output')
    }
  }, (_) => {})
}

const currentLocation = location.getCurrentHub()

initLocations(currentLocation.id)
initNews(currentLocation.id)
initFindHelp(currentLocation)
initStatistics(currentLocation)
initMap(currentLocation)
initSwep(currentLocation.id)
<commit_msg>fix location home page stats<commit_after>/* global alert */

// Common modules
import '../../common'

import htmlEncode from 'htmlencode'

const api = require('../../get-api-data')
const browser = require('../../browser')
const endpoints = require('../../api')
const location = require('../../location/locationSelector')
const templating = require('../../template-render')
const wp = require('../../wordpress')
const MapBuilder = require('../../models/accommodation/MapBuilder')

const initLocations = function (currentLocationId) {
  const ui = {
    form: document.querySelector('.js-change-location-form'),
    select: document.querySelector('.js-change-location-select')
  }

  ui.form.addEventListener('submit', function (e) {
    e.preventDefault()
    const reqLocation = ui.select.value
    if (reqLocation) {
      location.setCurrent(reqLocation)
      browser.redirect(`/${reqLocation}`)
    }
  })

  const redirectToHubPage = function (locationId) {
    location.setCurrent(locationId)
    browser.redirect(`/${locationId}`)
  }

  Array.from(document.querySelector('.js-change-location-select'))
  .filter((t) => t.tagName === 'OPTION')
  .find((o) => o.value === currentLocationId)
  .setAttribute('selected', 'selected')

  location.handler((result) => {
    if (result.length) {
      redirectToHubPage(result)
    }
  }, '.js-change-location-select')
}

const initNews = function (currentLocationId) {
  const reqPosts = 3
  wp
    .getPostsByLocation(currentLocationId, reqPosts, 0, true)
    .then((result) => {
      if (result.posts.length === reqPosts) {
        templating.renderTemplate('js-news-tpl', result, 'js-news-output')
      }
    })
}

const initFindHelp = function (currentLocation) {
  const ui = {
    form: document.querySelector('.js-find-help-form'),
    postcode: document.querySelector('.js-find-help-postcode')
  }

  ui.postcode.setAttribute('placeholder', `your postcode: eg ${currentLocation.postcode}`)
  ui.postcode.value = currentLocation.postcode

  ui.form.addEventListener('submit', function (e) {
    e.preventDefault()
    const reqLocation = ui.postcode.value
    location.setPostcode(reqLocation, () => {
      browser.redirect('/find-help/all-service-providers/')
    }, () => alert('We could not find your postcode, please try a nearby one'))
  })
}

const initStatistics = function (currentLocation) {
  const stats = [
    { field: 'totalServiceProviders', link: '/find-help/all-service-providers/', label: 'Organisations' },
    { field: 'totalPledges', link: 'https://charter.streetsupport.net/progress/', label: 'Pledges' },
    { field: 'totalVolunteers', link: '/give-help/volunteer/', label: 'Volunteers' },
    { field: 'totalNeeds', link: '/give-help/help/', label: 'Needs' }
  ]
  const requiredStats = currentLocation.homePageStats
    ? currentLocation.homePageStats
    : ['totalServiceProviders', 'totalNeeds', 'totalVolunteers']
  api
    .data(endpoints.statistics + currentLocation.id + '/latest')
    .then((result) => {
      const theData = {
        statistics: requiredStats
          .map((rs) => {
            const reqStat = stats.find((s) => s.field === rs)
            return {
              total: result.data[rs],
              link: reqStat.link,
              label: reqStat.label
            }
          })
      }

      templating.renderTemplate('js-statistics-tpl', theData, 'js-statistics-output')
    }, (_) => {
    })
}
window.initMap = () => { }

const initMap = function (currentLocation) {
  const endpoint = `${endpoints.serviceProviderLocations}?latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}&range=20000&pageSize=1000`

  const buildInfoWindowMarkup = (p) => {
    return `

                <button class="card__close js-popup-close" title="close">⨯</button>

${htmlEncode.htmlDecode(p.serviceProviderName)}

${htmlEncode.htmlDecode(p.serviceProviderSynopsis)}

                View details

`
  }
  const getLocation = (p) => {
    return { latitude: p.latitude, longitude: p.longitude }
  }
  const map = new MapBuilder()
  api
    .data(endpoint)
    .then((result) => {
      const zoom = currentLocation.id === 'bournemouth'
        ? 11 // stinky
        : 12
      map.init(result.data.items, currentLocation, null, buildInfoWindowMarkup, getLocation, { zoom })
    }, (_) => {
    })
}

const initSwep = function (currentLocationId) {
  api
  .data(endpoints.cities)
  .then((result) => {
    const city = result.data.find((c) => c.id === currentLocationId)
    if (city.swepIsAvailable) {
      templating.renderTemplate('js-swep-tpl', city, 'js-swep-output')
    }
  }, (_) => {})
}

const currentLocation = location.getCurrentHub()

initLocations(currentLocation.id)
initNews(currentLocation.id)
initFindHelp(currentLocation)
initStatistics(currentLocation)
initMap(currentLocation)
initSwep(currentLocation.id)
<|endoftext|>