code stringlengths 2 1.05M |
|---|
/**
* @license Highmaps JS v9.3.2 (2021-11-29)
*
* Highmaps as a plugin for Highcharts or Highcharts Stock.
*
* (c) 2011-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/modules/map', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Core/Axis/Color/ColorAxisComposition.js', [_modules['Core/Color/Color.js'], _modules['Core/Utilities.js']], function (Color, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var color = Color.parse;
var addEvent = U.addEvent,
extend = U.extend,
merge = U.merge,
pick = U.pick,
splat = U.splat;
/* *
*
* Composition
*
* */
var ColorAxisComposition;
(function (ColorAxisComposition) {
/* *
*
* Declarations
*
* */
/* *
*
* Constants
*
* */
var composedClasses = [];
/* *
*
* Variables
*
* */
var ColorAxisClass;
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* @private
*/
function compose(ColorAxisType, ChartClass, FxClass, LegendClass, SeriesClass) {
if (!ColorAxisClass) {
ColorAxisClass = ColorAxisType;
}
if (composedClasses.indexOf(ChartClass) === -1) {
composedClasses.push(ChartClass);
var chartProto = ChartClass.prototype;
chartProto.collectionsWithUpdate.push('colorAxis');
chartProto.collectionsWithInit.colorAxis = [
chartProto.addColorAxis
];
addEvent(ChartClass, 'afterGetAxes', onChartAfterGetAxes);
wrapChartCreateAxis(ChartClass);
}
if (composedClasses.indexOf(FxClass) === -1) {
composedClasses.push(FxClass);
var fxProto = FxClass.prototype;
fxProto.fillSetter = wrapFxFillSetter;
fxProto.strokeSetter = wrapFxStrokeSetter;
}
if (composedClasses.indexOf(LegendClass) === -1) {
composedClasses.push(LegendClass);
addEvent(LegendClass, 'afterGetAllItems', onLegendAfterGetAllItems);
addEvent(LegendClass, 'afterColorizeItem', onLegendAfterColorizeItem);
addEvent(LegendClass, 'afterUpdate', onLegendAfterUpdate);
}
if (composedClasses.indexOf(SeriesClass) === -1) {
composedClasses.push(SeriesClass);
extend(SeriesClass.prototype, {
optionalAxis: 'colorAxis',
translateColors: seriesTranslateColors
});
extend(SeriesClass.prototype.pointClass.prototype, {
setVisible: pointSetVisible
});
addEvent(SeriesClass, 'afterTranslate', onSeriesAfterTranslate);
addEvent(SeriesClass, 'bindAxes', onSeriesBindAxes);
}
}
ColorAxisComposition.compose = compose;
/**
* Extend the chart getAxes method to also get the color axis.
* @private
*/
function onChartAfterGetAxes() {
var _this = this;
var options = this.options;
this.colorAxis = [];
if (options.colorAxis) {
options.colorAxis = splat(options.colorAxis);
options.colorAxis.forEach(function (axisOptions, i) {
axisOptions.index = i;
new ColorAxisClass(_this, axisOptions); // eslint-disable-line no-new
});
}
}
/**
* Add the color axis. This also removes the axis' own series to prevent
* them from showing up individually.
* @private
*/
function onLegendAfterGetAllItems(e) {
var _this = this;
var colorAxes = this.chart.colorAxis || [],
destroyItem = function (item) {
var i = e.allItems.indexOf(item);
if (i !== -1) {
// #15436
_this.destroyItem(e.allItems[i]);
e.allItems.splice(i, 1);
}
};
var colorAxisItems = [],
options,
i;
colorAxes.forEach(function (colorAxis) {
options = colorAxis.options;
if (options && options.showInLegend) {
// Data classes
if (options.dataClasses && options.visible) {
colorAxisItems = colorAxisItems.concat(colorAxis.getDataClassLegendSymbols());
// Gradient legend
}
else if (options.visible) {
// Add this axis on top
colorAxisItems.push(colorAxis);
}
// If dataClasses are defined or showInLegend option is not set
// to true, do not add color axis' series to legend.
colorAxis.series.forEach(function (series) {
if (!series.options.showInLegend || options.dataClasses) {
if (series.options.legendType === 'point') {
series.points.forEach(function (point) {
destroyItem(point);
});
}
else {
destroyItem(series);
}
}
});
}
});
i = colorAxisItems.length;
while (i--) {
e.allItems.unshift(colorAxisItems[i]);
}
}
/**
* @private
*/
function onLegendAfterColorizeItem(e) {
if (e.visible && e.item.legendColor) {
e.item.legendSymbol.attr({
fill: e.item.legendColor
});
}
}
/**
* Updates in the legend need to be reflected in the color axis. (#6888)
* @private
*/
function onLegendAfterUpdate() {
var colorAxes = this.chart.colorAxis;
if (colorAxes) {
colorAxes.forEach(function (colorAxis) {
colorAxis.update({}, arguments[2]);
});
}
}
/**
* Calculate and set colors for points.
* @private
*/
function onSeriesAfterTranslate() {
if (this.chart.colorAxis &&
this.chart.colorAxis.length ||
this.colorAttribs) {
this.translateColors();
}
}
/**
* Add colorAxis to series axisTypes.
* @private
*/
function onSeriesBindAxes() {
var axisTypes = this.axisTypes;
if (!axisTypes) {
this.axisTypes = ['colorAxis'];
}
else if (axisTypes.indexOf('colorAxis') === -1) {
axisTypes.push('colorAxis');
}
}
/**
* Set the visibility of a single point
* @private
* @function Highcharts.colorPointMixin.setVisible
* @param {boolean} visible
*/
function pointSetVisible(vis) {
var point = this,
method = vis ? 'show' : 'hide';
point.visible = point.options.visible = Boolean(vis);
// Show and hide associated elements
['graphic', 'dataLabel'].forEach(function (key) {
if (point[key]) {
point[key][method]();
}
});
this.series.buildKDTree(); // rebuild kdtree #13195
}
ColorAxisComposition.pointSetVisible = pointSetVisible;
/**
* In choropleth maps, the color is a result of the value, so this needs
* translation too
* @private
* @function Highcharts.colorSeriesMixin.translateColors
*/
function seriesTranslateColors() {
var series = this,
points = this.data.length ? this.data : this.points,
nullColor = this.options.nullColor,
colorAxis = this.colorAxis,
colorKey = this.colorKey;
points.forEach(function (point) {
var value = point.getNestedProperty(colorKey),
color = point.options.color || (point.isNull || point.value === null ?
nullColor :
(colorAxis && typeof value !== 'undefined') ?
colorAxis.toColor(value,
point) :
point.color || series.color);
if (color && point.color !== color) {
point.color = color;
if (series.options.legendType === 'point' && point.legendItem) {
series.chart.legend.colorizeItem(point, point.visible);
}
}
});
}
/**
* @private
*/
function wrapChartCreateAxis(ChartClass) {
var superCreateAxis = ChartClass.prototype.createAxis;
ChartClass.prototype.createAxis = function (type, options) {
if (type !== 'colorAxis') {
return superCreateAxis.apply(this, arguments);
}
var axis = new ColorAxisClass(this,
merge(options.axis, {
index: this[type].length,
isX: false
}));
this.isDirtyLegend = true;
// Clear before 'bindAxes' (#11924)
this.axes.forEach(function (axis) {
axis.series = [];
});
this.series.forEach(function (series) {
series.bindAxes();
series.isDirtyData = true;
});
if (pick(options.redraw, true)) {
this.redraw(options.animation);
}
return axis;
};
}
/**
* Handle animation of the color attributes directly.
* @private
*/
function wrapFxFillSetter() {
this.elem.attr('fill', color(this.start).tweenTo(color(this.end), this.pos), void 0, true);
}
/**
* Handle animation of the color attributes directly.
* @private
*/
function wrapFxStrokeSetter() {
this.elem.attr('stroke', color(this.start).tweenTo(color(this.end), this.pos), void 0, true);
}
})(ColorAxisComposition || (ColorAxisComposition = {}));
/* *
*
* Default Export
*
* */
return ColorAxisComposition;
});
_registerModule(_modules, 'Core/Axis/Color/ColorAxisDefaults.js', [], function () {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
/* *
*
* API Options
*
* */
/**
* A color axis for series. Visually, the color
* axis will appear as a gradient or as separate items inside the
* legend, depending on whether the axis is scalar or based on data
* classes.
*
* For supported color formats, see the
* [docs article about colors](https://www.highcharts.com/docs/chart-design-and-style/colors).
*
* A scalar color axis is represented by a gradient. The colors either
* range between the [minColor](#colorAxis.minColor) and the
* [maxColor](#colorAxis.maxColor), or for more fine grained control the
* colors can be defined in [stops](#colorAxis.stops). Often times, the
* color axis needs to be adjusted to get the right color spread for the
* data. In addition to stops, consider using a logarithmic
* [axis type](#colorAxis.type), or setting [min](#colorAxis.min) and
* [max](#colorAxis.max) to avoid the colors being determined by
* outliers.
*
* When [dataClasses](#colorAxis.dataClasses) are used, the ranges are
* subdivided into separate classes like categories based on their
* values. This can be used for ranges between two values, but also for
* a true category. However, when your data is categorized, it may be as
* convenient to add each category to a separate series.
*
* Color axis does not work with: `sankey`, `sunburst`, `dependencywheel`,
* `networkgraph`, `wordcloud`, `venn`, `gauge` and `solidgauge` series
* types.
*
* Since v7.2.0 `colorAxis` can also be an array of options objects.
*
* See [the Axis object](/class-reference/Highcharts.Axis) for
* programmatic access to the axis.
*
* @sample {highcharts} highcharts/coloraxis/custom-color-key
* Column chart with color axis
* @sample {highcharts} highcharts/coloraxis/horizontal-layout
* Horizontal layout
* @sample {highmaps} maps/coloraxis/dataclasscolor
* With data classes
* @sample {highmaps} maps/coloraxis/mincolor-maxcolor
* Min color and max color
*
* @extends xAxis
* @excluding alignTicks, allowDecimals, alternateGridColor, breaks,
* categories, crosshair, dateTimeLabelFormats, height, left,
* lineWidth, linkedTo, maxZoom, minRange, minTickInterval,
* offset, opposite, pane, plotBands, plotLines,
* reversedStacks, scrollbar, showEmpty, title, top, width,
* zoomEnabled
* @product highcharts highstock highmaps
* @type {*|Array<*>}
* @optionparent colorAxis
*/
var colorAxisDefaults = {
/**
* Whether to allow decimals on the color axis.
* @type {boolean}
* @default true
* @product highcharts highstock highmaps
* @apioption colorAxis.allowDecimals
*/
/**
* Determines how to set each data class' color if no individual
* color is set. The default value, `tween`, computes intermediate
* colors between `minColor` and `maxColor`. The other possible
* value, `category`, pulls colors from the global or chart specific
* [colors](#colors) array.
*
* @sample {highmaps} maps/coloraxis/dataclasscolor/
* Category colors
*
* @type {string}
* @default tween
* @product highcharts highstock highmaps
* @validvalue ["tween", "category"]
* @apioption colorAxis.dataClassColor
*/
/**
* An array of data classes or ranges for the choropleth map. If
* none given, the color axis is scalar and values are distributed
* as a gradient between the minimum and maximum colors.
*
* @sample {highmaps} maps/demo/data-class-ranges/
* Multiple ranges
*
* @sample {highmaps} maps/demo/data-class-two-ranges/
* Two ranges
*
* @type {Array<*>}
* @product highcharts highstock highmaps
* @apioption colorAxis.dataClasses
*/
/**
* The layout of the color axis. Can be `'horizontal'` or `'vertical'`.
* If none given, the color axis has the same layout as the legend.
*
* @sample highcharts/coloraxis/horizontal-layout/
* Horizontal color axis layout with vertical legend
*
* @type {string|undefined}
* @since 7.2.0
* @product highcharts highstock highmaps
* @apioption colorAxis.layout
*/
/**
* The color of each data class. If not set, the color is pulled
* from the global or chart-specific [colors](#colors) array. In
* styled mode, this option is ignored. Instead, use colors defined
* in CSS.
*
* @sample {highmaps} maps/demo/data-class-two-ranges/
* Explicit colors
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highstock highmaps
* @apioption colorAxis.dataClasses.color
*/
/**
* The start of the value range that the data class represents,
* relating to the point value.
*
* The range of each `dataClass` is closed in both ends, but can be
* overridden by the next `dataClass`.
*
* @type {number}
* @product highcharts highstock highmaps
* @apioption colorAxis.dataClasses.from
*/
/**
* The name of the data class as it appears in the legend.
* If no name is given, it is automatically created based on the
* `from` and `to` values. For full programmatic control,
* [legend.labelFormatter](#legend.labelFormatter) can be used.
* In the formatter, `this.from` and `this.to` can be accessed.
*
* @sample {highmaps} maps/coloraxis/dataclasses-name/
* Named data classes
*
* @sample {highmaps} maps/coloraxis/dataclasses-labelformatter/
* Formatted data classes
*
* @type {string}
* @product highcharts highstock highmaps
* @apioption colorAxis.dataClasses.name
*/
/**
* The end of the value range that the data class represents,
* relating to the point value.
*
* The range of each `dataClass` is closed in both ends, but can be
* overridden by the next `dataClass`.
*
* @type {number}
* @product highcharts highstock highmaps
* @apioption colorAxis.dataClasses.to
*/
/** @ignore-option */
lineWidth: 0,
/**
* Padding of the min value relative to the length of the axis. A
* padding of 0.05 will make a 100px axis 5px longer.
*
* @product highcharts highstock highmaps
*/
minPadding: 0,
/**
* The maximum value of the axis in terms of map point values. If
* `null`, the max value is automatically calculated. If the
* `endOnTick` option is true, the max value might be rounded up.
*
* @sample {highmaps} maps/coloraxis/gridlines/
* Explicit min and max to reduce the effect of outliers
*
* @type {number}
* @product highcharts highstock highmaps
* @apioption colorAxis.max
*/
/**
* The minimum value of the axis in terms of map point values. If
* `null`, the min value is automatically calculated. If the
* `startOnTick` option is true, the min value might be rounded
* down.
*
* @sample {highmaps} maps/coloraxis/gridlines/
* Explicit min and max to reduce the effect of outliers
*
* @type {number}
* @product highcharts highstock highmaps
* @apioption colorAxis.min
*/
/**
* Padding of the max value relative to the length of the axis. A
* padding of 0.05 will make a 100px axis 5px longer.
*
* @product highcharts highstock highmaps
*/
maxPadding: 0,
/**
* Color of the grid lines extending from the axis across the
* gradient.
*
* @sample {highmaps} maps/coloraxis/gridlines/
* Grid lines demonstrated
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #e6e6e6
* @product highcharts highstock highmaps
* @apioption colorAxis.gridLineColor
*/
/**
* The width of the grid lines extending from the axis across the
* gradient of a scalar color axis.
*
* @sample {highmaps} maps/coloraxis/gridlines/
* Grid lines demonstrated
*
* @product highcharts highstock highmaps
*/
gridLineWidth: 1,
/**
* The interval of the tick marks in axis units. When `null`, the
* tick interval is computed to approximately follow the
* `tickPixelInterval`.
*
* @type {number}
* @product highcharts highstock highmaps
* @apioption colorAxis.tickInterval
*/
/**
* If [tickInterval](#colorAxis.tickInterval) is `null` this option
* sets the approximate pixel interval of the tick marks.
*
* @product highcharts highstock highmaps
*/
tickPixelInterval: 72,
/**
* Whether to force the axis to start on a tick. Use this option
* with the `maxPadding` option to control the axis start.
*
* @product highcharts highstock highmaps
*/
startOnTick: true,
/**
* Whether to force the axis to end on a tick. Use this option with
* the [maxPadding](#colorAxis.maxPadding) option to control the
* axis end.
*
* @product highcharts highstock highmaps
*/
endOnTick: true,
/** @ignore */
offset: 0,
/**
* The triangular marker on a scalar color axis that points to the
* value of the hovered area. To disable the marker, set
* `marker: null`.
*
* @sample {highmaps} maps/coloraxis/marker/
* Black marker
*
* @declare Highcharts.PointMarkerOptionsObject
* @product highcharts highstock highmaps
*/
marker: {
/**
* Animation for the marker as it moves between values. Set to
* `false` to disable animation. Defaults to `{ duration: 50 }`.
*
* @type {boolean|Partial<Highcharts.AnimationOptionsObject>}
* @product highcharts highstock highmaps
*/
animation: {
/** @internal */
duration: 50
},
/** @internal */
width: 0.01,
/**
* The color of the marker.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highstock highmaps
*/
color: "#999999" /* neutralColor40 */
},
/**
* The axis labels show the number for each tick.
*
* For more live examples on label options, see [xAxis.labels in the
* Highcharts API.](/highcharts#xAxis.labels)
*
* @extends xAxis.labels
* @product highcharts highstock highmaps
*/
labels: {
/**
* How to handle overflowing labels on horizontal color axis. If set
* to `"allow"`, it will not be aligned at all. By default it
* `"justify"` labels inside the chart area. If there is room to
* move it, it will be aligned to the edge, else it will be removed.
*
* @validvalue ["allow", "justify"]
* @product highcharts highstock highmaps
*/
overflow: 'justify',
rotation: 0
},
/**
* The color to represent the minimum of the color axis. Unless
* [dataClasses](#colorAxis.dataClasses) or
* [stops](#colorAxis.stops) are set, the gradient starts at this
* value.
*
* If dataClasses are set, the color is based on minColor and
* maxColor unless a color is set for each data class, or the
* [dataClassColor](#colorAxis.dataClassColor) is set.
*
* @sample {highmaps} maps/coloraxis/mincolor-maxcolor/
* Min and max colors on scalar (gradient) axis
* @sample {highmaps} maps/coloraxis/mincolor-maxcolor-dataclasses/
* On data classes
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highstock highmaps
*/
minColor: "#e6ebf5" /* highlightColor10 */,
/**
* The color to represent the maximum of the color axis. Unless
* [dataClasses](#colorAxis.dataClasses) or
* [stops](#colorAxis.stops) are set, the gradient ends at this
* value.
*
* If dataClasses are set, the color is based on minColor and
* maxColor unless a color is set for each data class, or the
* [dataClassColor](#colorAxis.dataClassColor) is set.
*
* @sample {highmaps} maps/coloraxis/mincolor-maxcolor/
* Min and max colors on scalar (gradient) axis
* @sample {highmaps} maps/coloraxis/mincolor-maxcolor-dataclasses/
* On data classes
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highstock highmaps
*/
maxColor: "#003399" /* highlightColor100 */,
/**
* Color stops for the gradient of a scalar color axis. Use this in
* cases where a linear gradient between a `minColor` and `maxColor`
* is not sufficient. The stops is an array of tuples, where the
* first item is a float between 0 and 1 assigning the relative
* position in the gradient, and the second item is the color.
*
* @sample {highmaps} maps/demo/heatmap/
* Heatmap with three color stops
*
* @type {Array<Array<number,Highcharts.ColorString>>}
* @product highcharts highstock highmaps
* @apioption colorAxis.stops
*/
/**
* The pixel length of the main tick marks on the color axis.
*/
tickLength: 5,
/**
* The type of interpolation to use for the color axis. Can be
* `linear` or `logarithmic`.
*
* @sample highcharts/coloraxis/logarithmic-with-emulate-negative-values/
* Logarithmic color axis with extension to emulate negative
* values
*
* @type {Highcharts.ColorAxisTypeValue}
* @default linear
* @product highcharts highstock highmaps
* @apioption colorAxis.type
*/
/**
* Whether to reverse the axis so that the highest number is closest
* to the origin. Defaults to `false` in a horizontal legend and
* `true` in a vertical legend, where the smallest value starts on
* top.
*
* @type {boolean}
* @product highcharts highstock highmaps
* @apioption colorAxis.reversed
*/
/**
* @product highcharts highstock highmaps
* @excluding afterBreaks, pointBreak, pointInBreak
* @apioption colorAxis.events
*/
/**
* Fires when the legend item belonging to the colorAxis is clicked.
* One parameter, `event`, is passed to the function.
*
* @type {Function}
* @product highcharts highstock highmaps
* @apioption colorAxis.events.legendItemClick
*/
/**
* Whether to display the colorAxis in the legend.
*
* @sample highcharts/coloraxis/hidden-coloraxis-with-3d-chart/
* Hidden color axis with 3d chart
*
* @see [heatmap.showInLegend](#series.heatmap.showInLegend)
*
* @since 4.2.7
* @product highcharts highstock highmaps
*/
showInLegend: true
};
/* *
*
* Default Export
*
* */
return colorAxisDefaults;
});
_registerModule(_modules, 'Core/Axis/Color/ColorAxis.js', [_modules['Core/Axis/Axis.js'], _modules['Core/Color/Color.js'], _modules['Core/Axis/Color/ColorAxisComposition.js'], _modules['Core/Axis/Color/ColorAxisDefaults.js'], _modules['Core/Globals.js'], _modules['Core/Legend/LegendSymbol.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (Axis, Color, ColorAxisComposition, ColorAxisDefaults, H, LegendSymbol, SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var color = Color.parse;
var noop = H.noop;
var Series = SeriesRegistry.series;
var extend = U.extend,
isNumber = U.isNumber,
merge = U.merge,
pick = U.pick;
/* *
*
* Class
*
* */
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The ColorAxis object for inclusion in gradient legends.
*
* @class
* @name Highcharts.ColorAxis
* @augments Highcharts.Axis
*
* @param {Highcharts.Chart} chart
* The related chart of the color axis.
*
* @param {Highcharts.ColorAxisOptions} userOptions
* The color axis options for initialization.
*/
var ColorAxis = /** @class */ (function (_super) {
__extends(ColorAxis, _super);
/* *
*
* Constructors
*
* */
/**
* @private
*/
function ColorAxis(chart, userOptions) {
var _this = _super.call(this,
chart,
userOptions) || this;
// Prevents unnecessary padding with `hc-more`
_this.beforePadding = false;
_this.chart = void 0;
_this.coll = 'colorAxis';
_this.dataClasses = void 0;
_this.legendItem = void 0;
_this.legendItems = void 0;
_this.name = ''; // Prevents 'undefined' in legend in IE8
_this.options = void 0;
_this.stops = void 0;
_this.visible = true;
_this.init(chart, userOptions);
return _this;
}
/* *
*
* Static Functions
*
* */
ColorAxis.compose = function (ChartClass, FxClass, LegendClass, SeriesClass) {
ColorAxisComposition.compose(ColorAxis, ChartClass, FxClass, LegendClass, SeriesClass);
};
/* *
*
* Functions
*
* */
/**
* Initializes the color axis.
*
* @function Highcharts.ColorAxis#init
*
* @param {Highcharts.Chart} chart
* The related chart of the color axis.
*
* @param {Highcharts.ColorAxisOptions} userOptions
* The color axis options for initialization.
*/
ColorAxis.prototype.init = function (chart, userOptions) {
var axis = this;
var legend = chart.options.legend || {},
horiz = userOptions.layout ?
userOptions.layout !== 'vertical' :
legend.layout !== 'vertical',
visible = userOptions.visible;
var options = merge(ColorAxis.defaultColorAxisOptions,
userOptions, {
showEmpty: false,
title: null,
visible: legend.enabled && visible !== false
});
axis.coll = 'colorAxis';
axis.side = userOptions.side || horiz ? 2 : 1;
axis.reversed = userOptions.reversed || !horiz;
axis.opposite = !horiz;
_super.prototype.init.call(this, chart, options);
// #16053: Restore the actual userOptions.visible so the color axis
// doesnt stay hidden forever when hiding and showing legend
axis.userOptions.visible = visible;
// Base init() pushes it to the xAxis array, now pop it again
// chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop();
// Prepare data classes
if (userOptions.dataClasses) {
axis.initDataClasses(userOptions);
}
axis.initStops();
// Override original axis properties
axis.horiz = horiz;
axis.zoomEnabled = false;
};
/**
* @private
*/
ColorAxis.prototype.initDataClasses = function (userOptions) {
var axis = this,
chart = axis.chart,
options = axis.options,
len = userOptions.dataClasses.length;
var dataClasses,
colorCounter = 0,
colorCount = chart.options.chart.colorCount;
axis.dataClasses = dataClasses = [];
axis.legendItems = [];
(userOptions.dataClasses || []).forEach(function (dataClass, i) {
var colors;
dataClass = merge(dataClass);
dataClasses.push(dataClass);
if (!chart.styledMode && dataClass.color) {
return;
}
if (options.dataClassColor === 'category') {
if (!chart.styledMode) {
colors = chart.options.colors;
colorCount = colors.length;
dataClass.color = colors[colorCounter];
}
dataClass.colorIndex = colorCounter;
// increase and loop back to zero
colorCounter++;
if (colorCounter === colorCount) {
colorCounter = 0;
}
}
else {
dataClass.color = color(options.minColor).tweenTo(color(options.maxColor), len < 2 ? 0.5 : i / (len - 1) // #3219
);
}
});
};
/**
* Returns true if the series has points at all.
*
* @function Highcharts.ColorAxis#hasData
*
* @return {boolean}
* True, if the series has points, otherwise false.
*/
ColorAxis.prototype.hasData = function () {
return !!(this.tickPositions || []).length;
};
/**
* Override so that ticks are not added in data class axes (#6914)
* @private
*/
ColorAxis.prototype.setTickPositions = function () {
if (!this.dataClasses) {
return _super.prototype.setTickPositions.call(this);
}
};
/**
* @private
*/
ColorAxis.prototype.initStops = function () {
var axis = this;
axis.stops = axis.options.stops || [
[0, axis.options.minColor],
[1, axis.options.maxColor]
];
axis.stops.forEach(function (stop) {
stop.color = color(stop[1]);
});
};
/**
* Extend the setOptions method to process extreme colors and color stops.
* @private
*/
ColorAxis.prototype.setOptions = function (userOptions) {
var axis = this;
_super.prototype.setOptions.call(this, userOptions);
axis.options.crosshair = axis.options.marker;
};
/**
* @private
*/
ColorAxis.prototype.setAxisSize = function () {
var axis = this;
var symbol = axis.legendSymbol;
var chart = axis.chart;
var legendOptions = chart.options.legend || {};
var x,
y,
width,
height;
if (symbol) {
this.left = x = symbol.attr('x');
this.top = y = symbol.attr('y');
this.width = width = symbol.attr('width');
this.height = height = symbol.attr('height');
this.right = chart.chartWidth - x - width;
this.bottom = chart.chartHeight - y - height;
this.len = this.horiz ? width : height;
this.pos = this.horiz ? x : y;
}
else {
// Fake length for disabled legend to avoid tick issues
// and such (#5205)
this.len = (this.horiz ?
legendOptions.symbolWidth :
legendOptions.symbolHeight) || ColorAxis.defaultLegendLength;
}
};
/**
* @private
*/
ColorAxis.prototype.normalizedValue = function (value) {
var axis = this;
if (axis.logarithmic) {
value = axis.logarithmic.log2lin(value);
}
return 1 - ((axis.max - value) /
((axis.max - axis.min) || 1));
};
/**
* Translate from a value to a color.
* @private
*/
ColorAxis.prototype.toColor = function (value, point) {
var axis = this;
var dataClasses = axis.dataClasses;
var stops = axis.stops;
var pos,
from,
to,
color,
dataClass,
i;
if (dataClasses) {
i = dataClasses.length;
while (i--) {
dataClass = dataClasses[i];
from = dataClass.from;
to = dataClass.to;
if ((typeof from === 'undefined' || value >= from) &&
(typeof to === 'undefined' || value <= to)) {
color = dataClass.color;
if (point) {
point.dataClass = i;
point.colorIndex = dataClass.colorIndex;
}
break;
}
}
}
else {
pos = axis.normalizedValue(value);
i = stops.length;
while (i--) {
if (pos > stops[i][0]) {
break;
}
}
from = stops[i] || stops[i + 1];
to = stops[i + 1] || from;
// The position within the gradient
pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1);
color = from.color.tweenTo(to.color, pos);
}
return color;
};
/**
* Override the getOffset method to add the whole axis groups inside the
* legend.
* @private
*/
ColorAxis.prototype.getOffset = function () {
var axis = this;
var group = axis.legendGroup;
var sideOffset = axis.chart.axisOffset[axis.side];
if (group) {
// Hook for the getOffset method to add groups to this parent
// group
axis.axisParent = group;
// Call the base
_super.prototype.getOffset.call(this);
// First time only
if (!axis.added) {
axis.added = true;
axis.labelLeft = 0;
axis.labelRight = axis.width;
}
// Reset it to avoid color axis reserving space
axis.chart.axisOffset[axis.side] = sideOffset;
}
};
/**
* Create the color gradient.
* @private
*/
ColorAxis.prototype.setLegendColor = function () {
var axis = this;
var horiz = axis.horiz;
var reversed = axis.reversed;
var one = reversed ? 1 : 0;
var zero = reversed ? 0 : 1;
var grad = horiz ? [one, 0,
zero, 0] : [0,
zero, 0,
one]; // #3190
axis.legendColor = {
linearGradient: {
x1: grad[0],
y1: grad[1],
x2: grad[2],
y2: grad[3]
},
stops: axis.stops
};
};
/**
* The color axis appears inside the legend and has its own legend symbol.
* @private
*/
ColorAxis.prototype.drawLegendSymbol = function (legend, item) {
var axis = this;
var padding = legend.padding;
var legendOptions = legend.options;
var horiz = axis.horiz;
var width = pick(legendOptions.symbolWidth,
horiz ? ColorAxis.defaultLegendLength : 12);
var height = pick(legendOptions.symbolHeight,
horiz ? 12 : ColorAxis.defaultLegendLength);
var labelPadding = pick(legendOptions.labelPadding,
horiz ? 16 : 30);
var itemDistance = pick(legendOptions.itemDistance, 10);
this.setLegendColor();
// Create the gradient
item.legendSymbol = this.chart.renderer.rect(0, legend.baseline - 11, width, height).attr({
zIndex: 1
}).add(item.legendGroup);
// Set how much space this legend item takes up
axis.legendItemWidth = (width +
padding +
(horiz ? itemDistance : labelPadding));
axis.legendItemHeight = height + padding + (horiz ? labelPadding : 0);
};
/**
* Fool the legend.
* @private
*/
ColorAxis.prototype.setState = function (state) {
this.series.forEach(function (series) {
series.setState(state);
});
};
/**
* @private
*/
ColorAxis.prototype.setVisible = function () {
};
/**
* @private
*/
ColorAxis.prototype.getSeriesExtremes = function () {
var axis = this;
var series = axis.series;
var colorValArray,
colorKey,
colorValIndex,
pointArrayMap,
calculatedExtremes,
cSeries,
i = series.length,
yData,
j;
this.dataMin = Infinity;
this.dataMax = -Infinity;
while (i--) { // x, y, value, other
cSeries = series[i];
colorKey = cSeries.colorKey = pick(cSeries.options.colorKey, cSeries.colorKey, cSeries.pointValKey, cSeries.zoneAxis, 'y');
pointArrayMap = cSeries.pointArrayMap;
calculatedExtremes = cSeries[colorKey + 'Min'] &&
cSeries[colorKey + 'Max'];
if (cSeries[colorKey + 'Data']) {
colorValArray = cSeries[colorKey + 'Data'];
}
else {
if (!pointArrayMap) {
colorValArray = cSeries.yData;
}
else {
colorValArray = [];
colorValIndex = pointArrayMap.indexOf(colorKey);
yData = cSeries.yData;
if (colorValIndex >= 0 && yData) {
for (j = 0; j < yData.length; j++) {
colorValArray.push(pick(yData[j][colorValIndex], yData[j]));
}
}
}
}
// If color key extremes are already calculated, use them.
if (calculatedExtremes) {
cSeries.minColorValue = cSeries[colorKey + 'Min'];
cSeries.maxColorValue = cSeries[colorKey + 'Max'];
}
else {
var cExtremes = Series.prototype.getExtremes.call(cSeries,
colorValArray);
cSeries.minColorValue = cExtremes.dataMin;
cSeries.maxColorValue = cExtremes.dataMax;
}
if (typeof cSeries.minColorValue !== 'undefined') {
this.dataMin =
Math.min(this.dataMin, cSeries.minColorValue);
this.dataMax =
Math.max(this.dataMax, cSeries.maxColorValue);
}
if (!calculatedExtremes) {
Series.prototype.applyExtremes.call(cSeries);
}
}
};
/**
* Internal function to draw a crosshair.
*
* @function Highcharts.ColorAxis#drawCrosshair
*
* @param {Highcharts.PointerEventObject} [e]
* The event arguments from the modified pointer event, extended with
* `chartX` and `chartY`
*
* @param {Highcharts.Point} [point]
* The Point object if the crosshair snaps to points.
*
* @emits Highcharts.ColorAxis#event:afterDrawCrosshair
* @emits Highcharts.ColorAxis#event:drawCrosshair
*/
ColorAxis.prototype.drawCrosshair = function (e, point) {
var axis = this;
var plotX = point && point.plotX;
var plotY = point && point.plotY;
var axisPos = axis.pos;
var axisLen = axis.len;
var crossPos;
if (point) {
crossPos = axis.toPixels(point.getNestedProperty(point.series.colorKey));
if (crossPos < axisPos) {
crossPos = axisPos - 2;
}
else if (crossPos > axisPos + axisLen) {
crossPos = axisPos + axisLen + 2;
}
point.plotX = crossPos;
point.plotY = axis.len - crossPos;
_super.prototype.drawCrosshair.call(this, e, point);
point.plotX = plotX;
point.plotY = plotY;
if (axis.cross &&
!axis.cross.addedToColorAxis &&
axis.legendGroup) {
axis.cross
.addClass('highcharts-coloraxis-marker')
.add(axis.legendGroup);
axis.cross.addedToColorAxis = true;
if (!axis.chart.styledMode &&
typeof axis.crosshair === 'object') {
axis.cross.attr({
fill: axis.crosshair.color
});
}
}
}
};
/**
* @private
*/
ColorAxis.prototype.getPlotLinePath = function (options) {
var axis = this,
left = axis.left,
pos = options.translatedValue,
top = axis.top;
// crosshairs only
return isNumber(pos) ? // pos can be 0 (#3969)
(axis.horiz ? [
['M', pos - 4, top - 6],
['L', pos + 4, top - 6],
['L', pos, top],
['Z']
] : [
['M', left, pos],
['L', left - 6, pos + 6],
['L', left - 6, pos - 6],
['Z']
]) :
_super.prototype.getPlotLinePath.call(this, options);
};
/**
* Updates a color axis instance with a new set of options. The options are
* merged with the existing options, so only new or altered options need to
* be specified.
*
* @function Highcharts.ColorAxis#update
*
* @param {Highcharts.ColorAxisOptions} newOptions
* The new options that will be merged in with existing options on the color
* axis.
*
* @param {boolean} [redraw]
* Whether to redraw the chart after the color axis is altered. If doing
* more operations on the chart, it is a good idea to set redraw to `false`
* and call {@link Highcharts.Chart#redraw} after.
*/
ColorAxis.prototype.update = function (newOptions, redraw) {
var axis = this,
chart = axis.chart,
legend = chart.legend;
this.series.forEach(function (series) {
// Needed for Axis.update when choropleth colors change
series.isDirtyData = true;
});
// When updating data classes, destroy old items and make sure new
// ones are created (#3207)
if (newOptions.dataClasses && legend.allItems || axis.dataClasses) {
axis.destroyItems();
}
_super.prototype.update.call(this, newOptions, redraw);
if (axis.legendItem) {
axis.setLegendColor();
legend.colorizeItem(this, true);
}
};
/**
* Destroy color axis legend items.
* @private
*/
ColorAxis.prototype.destroyItems = function () {
var axis = this;
var chart = axis.chart;
if (axis.legendItem) {
chart.legend.destroyItem(axis);
}
else if (axis.legendItems) {
axis.legendItems.forEach(function (item) {
chart.legend.destroyItem(item);
});
}
chart.isDirtyLegend = true;
};
// Removing the whole axis (#14283)
ColorAxis.prototype.destroy = function () {
this.chart.isDirtyLegend = true;
this.destroyItems();
_super.prototype.destroy.apply(this, [].slice.call(arguments));
};
/**
* Removes the color axis and the related legend item.
*
* @function Highcharts.ColorAxis#remove
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart following the remove.
*/
ColorAxis.prototype.remove = function (redraw) {
this.destroyItems();
_super.prototype.remove.call(this, redraw);
};
/**
* Get the legend item symbols for data classes.
* @private
*/
ColorAxis.prototype.getDataClassLegendSymbols = function () {
var axis = this;
var chart = axis.chart;
var legendItems = axis.legendItems;
var legendOptions = chart.options.legend;
var valueDecimals = legendOptions.valueDecimals;
var valueSuffix = legendOptions.valueSuffix || '';
var name;
if (!legendItems.length) {
axis.dataClasses.forEach(function (dataClass, i) {
var from = dataClass.from,
to = dataClass.to,
numberFormatter = chart.numberFormatter;
var vis = true;
// Assemble the default name. This can be overridden
// by legend.options.labelFormatter
name = '';
if (typeof from === 'undefined') {
name = '< ';
}
else if (typeof to === 'undefined') {
name = '> ';
}
if (typeof from !== 'undefined') {
name += numberFormatter(from, valueDecimals) + valueSuffix;
}
if (typeof from !== 'undefined' && typeof to !== 'undefined') {
name += ' - ';
}
if (typeof to !== 'undefined') {
name += numberFormatter(to, valueDecimals) + valueSuffix;
}
// Add a mock object to the legend items
legendItems.push(extend({
chart: chart,
name: name,
options: {},
drawLegendSymbol: LegendSymbol.drawRectangle,
visible: true,
setState: noop,
isDataClass: true,
setVisible: function () {
vis = axis.visible = !vis;
axis.series.forEach(function (series) {
series.points.forEach(function (point) {
if (point.dataClass === i) {
point.setVisible(vis);
}
});
});
chart.legend.colorizeItem(this, vis);
}
}, dataClass));
});
}
return legendItems;
};
/* *
*
* Static Properties
*
* */
ColorAxis.defaultColorAxisOptions = ColorAxisDefaults;
ColorAxis.defaultLegendLength = 200;
/**
* @private
*/
ColorAxis.keepProps = [
'legendGroup',
'legendItemHeight',
'legendItemWidth',
'legendItem',
'legendSymbol'
];
return ColorAxis;
}(Axis));
/* *
*
* Registry
*
* */
// Properties to preserve after destroy, for Axis.update (#5881, #6025).
Array.prototype.push.apply(Axis.keepProps, ColorAxis.keepProps);
/* *
*
* Default Export
*
* */
/* *
*
* API Declarations
*
* */
/**
* Color axis types
*
* @typedef {"linear"|"logarithmic"} Highcharts.ColorAxisTypeValue
*/
''; // detach doclet above
return ColorAxis;
});
_registerModule(_modules, 'Maps/MapNavigationOptionsDefault.js', [_modules['Core/DefaultOptions.js'], _modules['Core/Utilities.js']], function (D, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var extend = U.extend;
/* *
*
* Constants
*
* */
/**
* The `mapNavigation` option handles buttons for navigation in addition to
* mousewheel and doubleclick handlers for map zooming.
*
* @product highmaps
* @optionparent mapNavigation
*/
var defaultOptions = {
/**
* General options for the map navigation buttons. Individual options
* can be given from the [mapNavigation.buttons](#mapNavigation.buttons)
* option set.
*
* @sample {highmaps} maps/mapnavigation/button-theme/
* Theming the navigation buttons
*/
buttonOptions: {
/**
* What box to align the buttons to. Possible values are `plotBox`
* and `spacingBox`.
*
* @type {Highcharts.ButtonRelativeToValue}
*/
alignTo: 'plotBox',
/**
* The alignment of the navigation buttons.
*
* @type {Highcharts.AlignValue}
*/
align: 'left',
/**
* The vertical alignment of the buttons. Individual alignment can
* be adjusted by each button's `y` offset.
*
* @type {Highcharts.VerticalAlignValue}
*/
verticalAlign: 'top',
/**
* The X offset of the buttons relative to its `align` setting.
*/
x: 0,
/**
* The width of the map navigation buttons.
*/
width: 18,
/**
* The pixel height of the map navigation buttons.
*/
height: 18,
/**
* Padding for the navigation buttons.
*
* @since 5.0.0
*/
padding: 5,
/**
* Text styles for the map navigation buttons.
*
* @type {Highcharts.CSSObject}
* @default {"fontSize": "15px", "fontWeight": "bold"}
*/
style: {
/** @ignore */
fontSize: '15px',
/** @ignore */
fontWeight: 'bold'
},
/**
* A configuration object for the button theme. The object accepts
* SVG properties like `stroke-width`, `stroke` and `fill`. Tri-state
* button styles are supported by the `states.hover` and `states.select`
* objects.
*
* @sample {highmaps} maps/mapnavigation/button-theme/
* Themed navigation buttons
*
* @type {Highcharts.SVGAttributes}
* @default {"stroke-width": 1, "text-align": "center"}
*/
theme: {
/** @ignore */
'stroke-width': 1,
/** @ignore */
'text-align': 'center'
}
},
/**
* The individual buttons for the map navigation. This usually includes
* the zoom in and zoom out buttons. Properties for each button is
* inherited from
* [mapNavigation.buttonOptions](#mapNavigation.buttonOptions), while
* individual options can be overridden. But default, the `onclick`, `text`
* and `y` options are individual.
*/
buttons: {
/**
* Options for the zoom in button. Properties for the zoom in and zoom
* out buttons are inherited from
* [mapNavigation.buttonOptions](#mapNavigation.buttonOptions), while
* individual options can be overridden. By default, the `onclick`,
* `text` and `y` options are individual.
*
* @extends mapNavigation.buttonOptions
*/
zoomIn: {
// eslint-disable-next-line valid-jsdoc
/**
* Click handler for the button.
*
* @type {Function}
* @default function () { this.mapZoom(0.5); }
*/
onclick: function () {
this.mapZoom(0.5);
},
/**
* The text for the button. The tooltip (title) is a language option
* given by [lang.zoomIn](#lang.zoomIn).
*/
text: '+',
/**
* The position of the zoomIn button relative to the vertical
* alignment.
*/
y: 0
},
/**
* Options for the zoom out button. Properties for the zoom in and
* zoom out buttons are inherited from
* [mapNavigation.buttonOptions](#mapNavigation.buttonOptions), while
* individual options can be overridden. By default, the `onclick`,
* `text` and `y` options are individual.
*
* @extends mapNavigation.buttonOptions
*/
zoomOut: {
// eslint-disable-next-line valid-jsdoc
/**
* Click handler for the button.
*
* @type {Function}
* @default function () { this.mapZoom(2); }
*/
onclick: function () {
this.mapZoom(2);
},
/**
* The text for the button. The tooltip (title) is a language option
* given by [lang.zoomOut](#lang.zoomIn).
*/
text: '-',
/**
* The position of the zoomOut button relative to the vertical
* alignment.
*/
y: 28
}
},
/**
* Whether to enable navigation buttons. By default it inherits the
* [enabled](#mapNavigation.enabled) setting.
*
* @type {boolean}
* @apioption mapNavigation.enableButtons
*/
/**
* Whether to enable map navigation. The default is not to enable
* navigation, as many choropleth maps are simple and don't need it.
* Additionally, when touch zoom and mousewheel zoom is enabled, it breaks
* the default behaviour of these interactions in the website, and the
* implementer should be aware of this.
*
* Individual interactions can be enabled separately, namely buttons,
* multitouch zoom, double click zoom, double click zoom to element and
* mousewheel zoom.
*
* @type {boolean}
* @default false
* @apioption mapNavigation.enabled
*/
/**
* Enables zooming in on an area on double clicking in the map. By default
* it inherits the [enabled](#mapNavigation.enabled) setting.
*
* @type {boolean}
* @apioption mapNavigation.enableDoubleClickZoom
*/
/**
* Whether to zoom in on an area when that area is double clicked.
*
* @sample {highmaps} maps/mapnavigation/doubleclickzoomto/
* Enable double click zoom to
*
* @type {boolean}
* @default false
* @apioption mapNavigation.enableDoubleClickZoomTo
*/
/**
* Enables zooming by mouse wheel. By default it inherits the [enabled](
* #mapNavigation.enabled) setting.
*
* @type {boolean}
* @apioption mapNavigation.enableMouseWheelZoom
*/
/**
* Whether to enable multitouch zooming. Note that if the chart covers the
* viewport, this prevents the user from using multitouch and touchdrag on
* the web page, so you should make sure the user is not trapped inside the
* chart. By default it inherits the [enabled](#mapNavigation.enabled)
* setting.
*
* @type {boolean}
* @apioption mapNavigation.enableTouchZoom
*/
/**
* Sensitivity of mouse wheel or trackpad scrolling. 1 is no sensitivity,
* while with 2, one mousewheel delta will zoom in 50%.
*
* @since 4.2.4
*/
mouseWheelSensitivity: 1.1
// enabled: false,
// enableButtons: null, // inherit from enabled
// enableTouchZoom: null, // inherit from enabled
// enableDoubleClickZoom: null, // inherit from enabled
// enableDoubleClickZoomTo: false
// enableMouseWheelZoom: null, // inherit from enabled
};
/* *
*
* Composition
*
* */
// Add language
extend(D.defaultOptions.lang, {
zoomIn: 'Zoom in',
zoomOut: 'Zoom out'
});
// Set the default map navigation options
D.defaultOptions.mapNavigation = defaultOptions;
/* *
*
* Default Export
*
* */
return defaultOptions;
});
_registerModule(_modules, 'Maps/MapNavigation.js', [_modules['Core/Chart/Chart.js'], _modules['Core/Globals.js'], _modules['Core/Utilities.js']], function (Chart, H, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var doc = H.doc;
var addEvent = U.addEvent,
extend = U.extend,
isNumber = U.isNumber,
merge = U.merge,
objectEach = U.objectEach,
pick = U.pick;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function stopEvent(e) {
if (e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.cancelBubble = true;
}
}
/**
* The MapNavigation handles buttons for navigation in addition to mousewheel
* and doubleclick handlers for chart zooming.
*
* @private
* @class
* @name MapNavigation
*
* @param {Highcharts.Chart} chart
* The Chart instance.
*/
function MapNavigation(chart) {
this.init(chart);
}
/**
* Initialize function.
*
* @function MapNavigation#init
*
* @param {Highcharts.Chart} chart
* The Chart instance.
*
* @return {void}
*/
MapNavigation.prototype.init = function (chart) {
this.chart = chart;
chart.mapNavButtons = [];
};
/**
* Update the map navigation with new options. Calling this is the same as
* calling `chart.update({ mapNavigation: {} })`.
*
* @function MapNavigation#update
*
* @param {Highcharts.MapNavigationOptions} [options]
* New options for the map navigation.
*
* @return {void}
*/
MapNavigation.prototype.update = function (options) {
var chart = this.chart,
o = chart.options.mapNavigation,
attr,
states,
hoverStates,
selectStates,
outerHandler = function (e) {
this.handler.call(chart,
e);
stopEvent(e); // Stop default click event (#4444)
}, mapNavButtons = chart.mapNavButtons;
// Merge in new options in case of update, and register back to chart
// options.
if (options) {
o = chart.options.mapNavigation =
merge(chart.options.mapNavigation, options);
}
// Destroy buttons in case of dynamic update
while (mapNavButtons.length) {
mapNavButtons.pop().destroy();
}
if (pick(o.enableButtons, o.enabled) && !chart.renderer.forExport) {
objectEach(o.buttons, function (buttonOptions, n) {
buttonOptions = merge(o.buttonOptions, buttonOptions);
// Presentational
if (!chart.styledMode && buttonOptions.theme) {
attr = buttonOptions.theme;
attr.style = merge(buttonOptions.theme.style, buttonOptions.style // #3203
);
states = attr.states;
hoverStates = states && states.hover;
selectStates = states && states.select;
delete attr.states;
}
var button = chart.renderer
.button(buttonOptions.text || '', 0, 0, outerHandler, attr, hoverStates, selectStates, void 0, n === 'zoomIn' ? 'topbutton' : 'bottombutton')
.addClass('highcharts-map-navigation highcharts-' + {
zoomIn: 'zoom-in',
zoomOut: 'zoom-out'
}[n])
.attr({
width: buttonOptions.width,
height: buttonOptions.height,
title: chart.options.lang[n],
padding: buttonOptions.padding,
zIndex: 5
})
.add();
button.handler = buttonOptions.onclick;
// Stop double click event (#4444)
addEvent(button.element, 'dblclick', stopEvent);
mapNavButtons.push(button);
extend(buttonOptions, {
width: button.width,
height: 2 * button.height
});
if (!chart.hasLoaded) {
// Align it after the plotBox is known (#12776)
var unbind_1 = addEvent(chart, 'load',
function () {
// #15406: Make sure button hasnt been destroyed
if (button.element) {
button.align(buttonOptions,
false,
buttonOptions.alignTo);
}
unbind_1();
});
}
else {
button.align(buttonOptions, false, buttonOptions.alignTo);
}
});
}
this.updateEvents(o);
};
/**
* Update events, called internally from the update function. Add new event
* handlers, or unbinds events if disabled.
*
* @function MapNavigation#updateEvents
*
* @param {Highcharts.MapNavigationOptions} options
* Options for map navigation.
*
* @return {void}
*/
MapNavigation.prototype.updateEvents = function (options) {
var chart = this.chart;
// Add the double click event
if (pick(options.enableDoubleClickZoom, options.enabled) ||
options.enableDoubleClickZoomTo) {
this.unbindDblClick = this.unbindDblClick || addEvent(chart.container, 'dblclick', function (e) {
chart.pointer.onContainerDblClick(e);
});
}
else if (this.unbindDblClick) {
// Unbind and set unbinder to undefined
this.unbindDblClick = this.unbindDblClick();
}
// Add the mousewheel event
if (pick(options.enableMouseWheelZoom, options.enabled)) {
this.unbindMouseWheel = this.unbindMouseWheel || addEvent(chart.container, doc.onwheel !== void 0 ? 'wheel' : // Newer Firefox
doc.onmousewheel !== void 0 ? 'mousewheel' :
'DOMMouseScroll', function (e) {
// Prevent scrolling when the pointer is over the element with
// that class, for example anotation popup #12100.
if (!chart.pointer.inClass(e.target, 'highcharts-no-mousewheel')) {
chart.pointer.onContainerMouseWheel(e);
// Issue #5011, returning false from non-jQuery event does
// not prevent default
stopEvent(e);
}
return false;
});
}
else if (this.unbindMouseWheel) {
// Unbind and set unbinder to undefined
this.unbindMouseWheel = this.unbindMouseWheel();
}
};
// Add events to the Chart object itself
extend(Chart.prototype, /** @lends Chart.prototype */ {
/**
* Fit an inner box to an outer. If the inner box overflows left or right,
* align it to the sides of the outer. If it overflows both sides, fit it
* within the outer. This is a pattern that occurs more places in
* Highcharts, perhaps it should be elevated to a common utility function.
*
* @ignore
* @function Highcharts.Chart#fitToBox
*
* @param {Highcharts.BBoxObject} inner
*
* @param {Highcharts.BBoxObject} outer
*
* @return {Highcharts.BBoxObject}
* The inner box
*/
fitToBox: function (inner, outer) {
[['x', 'width'], ['y', 'height']].forEach(function (dim) {
var pos = dim[0],
size = dim[1];
if (inner[pos] + inner[size] >
outer[pos] + outer[size]) { // right
// the general size is greater, fit fully to outer
if (inner[size] > outer[size]) {
inner[size] = outer[size];
inner[pos] = outer[pos];
}
else { // align right
inner[pos] = outer[pos] +
outer[size] - inner[size];
}
}
if (inner[size] > outer[size]) {
inner[size] = outer[size];
}
if (inner[pos] < outer[pos]) {
inner[pos] = outer[pos];
}
});
return inner;
},
/**
* Highcharts Maps only. Zoom in or out of the map. See also
* {@link Point#zoomTo}. See {@link Chart#fromLatLonToPoint} for how to get
* the `centerX` and `centerY` parameters for a geographic location.
*
* Deprecated as of v9.3 in favor of [MapView.zoomBy](https://api.highcharts.com/class-reference/Highcharts.MapView#zoomBy).
*
* @function Highcharts.Chart#mapZoom
*
* @param {number} [howMuch]
* How much to zoom the map. Values less than 1 zooms in. 0.5 zooms
* in to half the current view. 2 zooms to twice the current view. If
* omitted, the zoom is reset.
*
* @param {number} [xProjected]
* The projected x position to keep stationary when zooming, if
* available space.
*
* @param {number} [yProjected]
* The projected y position to keep stationary when zooming, if
* available space.
*
* @param {number} [chartX]
* Keep this chart position stationary if possible. This is used for
* example in mousewheel events, where the area under the mouse
* should be fixed as we zoom in.
*
* @param {number} [chartY]
* Keep this chart position stationary if possible.
*
* @deprecated
*/
mapZoom: function (howMuch, xProjected, yProjected, chartX, chartY) {
if (this.mapView) {
if (isNumber(howMuch)) {
// Compliance, mapView.zoomBy uses different values
howMuch = Math.log(howMuch) / Math.log(0.5);
}
this.mapView.zoomBy(howMuch, isNumber(xProjected) && isNumber(yProjected) ?
this.mapView.projection.inverse([xProjected, yProjected]) :
void 0, isNumber(chartX) && isNumber(chartY) ?
[chartX, chartY] :
void 0);
}
}
});
// Extend the Chart.render method to add zooming and panning
addEvent(Chart, 'beforeRender', function () {
// Render the plus and minus buttons. Doing this before the shapes makes
// getBBox much quicker, at least in Chrome.
this.mapNavigation = new MapNavigation(this);
this.mapNavigation.update();
});
H.MapNavigation = MapNavigation;
});
_registerModule(_modules, 'Maps/MapPointer.js', [_modules['Core/Pointer.js'], _modules['Core/Utilities.js']], function (Pointer, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var defined = U.defined,
extend = U.extend,
pick = U.pick,
wrap = U.wrap;
/* eslint-disable no-invalid-this */
var totalWheelDelta = 0;
var totalWheelDeltaTimer;
// Extend the Pointer
extend(Pointer.prototype, {
// The event handler for the doubleclick event
onContainerDblClick: function (e) {
var chart = this.chart;
e = this.normalize(e);
if (chart.options.mapNavigation.enableDoubleClickZoomTo) {
if (chart.pointer.inClass(e.target, 'highcharts-tracker') &&
chart.hoverPoint) {
chart.hoverPoint.zoomTo();
}
}
else if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
chart.mapZoom(0.5, void 0, void 0, e.chartX, e.chartY);
}
},
// The event handler for the mouse scroll event
onContainerMouseWheel: function (e) {
var chart = this.chart;
e = this.normalize(e);
// Firefox uses e.deltaY or e.detail, WebKit and IE uses wheelDelta
// try wheelDelta first #15656
var delta = (defined(e.wheelDelta) && -e.wheelDelta / 120) ||
e.deltaY || e.detail;
// Wheel zooming on trackpads have different behaviours in Firefox vs
// WebKit. In Firefox the delta increments in steps by 1, so it is not
// distinguishable from true mouse wheel. Therefore we use this timer
// to avoid trackpad zooming going too fast and out of control. In
// WebKit however, the delta is < 1, so we simply disable animation in
// the `chart.mapZoom` call below.
if (Math.abs(delta) >= 1) {
totalWheelDelta += Math.abs(delta);
if (totalWheelDeltaTimer) {
clearTimeout(totalWheelDeltaTimer);
}
totalWheelDeltaTimer = setTimeout(function () {
totalWheelDelta = 0;
}, 50);
}
if (totalWheelDelta < 10 && chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && chart.mapView) {
chart.mapView.zoomBy((chart.options.mapNavigation.mouseWheelSensitivity -
1) * -delta, void 0, [e.chartX, e.chartY],
// Delta less than 1 indicates stepless/trackpad zooming, avoid
// animation delaying the zoom
Math.abs(delta) < 1 ? false : void 0);
}
}
});
// The pinchType is inferred from mapNavigation options.
wrap(Pointer.prototype, 'zoomOption', function (proceed) {
var mapNavigation = this.chart.options.mapNavigation;
// Pinch status
if (pick(mapNavigation.enableTouchZoom, mapNavigation.enabled)) {
this.chart.options.chart.pinchType = 'xy';
}
proceed.apply(this, [].slice.call(arguments, 1));
});
// Extend the pinchTranslate method to preserve fixed ratio when zooming
wrap(Pointer.prototype, 'pinchTranslate', function (proceed, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
var xBigger;
proceed.call(this, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
// Keep ratio
if (this.chart.options.chart.type === 'map' && this.hasZoom) {
xBigger = transform.scaleX > transform.scaleY;
this.pinchTranslateDirection(!xBigger, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, xBigger ? transform.scaleX : transform.scaleY);
}
});
});
_registerModule(_modules, 'Series/ColorMapMixin.js', [_modules['Core/Globals.js'], _modules['Core/Series/Point.js'], _modules['Core/Utilities.js']], function (H, Point, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
// @todo cleanup & reduction - consider composition
var noop = H.noop,
seriesTypes = H.seriesTypes;
var defined = U.defined,
addEvent = U.addEvent;
// Move points to the top of the z-index order when hovered
addEvent(Point, 'afterSetState', function (e) {
var point = this;
if (point.moveToTopOnHover && point.graphic) {
point.graphic.attr({
zIndex: e && e.state === 'hover' ? 1 : 0
});
}
});
/**
* Mixin for maps and heatmaps
*
* @private
* @mixin Highcharts.colorMapPointMixin
*/
var PointMixin = {
dataLabelOnNull: true,
moveToTopOnHover: true,
/* eslint-disable valid-jsdoc */
/**
* Color points have a value option that determines whether or not it is
* a null point
* @private
*/
isValid: function () {
// undefined is allowed
return (this.value !== null &&
this.value !== Infinity &&
this.value !== -Infinity);
}
/* eslint-enable valid-jsdoc */
};
/**
* @private
* @mixin Highcharts.colorMapSeriesMixin
*/
var SeriesMixin = {
pointArrayMap: ['value'],
axisTypes: ['xAxis', 'yAxis', 'colorAxis'],
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
getSymbol: noop,
parallelArrays: ['x', 'y', 'value'],
colorKey: 'value',
pointAttribs: seriesTypes.column.prototype.pointAttribs,
/* eslint-disable valid-jsdoc */
/**
* Get the color attibutes to apply on the graphic
* @private
* @function Highcharts.colorMapSeriesMixin.colorAttribs
* @param {Highcharts.Point} point
* @return {Highcharts.SVGAttributes}
* The SVG attributes
*/
colorAttribs: function (point) {
var ret = {};
if (defined(point.color) &&
(!point.state || point.state === 'normal') // #15746
) {
ret[this.colorProp || 'fill'] = point.color;
}
return ret;
}
};
var ColorMapMixin = {
PointMixin: PointMixin,
SeriesMixin: SeriesMixin
};
return ColorMapMixin;
});
_registerModule(_modules, 'Maps/MapViewOptionsDefault.js', [], function () {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
/**
* The `mapView` options control the initial view of the chart, and how
* projection is set up for raw geoJSON maps (beta as of v9.3).
*
* To set the view dynamically after chart generation, see
* [mapView.setView](/class-reference/Highcharts.MapView#setView).
*
* @since 9.3.0
* @product highmaps
* @optionparent mapView
*/
var defaultOptions = {
/**
* The center of the map in terms of longitude and latitude. For
* preprojected maps (like in Map Collection v1.x),
the units are projected
* x and y units.
*
* @default [0, 0]
* @type {Highcharts.LonLatArray}
*
* @sample {highmaps} maps/mapview/center-zoom
* Custom view of a world map
* @sample {highmaps} maps/mapview/get-view
* Report the current view of a preprojected map
*/
center: [0, 0],
/**
* Prevents the end user from zooming too far in on the map. See
* [zoom](#mapView.zoom).
*
* @type {number|undefined}
*
* @sample {highmaps} maps/mapview/maxzoom
* Prevent zooming in too far
*/
maxZoom: void 0,
/**
* The padding inside the plot area when auto fitting to the map bounds. A
* number signifies pixels,
and a percentage is relative to the plot area
* size.
*
* @sample {highmaps} maps/chart/plotbackgroundcolor-color
* Visible plot area and percentage padding
*/
padding: 0,
/**
* Beta feature in v9.3. The projection options allow applying client side
* projection to a map given in coordinates,
typically from TopoJSON or
* GeoJSON.
*
* Sub-options are:
* * `name`,
which as of v9.3 can be `EqualEarth`,
* `LambertConformalConic`,
`Miller`,
`Orthographic` or `WebMercator`.
* * `parallels`,
the standard parallels for the LambertConformalConic
* projection.
* * `rotation`,
a three-axis rotation of the globe prior to projection,
* which in practice can be used for example to render a world map with the
* Americas centered (`[90, 0]`),
or to rotate an orthographic projection.
*
* @type {Object}
* @sample {highmaps} maps/demo/topojson-projection
* Orthographic projection
*/
projection: void 0,
/**
* The zoom level of a map. Higher zoom levels means more zoomed in. An
* increase of 1 zooms in to a quarter of the viewed area (half the width
* and height). Defaults to fitting to the map bounds.
*
* In a `WebMercator` projection,
a zoom level of 0 represents
* the world in a 256x256 pixel square. This is a common concept for WMS
* tiling software.
*
* @type {number|undefined}
* @sample {highmaps} maps/mapview/center-zoom
* Custom view of a world map
* @sample {highmaps} maps/mapview/get-view
* Report the current view of a preprojected map
*/
zoom: void 0
};
/* *
*
* Default Export
*
* */
return defaultOptions;
});
_registerModule(_modules, 'Maps/Projections/LambertConformalConic.js', [], function () {
/* *
* Lambert Conformal Conic projection
* */
var sign = Math.sign ||
(function (n) { return (n === 0 ? 0 : n > 0 ? 1 : -1); }),
scale = 63.78137,
deg2rad = Math.PI / 180,
halfPI = Math.PI / 2,
eps10 = 1e-6,
tany = function (y) { return Math.tan((halfPI + y) / 2); };
var n = 0,
c = 0;
var LambertConformalConic = {
init: function (options) {
var parallels = (options.parallels || [])
.map(function (n) { return n * deg2rad; }),
lat1 = parallels[0] || 0,
lat2 = parallels[1] || lat1,
cosLat1 = Math.cos(lat1);
// Apply the global variables
n = lat1 === lat2 ?
Math.sin(lat1) :
Math.log(cosLat1 / Math.cos(lat2)) / Math.log(tany(lat2) / tany(lat1));
if (Math.abs(n) < 1e-10) {
n = (sign(n) || 1) * 1e-10;
}
c = cosLat1 * Math.pow(tany(lat1), n) / n;
},
forward: function (lonLat) {
var lon = lonLat[0] * deg2rad;
var lat = lonLat[1] * deg2rad;
if (c > 0) {
if (lat < -halfPI + eps10) {
lat = -halfPI + eps10;
}
}
else {
if (lat > halfPI - eps10) {
lat = halfPI - eps10;
}
}
var r = c / Math.pow(tany(lat),
n);
return [
r * Math.sin(n * lon) * scale,
(c - r * Math.cos(n * lon)) * scale
];
},
inverse: function (xy) {
var x = xy[0] / scale,
y = xy[1] / scale,
cy = c - y,
rho = sign(n) * Math.sqrt(x * x + cy * cy);
var l = Math.atan2(x,
Math.abs(cy)) * sign(cy);
if (cy * n < 0) {
l -= Math.PI * sign(x) * sign(cy);
}
return [
(l / n) / deg2rad,
(2 * Math.atan(Math.pow(c / rho, 1 / n)) - halfPI) / deg2rad
];
}
};
return LambertConformalConic;
});
_registerModule(_modules, 'Maps/Projections/EqualEarth.js', [], function () {
/* *
*
* Equal Earth projection, an equal-area projection designed to minimize
* distortion and remain pleasing to the eye.
*
* Invented by Bojan Šavrič, Bernhard Jenny, and Tom Patterson in 2018. It is
* inspired by the widely used Robinson projection.
*
* */
var A1 = 1.340264,
A2 = -0.081106,
A3 = 0.000893,
A4 = 0.003796,
M = Math.sqrt(3) / 2.0,
scale = 74.03120656864502;
var EqualEarth = {
forward: function (lonLat) {
var d = Math.PI / 180,
paramLat = Math.asin(M * Math.sin(lonLat[1] * d)),
paramLatSq = paramLat * paramLat,
paramLatPow6 = paramLatSq * paramLatSq * paramLatSq;
var x = lonLat[0] * d * Math.cos(paramLat) * scale / (M *
(A1 +
3 * A2 * paramLatSq +
paramLatPow6 * (7 * A3 + 9 * A4 * paramLatSq)));
var y = paramLat * scale * (A1 + A2 * paramLatSq + paramLatPow6 * (A3 + A4 * paramLatSq));
return [x, y];
},
inverse: function (xy) {
var x = xy[0] / scale,
y = xy[1] / scale,
d = 180 / Math.PI,
epsilon = 1e-9,
iterations = 12;
var paramLat = y,
paramLatSq,
paramLatPow6,
fy,
fpy,
dlat,
i;
for (i = 0; i < iterations; ++i) {
paramLatSq = paramLat * paramLat;
paramLatPow6 = paramLatSq * paramLatSq * paramLatSq;
fy = paramLat * (A1 + A2 * paramLatSq + paramLatPow6 * (A3 + A4 * paramLatSq)) - y;
fpy = A1 + 3 * A2 * paramLatSq + paramLatPow6 * (7 * A3 + 9 * A4 * paramLatSq);
paramLat -= dlat = fy / fpy;
if (Math.abs(dlat) < epsilon) {
break;
}
}
paramLatSq = paramLat * paramLat;
paramLatPow6 = paramLatSq * paramLatSq * paramLatSq;
var lon = d * M * x * (A1 + 3 * A2 * paramLatSq + paramLatPow6 * (7 * A3 + 9 * A4 * paramLatSq)) / Math.cos(paramLat);
var lat = d * Math.asin(Math.sin(paramLat) / M);
return [lon, lat];
}
};
return EqualEarth;
});
_registerModule(_modules, 'Maps/Projections/Miller.js', [], function () {
/* *
* Miller projection
* */
var quarterPI = Math.PI / 4,
deg2rad = Math.PI / 180,
scale = 63.78137;
var Miller = {
forward: function (lonLat) { return [
lonLat[0] * deg2rad * scale,
1.25 * scale * Math.log(Math.tan(quarterPI + 0.4 * lonLat[1] * deg2rad))
]; },
inverse: function (xy) { return [
(xy[0] / scale) / deg2rad,
2.5 * (Math.atan(Math.exp(0.8 * (xy[1] / scale))) - quarterPI) / deg2rad
]; }
};
return Miller;
});
_registerModule(_modules, 'Maps/Projections/Orthographic.js', [], function () {
/* *
* Orthographic projection
* */
var deg2rad = Math.PI / 180,
scale = 63.78460826781007;
var Orthographic = {
forward: function (lonLat) {
var lonDeg = lonLat[0],
latDeg = lonLat[1];
if (lonDeg < -90 || lonDeg > 90) {
return [NaN, NaN];
}
var lat = latDeg * deg2rad;
return [
Math.cos(lat) * Math.sin(lonDeg * deg2rad) * scale,
Math.sin(lat) * scale
];
},
inverse: function (xy) {
var x = xy[0] / scale,
y = xy[1] / scale,
z = Math.sqrt(x * x + y * y),
c = Math.asin(z),
cSin = Math.sin(c),
cCos = Math.cos(c);
return [
Math.atan2(x * cSin, z * cCos) / deg2rad,
Math.asin(z && y * cSin / z) / deg2rad
];
}
};
return Orthographic;
});
_registerModule(_modules, 'Maps/Projections/WebMercator.js', [], function () {
/* *
* Web Mercator projection, used for most online map tile services
* */
var maxLatitude = 85.0511287798, // The latitude that defines a square
r = 63.78137,
deg2rad = Math.PI / 180;
var WebMercator = {
forward: function (lonLat) {
if (Math.abs(lonLat[1]) > maxLatitude) {
return [NaN,
NaN];
}
var sinLat = Math.sin(lonLat[1] * deg2rad);
return [
r * lonLat[0] * deg2rad,
r * Math.log((1 + sinLat) / (1 - sinLat)) / 2
];
},
inverse: function (xy) { return [
xy[0] / (r * deg2rad),
(2 * Math.atan(Math.exp(xy[1] / r)) - (Math.PI / 2)) / deg2rad
]; },
maxLatitude: maxLatitude
};
return WebMercator;
});
_registerModule(_modules, 'Maps/Projections/ProjectionRegistry.js', [_modules['Maps/Projections/LambertConformalConic.js'], _modules['Maps/Projections/EqualEarth.js'], _modules['Maps/Projections/Miller.js'], _modules['Maps/Projections/Orthographic.js'], _modules['Maps/Projections/WebMercator.js']], function (LambertConformalConic, EqualEarth, Miller, Orthographic, WebMercator) {
/* *
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var registry = {
EqualEarth: EqualEarth,
LambertConformalConic: LambertConformalConic,
Miller: Miller,
Orthographic: Orthographic,
WebMercator: WebMercator
};
return registry;
});
_registerModule(_modules, 'Maps/Projection.js', [_modules['Maps/Projections/ProjectionRegistry.js'], _modules['Core/Utilities.js']], function (registry, U) {
/* *
*
* (c) 2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0,
i = 0,
il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
var erase = U.erase;
var deg2rad = Math.PI * 2 / 360;
// Safe padding on either side of the antimeridian to avoid points being
// projected to the wrong side of the plane
var floatCorrection = 0.000001;
// Keep longitude within -180 and 180. This is faster than using the modulo
// operator, and preserves the distinction between -180 and 180.
var wrapLon = function (lon) {
// Replacing the if's with while would increase the range, but make it prone
// to crashes on bad data
if (lon < -180) {
lon += 360;
}
if (lon > 180) {
lon -= 360;
}
return lon;
};
var Projection = /** @class */ (function () {
function Projection(options) {
if (options === void 0) { options = {}; }
// Whether the chart has points, lines or polygons given as coordinates
// with positive up, as opposed to paths in the SVG plane with positive
// down.
this.hasCoordinates = false;
// Whether the chart has true projection as opposed to pre-projected geojson
// as in the legacy map collection.
this.hasGeoProjection = false;
this.maxLatitude = 90;
this.options = options;
var name = options.name,
rotation = options.rotation;
this.rotator = rotation ? this.getRotator(rotation) : void 0;
this.def = name ? Projection.registry[name] : void 0;
var _a = this,
def = _a.def,
rotator = _a.rotator;
if (def) {
if (def.init) {
def.init(options);
}
this.maxLatitude = def.maxLatitude || 90;
this.hasGeoProjection = true;
}
if (rotator && def) {
this.forward = function (lonLat) {
lonLat = rotator.forward(lonLat);
return def.forward(lonLat);
};
this.inverse = function (xy) {
var lonLat = def.inverse(xy);
return rotator.inverse(lonLat);
};
}
else if (def) {
this.forward = def.forward;
this.inverse = def.inverse;
}
else if (rotator) {
this.forward = rotator.forward;
this.inverse = rotator.inverse;
}
}
// Add a projection definition to the registry, accessible by its `name`.
Projection.add = function (name, definition) {
Projection.registry[name] = definition;
};
// Calculate the great circle between two given coordinates
Projection.greatCircle = function (point1, point2, inclusive) {
var atan2 = Math.atan2,
cos = Math.cos,
sin = Math.sin,
sqrt = Math.sqrt;
var lat1 = point1[1] * deg2rad;
var lon1 = point1[0] * deg2rad;
var lat2 = point2[1] * deg2rad;
var lon2 = point2[0] * deg2rad;
var deltaLat = lat2 - lat1;
var deltaLng = lon2 - lon1;
var calcA = sin(deltaLat / 2) * sin(deltaLat / 2) +
cos(lat1) * cos(lat2) * sin(deltaLng / 2) * sin(deltaLng / 2);
var calcB = 2 * atan2(sqrt(calcA),
sqrt(1 - calcA));
var distance = calcB * 6371e3; // in meters
var jumps = Math.round(distance / 500000); // 500 km each jump
var lineString = [];
if (inclusive) {
lineString.push(point1);
}
if (jumps > 1) {
var step = 1 / jumps;
for (var fraction = step; fraction < 0.999; // Account for float errors
fraction += step) {
var A = sin((1 - fraction) * calcB) / sin(calcB);
var B = sin(fraction * calcB) / sin(calcB);
var x = A * cos(lat1) * cos(lon1) + B * cos(lat2) * cos(lon2);
var y = A * cos(lat1) * sin(lon1) + B * cos(lat2) * sin(lon2);
var z = A * sin(lat1) + B * sin(lat2);
var lat3 = atan2(z,
sqrt(x * x + y * y));
var lon3 = atan2(y,
x);
lineString.push([lon3 / deg2rad, lat3 / deg2rad]);
}
}
if (inclusive) {
lineString.push(point2);
}
return lineString;
};
Projection.insertGreatCircles = function (poly) {
var i = poly.length - 1;
while (i--) {
// Distance in degrees, either in lon or lat. Avoid heavy
// calculation of true distance.
var roughDistance = Math.max(Math.abs(poly[i][0] - poly[i + 1][0]),
Math.abs(poly[i][1] - poly[i + 1][1]));
if (roughDistance > 10) {
var greatCircle = Projection.greatCircle(poly[i],
poly[i + 1]);
if (greatCircle.length) {
poly.splice.apply(poly, __spreadArrays([i + 1, 0], greatCircle));
}
}
}
};
Projection.toString = function (options) {
var _a = options || {},
name = _a.name,
rotation = _a.rotation;
return [name, rotation && rotation.join(',')].join(';');
};
/*
* Take the rotation options and return the appropriate projection functions
*/
Projection.prototype.getRotator = function (rotation) {
var deltaLambda = rotation[0] * deg2rad,
deltaPhi = (rotation[1] || 0) * deg2rad,
deltaGamma = (rotation[2] || 0) * deg2rad;
var cosDeltaPhi = Math.cos(deltaPhi),
sinDeltaPhi = Math.sin(deltaPhi),
cosDeltaGamma = Math.cos(deltaGamma),
sinDeltaGamma = Math.sin(deltaGamma);
if (deltaLambda === 0 && deltaPhi === 0 && deltaGamma === 0) {
// Don't waste processing time
return;
}
return {
forward: function (lonLat) {
// Lambda (lon) rotation
var lon = lonLat[0] * deg2rad + deltaLambda;
// Phi (lat) and gamma rotation
var lat = lonLat[1] * deg2rad,
cosLat = Math.cos(lat),
x = Math.cos(lon) * cosLat,
y = Math.sin(lon) * cosLat,
sinLat = Math.sin(lat),
k = sinLat * cosDeltaPhi + x * sinDeltaPhi;
return [
Math.atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - sinLat * sinDeltaPhi) / deg2rad,
Math.asin(k * cosDeltaGamma + y * sinDeltaGamma) / deg2rad
];
},
inverse: function (rLonLat) {
// Lambda (lon) unrotation
var lon = rLonLat[0] * deg2rad;
// Phi (lat) and gamma unrotation
var lat = rLonLat[1] * deg2rad,
cosLat = Math.cos(lat),
x = Math.cos(lon) * cosLat,
y = Math.sin(lon) * cosLat,
sinLat = Math.sin(lat),
k = sinLat * cosDeltaGamma - y * sinDeltaGamma;
return [
(Math.atan2(y * cosDeltaGamma + sinLat * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi) - deltaLambda) / deg2rad,
Math.asin(k * cosDeltaPhi - x * sinDeltaPhi) / deg2rad
];
}
};
};
// Project a lonlat coordinate position to xy. Dynamically overridden when
// projection is set.
Projection.prototype.forward = function (lonLat) {
return lonLat;
};
// Project an xy chart coordinate position to lonlat. Dynamically overridden
// when projection is set.
Projection.prototype.inverse = function (xy) {
return xy;
};
Projection.prototype.clipOnAntimeridian = function (poly, isPolygon) {
var antimeridian = 180;
var intersections = [];
var polygons = [poly];
poly.forEach(function (lonLat, i) {
var previousLonLat = poly[i - 1];
if (!i) {
if (!isPolygon) {
return;
}
// Else, wrap to beginning
previousLonLat = poly[poly.length - 1];
}
var lon1 = previousLonLat[0],
lon2 = lonLat[0];
if (
// Both points, after rotating for antimeridian, are on the far
// side of the Earth
(lon1 < -90 || lon1 > 90) &&
(lon2 < -90 || lon2 > 90) &&
// ... and on either side of the plane
(lon1 > 0) !== (lon2 > 0)) {
// Interpolate to the intersection latitude
var fraction = (antimeridian - previousLonLat[0]) /
(lonLat[0] - previousLonLat[0]);
var lat = previousLonLat[1] +
fraction * (lonLat[1] - previousLonLat[1]);
intersections.push({
i: i,
lat: lat,
direction: lon1 < 0 ? 1 : -1,
previousLonLat: previousLonLat,
lonLat: lonLat
});
}
});
var polarIntersection;
if (intersections.length) {
if (isPolygon) {
// Simplified use of the even-odd rule, if there is an odd
// amount of intersections between the polygon and the
// antimeridian, the pole is inside the polygon. Applies
// primarily to Antarctica.
if (intersections.length % 2 === 1) {
polarIntersection = intersections.slice().sort(function (a, b) { return Math.abs(b.lat) - Math.abs(a.lat); })[0];
erase(intersections, polarIntersection);
}
// Pull out slices of the polygon that is on the opposite side
// of the antimeridian compared to the starting point
var i = intersections.length - 2;
while (i >= 0) {
var index = intersections[i].i;
var lonPlus = wrapLon(antimeridian +
intersections[i].direction * floatCorrection);
var lonMinus = wrapLon(antimeridian -
intersections[i].direction * floatCorrection);
var slice = poly.splice.apply(poly,
__spreadArrays([index,
intersections[i + 1].i - index],
Projection.greatCircle([lonPlus,
intersections[i].lat],
[lonPlus,
intersections[i + 1].lat],
true)));
// Add interpolated points close to the cut
slice.push.apply(slice, Projection.greatCircle([lonMinus, intersections[i + 1].lat], [lonMinus, intersections[i].lat], true));
polygons.push(slice);
i -= 2;
}
// Insert dummy points close to the pole
if (polarIntersection) {
for (var i_1 = 0; i_1 < polygons.length; i_1++) {
var poly_1 = polygons[i_1];
var indexOf = poly_1.indexOf(polarIntersection.lonLat);
if (indexOf > -1) {
var polarLatitude = (polarIntersection.lat < 0 ? -1 : 1) *
this.maxLatitude;
var lon1 = wrapLon(antimeridian +
polarIntersection.direction * floatCorrection);
var lon2 = wrapLon(antimeridian -
polarIntersection.direction * floatCorrection);
var polarSegment = Projection.greatCircle([lon1,
polarIntersection.lat],
[lon1,
polarLatitude],
true).concat(Projection.greatCircle([lon2,
polarLatitude],
[lon2,
polarIntersection.lat],
true));
poly_1.splice.apply(poly_1, __spreadArrays([indexOf,
0], polarSegment));
break;
}
}
}
// Map lines, not closed
}
else {
var i = intersections.length;
while (i--) {
var index = intersections[i].i;
var slice = poly.splice(index,
poly.length,
// Add interpolated point close to the cut
[
wrapLon(antimeridian +
intersections[i].direction * floatCorrection),
intersections[i].lat
]);
// Add interpolated point close to the cut
slice.unshift([
wrapLon(antimeridian -
intersections[i].direction * floatCorrection),
intersections[i].lat
]);
polygons.push(slice);
}
}
}
// Insert great circles along the cuts
/*
if (isPolygon && polygons.length > 1 || polarIntersection) {
polygons.forEach(Projection.insertGreatCircles);
}
*/
return polygons;
};
// Take a GeoJSON geometry and return a translated SVGPath
Projection.prototype.path = function (geometry) {
var _this = this;
var _a = this,
def = _a.def,
rotator = _a.rotator;
var antimeridian = 180;
var path = [];
var isPolygon = geometry.type === 'Polygon' ||
geometry.type === 'MultiPolygon';
// @todo: It doesn't really have to do with whether north is
// positive. It depends on whether the coordinates are
// pre-projected.
var hasGeoProjection = this.hasGeoProjection;
// @todo better test for when to do this
var projectingToPlane = this.options.name !== 'Orthographic';
// We need to rotate in a separate step before applying antimeridian
// clipping
var preclip = projectingToPlane ? rotator : void 0;
var postclip = projectingToPlane ? (def || this) : this;
var addToPath = function (polygon) {
// Create a copy of the original coordinates. The copy applies a
// correction of points close to the antimeridian in order to
// prevent the points to be projected to the wrong side of the
// plane. Float errors in topojson or in the projection may cause
// that.
var poly = polygon.map(function (lonLat) {
if (projectingToPlane) {
if (preclip) {
lonLat = preclip.forward(lonLat);
}
var lon = lonLat[0];
if (Math.abs(lon - antimeridian) < floatCorrection) {
if (lon < antimeridian) {
lon = antimeridian - floatCorrection;
}
else {
lon = antimeridian + floatCorrection;
}
}
lonLat = [lon, lonLat[1]];
}
return lonLat;
});
var polygons = [poly];
if (hasGeoProjection) {
// Insert great circles into long straight lines
Projection.insertGreatCircles(poly);
if (projectingToPlane) {
polygons = _this.clipOnAntimeridian(poly, isPolygon);
}
}
polygons.forEach(function (poly) {
if (poly.length < 2) {
return;
}
var movedTo = false;
var firstValidLonLat;
var lastValidLonLat;
var gap = false;
var pushToPath = function (point) {
if (!movedTo) {
path.push(['M',
point[0],
point[1]]);
movedTo = true;
}
else {
path.push(['L', point[0], point[1]]);
}
};
for (var i = 0; i < poly.length; i++) {
var lonLat = poly[i];
var point = postclip.forward(lonLat);
var valid = (!isNaN(point[0]) &&
!isNaN(point[1]) &&
(!hasGeoProjection ||
// Limited projections like Web Mercator
(lonLat[1] <= _this.maxLatitude &&
lonLat[1] >= -_this.maxLatitude)));
if (valid) {
// In order to be able to interpolate if the first or
// last point is invalid (on the far side of the globe
// in an orthographic projection), we need to push the
// first valid point to the end of the polygon.
if (isPolygon && !firstValidLonLat) {
firstValidLonLat = lonLat;
poly.push(lonLat);
}
// When entering the first valid point after a gap of
// invalid points, typically on the far side of the
// globe in an orthographic projection.
if (gap && lastValidLonLat) {
// For areas, in an orthographic projection, the
// great circle between two visible points will be
// close to the horizon. A possible exception may be
// when the two points are on opposite sides of the
// globe. It that poses a problem, we may have to
// rewrite this to use the small circle related to
// the current lon0 and lat0.
if (isPolygon && hasGeoProjection) {
var greatCircle = Projection.greatCircle(lastValidLonLat,
lonLat);
greatCircle.forEach(function (lonLat) {
return pushToPath(postclip.forward(lonLat));
});
// For lines, just jump over the gap
}
else {
movedTo = false;
}
}
pushToPath(point);
lastValidLonLat = lonLat;
gap = false;
}
else {
gap = true;
}
}
});
};
if (geometry.type === 'LineString') {
addToPath(geometry.coordinates);
}
else if (geometry.type === 'MultiLineString') {
geometry.coordinates.forEach(function (c) { return addToPath(c); });
}
else if (geometry.type === 'Polygon') {
geometry.coordinates.forEach(function (c) { return addToPath(c); });
if (path.length) {
path.push(['Z']);
}
}
else if (geometry.type === 'MultiPolygon') {
geometry.coordinates.forEach(function (polygons) {
polygons.forEach(function (c) { return addToPath(c); });
});
if (path.length) {
path.push(['Z']);
}
}
return path;
};
Projection.registry = registry;
return Projection;
}());
return Projection;
});
_registerModule(_modules, 'Maps/MapView.js', [_modules['Maps/MapViewOptionsDefault.js'], _modules['Maps/Projection.js'], _modules['Core/Utilities.js']], function (defaultOptions, Projection, U) {
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var addEvent = U.addEvent,
clamp = U.clamp,
fireEvent = U.fireEvent,
isNumber = U.isNumber,
merge = U.merge,
pick = U.pick,
relativeLength = U.relativeLength;
/**
* The world size in terms of 10k meters in the Web Mercator projection, to
* match a 256 square tile to zoom level 0
*/
var worldSize = 400.979322;
var tileSize = 256;
/**
* The map view handles zooming and centering on the map, and various
* client-side projection capabilities.
*
* On a chart instance, the map view is available as `chart.mapView`.
*
* @class
* @name Highcharts.MapView
*
* @param {Highcharts.Chart} chart
* The Chart instance
* @param {Highcharts.MapViewOptions} options
* MapView options
*/
var MapView = /** @class */ (function () {
function MapView(chart, options) {
var _this = this;
this.userOptions = options || {};
var o = merge(defaultOptions,
options);
this.chart = chart;
/**
* The current center of the view in terms of `[longitude, latitude]`.
* @name Highcharts.MapView#center
* @readonly
* @type {LonLatArray}
*/
this.center = o.center;
this.options = o;
this.projection = new Projection(o.projection);
/**
* The current zoom level of the view.
* @name Highcharts.MapView#zoom
* @readonly
* @type {number}
*/
this.zoom = o.zoom || 0;
// Initialize and respond to chart size changes
addEvent(chart, 'afterSetChartSize', function () {
if (_this.minZoom === void 0 || // When initializing the chart
_this.minZoom === _this.zoom // When resizing the chart
) {
_this.fitToBounds(void 0, void 0, false);
if (isNumber(_this.userOptions.zoom)) {
_this.zoom = _this.userOptions.zoom;
}
if (_this.userOptions.center) {
merge(true, _this.center, _this.userOptions.center);
}
}
});
// Set up panning for maps. In orthographic projections the globe will
// rotate, otherwise adjust the map center.
var mouseDownCenterProjected;
var mouseDownKey;
var mouseDownRotation;
var onPan = function (e) {
var pinchDown = chart.pointer.pinchDown;
var mouseDownX = chart.mouseDownX,
mouseDownY = chart.mouseDownY;
if (pinchDown.length === 1) {
mouseDownX = pinchDown[0].chartX;
mouseDownY = pinchDown[0].chartY;
}
if (typeof mouseDownX === 'number' &&
typeof mouseDownY === 'number') {
var key = mouseDownX + "," + mouseDownY, _a = e.originalEvent, chartX = _a.chartX, chartY = _a.chartY;
// Reset starting position
if (key !== mouseDownKey) {
mouseDownKey = key;
mouseDownCenterProjected = _this.projection
.forward(_this.center);
mouseDownRotation = (_this.projection.options.rotation || [0, 0]).slice();
}
// Panning rotates the globe
if (_this.projection.options.name === 'Orthographic' &&
// ... but don't rotate if we're loading only a part of the
// world
(_this.minZoom || Infinity) < 3) {
// Empirical ratio where the globe rotates roughly the same
// speed as moving the pointer across the center of the
// projection
var ratio = 440 / (_this.getScale() * Math.min(chart.plotWidth,
chart.plotHeight));
if (mouseDownRotation) {
var lon = (mouseDownX - chartX) * ratio -
mouseDownRotation[0];
var lat = clamp(-mouseDownRotation[1] -
(mouseDownY - chartY) * ratio, -80, 80);
_this.update({
projection: {
rotation: [-lon, -lat]
},
center: [lon, lat],
zoom: _this.zoom
}, true, false);
}
}
else {
var scale = _this.getScale();
var newCenter = _this.projection.inverse([
mouseDownCenterProjected[0] +
(mouseDownX - chartX) / scale,
mouseDownCenterProjected[1] -
(mouseDownY - chartY) / scale
]);
_this.setView(newCenter, void 0, true, false);
}
e.preventDefault();
}
};
addEvent(chart, 'pan', onPan);
addEvent(chart, 'touchpan', onPan);
// Perform the map zoom by selection
addEvent(chart, 'selection', function (evt) {
// Zoom in
if (!evt.resetSelection) {
var x = evt.x - chart.plotLeft;
var y = evt.y - chart.plotTop;
var _a = _this.pixelsToProjectedUnits({ x: x,
y: y }),
y1 = _a.y,
x1 = _a.x;
var _b = _this.pixelsToProjectedUnits({ x: x + evt.width,
y: y + evt.height }),
y2 = _b.y,
x2 = _b.x;
_this.fitToBounds({ x1: x1, y1: y1, x2: x2, y2: y2 }, void 0, true, evt.originalEvent.touches ?
// On touch zoom, don't animate, since we're already in
// transformed zoom preview
false :
// On mouse zoom, obey the chart-level animation
void 0);
// Only for mouse. Touch users can pinch out.
if (!/^touch/.test((evt.originalEvent.type))) {
chart.showResetZoom();
}
evt.preventDefault();
// Reset zoom
}
else {
_this.zoomBy();
}
});
}
/**
* Fit the view to given bounds
*
* @function Highcharts.MapView#fitToBounds
* @param {Object} bounds
* Bounds in terms of projected units given as `{ x1, y1, x2, y2 }`.
* If not set, fit to the bounds of the current data set
* @param {number|string} [padding=0]
* Padding inside the bounds. A number signifies pixels, while a
* percentage string (like `5%`) can be used as a fraction of the
* plot area size.
* @param {boolean} [redraw=true]
* Whether to redraw the chart immediately
* @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
* What animation to use for redraw
*/
MapView.prototype.fitToBounds = function (bounds, padding, redraw, animation) {
if (redraw === void 0) { redraw = true; }
var b = bounds || this.getProjectedBounds();
if (b) {
var _a = this.chart,
plotWidth = _a.plotWidth,
plotHeight = _a.plotHeight,
pad = pick(padding,
bounds ? 0 : this.options.padding),
paddingX = relativeLength(pad,
plotWidth),
paddingY = relativeLength(pad,
plotHeight);
var scaleToPlotArea = Math.max((b.x2 - b.x1) / ((plotWidth - paddingX) / tileSize), (b.y2 - b.y1) / ((plotHeight - paddingY) / tileSize));
var zoom = Math.log(worldSize / scaleToPlotArea) / Math.log(2);
// Reset minZoom when fitting to natural bounds
if (!bounds) {
this.minZoom = zoom;
}
var center = this.projection.inverse([
(b.x2 + b.x1) / 2,
(b.y2 + b.y1) / 2
]);
this.setView(center, zoom, redraw, animation);
}
};
MapView.prototype.getProjectedBounds = function () {
var allBounds = this.chart.series.reduce(function (acc,
s) {
var bounds = s.getProjectedBounds && s.getProjectedBounds();
if (bounds) {
acc.push(bounds);
}
return acc;
}, []);
return MapView.compositeBounds(allBounds);
};
MapView.prototype.getScale = function () {
// A zoom of 0 means the world (360x360 degrees) fits in a 256x256 px
// tile
return (tileSize / worldSize) * Math.pow(2, this.zoom);
};
MapView.prototype.redraw = function (animation) {
this.chart.series.forEach(function (s) {
if (s.useMapGeometry) {
s.isDirty = true;
}
});
this.chart.redraw(animation);
};
/**
* Set the view to given center and zoom values.
* @function Highcharts.MapView#setView
* @param {Highcharts.LonLatArray|undefined} center
* The center point
* @param {number} zoom
* The zoom level
* @param {boolean} [redraw=true]
* Whether to redraw immediately
* @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
* Animation options for the redraw
*
* @sample maps/mapview/setview
* Set the view programmatically
*/
MapView.prototype.setView = function (center, zoom, redraw, animation) {
if (redraw === void 0) { redraw = true; }
var zoomingIn = false;
if (center) {
this.center = center;
}
if (typeof zoom === 'number') {
if (typeof this.minZoom === 'number') {
zoom = Math.max(zoom, this.minZoom);
}
if (typeof this.options.maxZoom === 'number') {
zoom = Math.min(zoom, this.options.maxZoom);
}
zoomingIn = zoom > this.zoom;
this.zoom = zoom;
}
// Stay within the data bounds
var bounds = this.getProjectedBounds();
if (bounds &&
// When zooming in, we don't need to adjust to the bounds, as that
// could shift the location under the mouse
!zoomingIn) {
var projectedCenter = this.projection.forward(this.center);
var _a = this.chart,
plotWidth = _a.plotWidth,
plotHeight = _a.plotHeight;
var scale = this.getScale();
var bottomLeft = this.projectedUnitsToPixels({
x: bounds.x1,
y: bounds.y1
});
var topRight = this.projectedUnitsToPixels({
x: bounds.x2,
y: bounds.y2
});
var boundsCenterProjected = [
(bounds.x1 + bounds.x2) / 2,
(bounds.y1 + bounds.y2) / 2
];
// Pixel coordinate system is reversed vs projected
var x1 = bottomLeft.x;
var y1 = topRight.y;
var x2 = topRight.x;
var y2 = bottomLeft.y;
// Map smaller than plot area, center it
if (x2 - x1 < plotWidth) {
projectedCenter[0] = boundsCenterProjected[0];
// Off west
}
else if (x1 < 0 && x2 < plotWidth) {
// Adjust eastwards
projectedCenter[0] += Math.max(x1, x2 - plotWidth) / scale;
// Off east
}
else if (x2 > plotWidth && x1 > 0) {
// Adjust westwards
projectedCenter[0] += Math.min(x2 - plotWidth, x1) / scale;
}
// Map smaller than plot area, center it
if (y2 - y1 < plotHeight) {
projectedCenter[1] = boundsCenterProjected[1];
// Off north
}
else if (y1 < 0 && y2 < plotHeight) {
// Adjust southwards
projectedCenter[1] -= Math.max(y1, y2 - plotHeight) / scale;
// Off south
}
else if (y2 > plotHeight && y1 > 0) {
// Adjust northwards
projectedCenter[1] -= Math.min(y2 - plotHeight, y1) / scale;
}
this.center = this.projection.inverse(projectedCenter);
}
fireEvent(this, 'afterSetView');
if (redraw) {
this.redraw(animation);
}
};
/**
* Convert projected units to pixel position
*
* @function Highcharts.MapView#projectedUnitsToPixels
* @param {Highcharts.PositionObject} pos
* The position in projected units
* @return {Highcharts.PositionObject} The position in pixels
*/
MapView.prototype.projectedUnitsToPixels = function (pos) {
var scale = this.getScale();
var projectedCenter = this.projection.forward(this.center);
var centerPxX = this.chart.plotWidth / 2;
var centerPxY = this.chart.plotHeight / 2;
var x = centerPxX - scale * (projectedCenter[0] - pos.x);
var y = centerPxY + scale * (projectedCenter[1] - pos.y);
return { x: x, y: y };
};
/**
* Convert pixel position to projected units
*
* @function Highcharts.MapView#pixelsToProjectedUnits
* @param {Highcharts.PositionObject} pos
* The position in pixels
* @return {Highcharts.PositionObject} The position in projected units
*/
MapView.prototype.pixelsToProjectedUnits = function (pos) {
var x = pos.x,
y = pos.y;
var scale = this.getScale();
var projectedCenter = this.projection.forward(this.center);
var centerPxX = this.chart.plotWidth / 2;
var centerPxY = this.chart.plotHeight / 2;
var projectedX = projectedCenter[0] + (x - centerPxX) / scale;
var projectedY = projectedCenter[1] - (y - centerPxY) / scale;
return { x: projectedX, y: projectedY };
};
/**
* Update the view with given options
*
* @function Highcharts.MapView#update
*
* @param {Partial<Highcharts.MapViewOptions>} options
* The new map view options to apply
* @param {boolean} [redraw=true]
* Whether to redraw immediately
* @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
* The animation to apply to a the redraw
*/
MapView.prototype.update = function (options, redraw, animation) {
if (redraw === void 0) { redraw = true; }
var newProjection = options.projection;
var isDirtyProjection = newProjection && ((Projection.toString(newProjection) !==
Projection.toString(this.options.projection)));
merge(true, this.userOptions, options);
merge(true, this.options, options);
if (isDirtyProjection) {
this.chart.series.forEach(function (series) {
if (series.clearBounds) {
series.clearBounds();
}
series.isDirty = true;
series.isDirtyData = true;
});
this.projection = new Projection(this.options.projection);
// Fit to natural bounds if center/zoom are not explicitly given
if (!options.center && !isNumber(options.zoom)) {
this.fitToBounds(void 0, void 0, false);
}
}
if (options.center || isNumber(options.zoom)) {
this.setView(this.options.center, options.zoom, false);
}
if (redraw) {
this.chart.redraw(animation);
}
};
/**
* Zoom the map view by a given number
*
* @function Highcharts.MapView#zoomBy
*
* @param {number|undefined} [howMuch]
* The amount of zoom to apply. 1 zooms in on half the current view,
* -1 zooms out. Pass `undefined` to zoom to the full bounds of the
* map.
* @param {Highcharts.LonLatArray} [coords]
* Optional map coordinates to keep fixed
* @param {Array<number>} [chartCoords]
* Optional chart coordinates to keep fixed, in pixels
* @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
* The animation to apply to a the redraw
*/
MapView.prototype.zoomBy = function (howMuch, coords, chartCoords, animation) {
var chart = this.chart;
var projectedCenter = this.projection.forward(this.center);
// let { x, y } = coords || {};
var _a = coords ? this.projection.forward(coords) : [],
x = _a[0],
y = _a[1];
if (typeof howMuch === 'number') {
var zoom = this.zoom + howMuch;
var center = void 0;
// Keep chartX and chartY stationary - convert to lat and lng
if (chartCoords) {
var chartX = chartCoords[0],
chartY = chartCoords[1];
var scale = this.getScale();
var offsetX = chartX - chart.plotLeft - chart.plotWidth / 2;
var offsetY = chartY - chart.plotTop - chart.plotHeight / 2;
x = projectedCenter[0] + offsetX / scale;
y = projectedCenter[1] + offsetY / scale;
}
// Keep lon and lat stationary by adjusting the center
if (typeof x === 'number' && typeof y === 'number') {
var scale = 1 - Math.pow(2,
this.zoom) / Math.pow(2,
zoom);
// const projectedCenter = this.projection.forward(this.center);
var offsetX = projectedCenter[0] - x;
var offsetY = projectedCenter[1] - y;
projectedCenter[0] -= offsetX * scale;
projectedCenter[1] += offsetY * scale;
center = this.projection.inverse(projectedCenter);
}
this.setView(center, zoom, void 0, animation);
// Undefined howMuch => reset zoom
}
else {
this.fitToBounds(void 0, void 0, void 0, animation);
}
};
/* *
* Return the composite bounding box of a collection of bounding boxes
*/
MapView.compositeBounds = function (arrayOfBounds) {
if (arrayOfBounds.length) {
return arrayOfBounds
.slice(1)
.reduce(function (acc, cur) {
acc.x1 = Math.min(acc.x1, cur.x1);
acc.y1 = Math.min(acc.y1, cur.y1);
acc.x2 = Math.max(acc.x2, cur.x2);
acc.y2 = Math.max(acc.y2, cur.y2);
return acc;
}, merge(arrayOfBounds[0]));
}
return;
};
return MapView;
}());
return MapView;
});
_registerModule(_modules, 'Maps/MapSymbols.js', [_modules['Core/Renderer/SVG/SVGRenderer.js']], function (SVGRenderer) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var symbols = SVGRenderer.prototype.symbols;
/* *
*
* Functions
*
* */
/* eslint-disable require-jsdoc, valid-jsdoc */
function bottomButton(x, y, w, h, options) {
var r = (options && options.r) || 0;
return selectiveRoundedRect(x - 1, y - 1, w, h, 0, 0, r, r);
}
/**
* Create symbols for the zoom buttons
* @private
*/
function selectiveRoundedRect(x, y, w, h, rTopLeft, rTopRight, rBottomRight, rBottomLeft) {
return [
['M', x + rTopLeft, y],
// top side
['L', x + w - rTopRight, y],
// top right corner
[
'C',
x + w - rTopRight / 2,
y,
x + w,
y + rTopRight / 2,
x + w,
y + rTopRight
],
// right side
['L', x + w, y + h - rBottomRight],
// bottom right corner
[
'C', x + w, y + h - rBottomRight / 2,
x + w - rBottomRight / 2, y + h,
x + w - rBottomRight, y + h
],
// bottom side
['L', x + rBottomLeft, y + h],
// bottom left corner
[
'C',
x + rBottomLeft / 2,
y + h,
x,
y + h - rBottomLeft / 2,
x,
y + h - rBottomLeft
],
// left side
['L', x, y + rTopLeft],
// top left corner
['C', x, y + rTopLeft / 2, x + rTopLeft / 2, y, x + rTopLeft, y],
['Z']
];
}
function topButton(x, y, w, h, options) {
var r = (options && options.r) || 0;
return selectiveRoundedRect(x - 1, y - 1, w, h, r, r, 0, 0);
}
symbols.bottombutton = bottomButton;
symbols.topbutton = topButton;
/* *
*
* Default Export
*
* */
return symbols;
});
_registerModule(_modules, 'Core/Chart/MapChart.js', [_modules['Core/Chart/Chart.js'], _modules['Core/DefaultOptions.js'], _modules['Maps/MapView.js'], _modules['Core/Renderer/SVG/SVGRenderer.js'], _modules['Core/Utilities.js']], function (Chart, D, MapView, SVGRenderer, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var getOptions = D.getOptions;
var addEvent = U.addEvent,
clamp = U.clamp,
isNumber = U.isNumber,
merge = U.merge,
pick = U.pick;
/**
* Map-optimized chart. Use {@link Highcharts.Chart|Chart} for common charts.
*
* @requires modules/map
*
* @class
* @name Highcharts.MapChart
* @extends Highcharts.Chart
*/
var MapChart = /** @class */ (function (_super) {
__extends(MapChart, _super);
function MapChart() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Initializes the chart. The constructor's arguments are passed on
* directly.
*
* @function Highcharts.MapChart#init
*
* @param {Highcharts.Options} userOptions
* Custom options.
*
* @param {Function} [callback]
* Function to run when the chart has loaded and and all external
* images are loaded.
*
*
* @emits Highcharts.MapChart#event:init
* @emits Highcharts.MapChart#event:afterInit
*/
MapChart.prototype.init = function (userOptions, callback) {
// Initialize the MapView after initialization, but before firstRender
addEvent(this, 'afterInit', function () {
this.mapView = new MapView(this, this.options.mapView);
});
var defaultCreditsOptions = getOptions().credits;
var options = merge({
chart: {
panning: {
enabled: true,
type: 'xy'
},
type: 'map'
},
credits: {
mapText: pick(defaultCreditsOptions.mapText, ' \u00a9 <a href="{geojson.copyrightUrl}">' +
'{geojson.copyrightShort}</a>'),
mapTextFull: pick(defaultCreditsOptions.mapTextFull, '{geojson.copyright}')
},
mapView: {},
tooltip: {
followTouchMove: false
}
},
userOptions // user's options
);
_super.prototype.init.call(this, options, callback);
};
return MapChart;
}(Chart));
/* eslint-disable valid-jsdoc */
(function (MapChart) {
/**
* Contains all loaded map data for Highmaps.
*
* @requires modules/map
*
* @name Highcharts.maps
* @type {Record<string,*>}
*/
MapChart.maps = {};
/**
* The factory function for creating new map charts. Creates a new {@link
* Highcharts.MapChart|MapChart} object with different default options than
* the basic Chart.
*
* @requires modules/map
*
* @function Highcharts.mapChart
*
* @param {string|Highcharts.HTMLDOMElement} [renderTo]
* The DOM element to render to, or its id.
*
* @param {Highcharts.Options} options
* The chart options structure as described in the
* [options reference](https://api.highcharts.com/highstock).
*
* @param {Highcharts.ChartCallbackFunction} [callback]
* A function to execute when the chart object is finished loading and
* rendering. In most cases the chart is built in one thread, but in
* Internet Explorer version 8 or less the chart is sometimes initialized
* before the document is ready, and in these cases the chart object will
* not be finished synchronously. As a consequence, code that relies on the
* newly built Chart object should always run in the callback. Defining a
* [chart.events.load](https://api.highcharts.com/highstock/chart.events.load)
* handler is equivalent.
*
* @return {Highcharts.MapChart}
* The chart object.
*/
function mapChart(a, b, c) {
return new MapChart(a, b, c);
}
MapChart.mapChart = mapChart;
/**
* Utility for reading SVG paths directly.
*
* @requires modules/map
*
* @function Highcharts.splitPath
*
* @param {string|Array<string|number>} path
*
* @return {Highcharts.SVGPathArray}
* Splitted SVG path
*/
function splitPath(path) {
var arr;
if (typeof path === 'string') {
path = path
// Move letters apart
.replace(/([A-Za-z])/g, ' $1 ')
// Trim
.replace(/^\s*/, '').replace(/\s*$/, '');
// Split on spaces and commas. The semicolon is bogus, designed to
// circumvent string replacement in the pre-v7 assembler that built
// specific styled mode files.
var split = path.split(/[ ,;]+/);
arr = split.map(function (item) {
if (!/[A-za-z]/.test(item)) {
return parseFloat(item);
}
return item;
});
}
else {
arr = path;
}
return SVGRenderer.prototype.pathToSegments(arr);
}
MapChart.splitPath = splitPath;
})(MapChart || (MapChart = {}));
/* *
*
* Default Export
*
* */
return MapChart;
});
_registerModule(_modules, 'Series/Map/MapPoint.js', [_modules['Series/ColorMapMixin.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (ColorMapMixin, SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var ScatterSeries = SeriesRegistry.seriesTypes.scatter;
var extend = U.extend;
/* *
*
* Class
*
* */
var MapPoint = /** @class */ (function (_super) {
__extends(MapPoint, _super);
function MapPoint() {
/* *
*
* Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
_this.options = void 0;
_this.path = void 0;
_this.series = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
// Get the projected path based on the geometry. May also be called on
// mapData options (not point instances), hence static.
MapPoint.getProjectedPath = function (point, projection) {
if (!point.projectedPath) {
if (projection && point.geometry) {
// Always true when given GeoJSON coordinates
projection.hasCoordinates = true;
point.projectedPath = projection.path(point.geometry);
// SVG path given directly in point options
}
else {
point.projectedPath = point.path;
}
}
return point.projectedPath || [];
};
/**
* Extend the Point object to split paths.
* @private
*/
MapPoint.prototype.applyOptions = function (options, x) {
var series = this.series,
point = _super.prototype.applyOptions.call(this,
options,
x),
joinBy = series.joinBy,
mapPoint;
if (series.mapData && series.mapMap) {
var joinKey = joinBy[1];
var mapKey = _super.prototype.getNestedProperty.call(point,
joinKey);
mapPoint = typeof mapKey !== 'undefined' &&
series.mapMap[mapKey];
if (mapPoint) {
extend(point, mapPoint); // copy over properties
}
else {
point.value = point.value || null;
}
}
return point;
};
/**
* Stop the fade-out
* @private
*/
MapPoint.prototype.onMouseOver = function (e) {
U.clearTimeout(this.colorInterval);
if (this.value !== null || this.series.options.nullInteraction) {
_super.prototype.onMouseOver.call(this, e);
}
else {
// #3401 Tooltip doesn't hide when hovering over null points
this.series.onMouseOut(e);
}
};
/**
* Highmaps only. Zoom in on the point using the global animation.
*
* @sample maps/members/point-zoomto/
* Zoom to points from butons
*
* @requires modules/map
*
* @function Highcharts.Point#zoomTo
*/
MapPoint.prototype.zoomTo = function () {
var point = this;
var chart = point.series.chart;
if (chart.mapView && point.bounds) {
chart.mapView.fitToBounds(point.bounds, void 0, false);
point.series.isDirty = true;
chart.redraw();
}
};
return MapPoint;
}(ScatterSeries.prototype.pointClass));
extend(MapPoint.prototype, {
dataLabelOnNull: ColorMapMixin.PointMixin.dataLabelOnNull,
isValid: ColorMapMixin.PointMixin.isValid,
moveToTopOnHover: ColorMapMixin.PointMixin.moveToTopOnHover
});
/* *
*
* Default Export
*
* */
return MapPoint;
});
_registerModule(_modules, 'Series/Map/MapSeries.js', [_modules['Core/Animation/AnimationUtilities.js'], _modules['Series/ColorMapMixin.js'], _modules['Series/CenteredUtilities.js'], _modules['Core/Globals.js'], _modules['Core/Legend/LegendSymbol.js'], _modules['Core/Chart/MapChart.js'], _modules['Series/Map/MapPoint.js'], _modules['Maps/MapView.js'], _modules['Core/Series/Series.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Renderer/SVG/SVGRenderer.js'], _modules['Core/Utilities.js']], function (A, ColorMapMixin, CU, H, LegendSymbol, MapChart, MapPoint, MapView, Series, SeriesRegistry, SVGRenderer, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var animObject = A.animObject;
var noop = H.noop;
var maps = MapChart.maps,
splitPath = MapChart.splitPath;
var
// indirect dependency to keep product size low
_a = SeriesRegistry.seriesTypes,
ColumnSeries = _a.column,
ScatterSeries = _a.scatter;
var extend = U.extend,
fireEvent = U.fireEvent,
getNestedProperty = U.getNestedProperty,
isArray = U.isArray,
isNumber = U.isNumber,
merge = U.merge,
objectEach = U.objectEach,
pick = U.pick,
splat = U.splat;
/* *
*
* Class
*
* */
/**
* @private
* @class
* @name Highcharts.seriesTypes.map
*
* @augments Highcharts.Series
*/
var MapSeries = /** @class */ (function (_super) {
__extends(MapSeries, _super);
function MapSeries() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
_this.chart = void 0;
_this.data = void 0;
_this.group = void 0;
_this.joinBy = void 0;
_this.options = void 0;
_this.points = void 0;
_this.transformGroup = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* The initial animation for the map series. By default, animation is
* disabled. Animation of map shapes is not at all supported in VML
* browsers.
* @private
*/
MapSeries.prototype.animate = function (init) {
var _a = this,
chart = _a.chart,
group = _a.group,
animation = animObject(this.options.animation);
if (chart.renderer.isSVG) {
// Initialize the animation
if (init) {
// Scale down the group and place it in the center
group.attr({
translateX: chart.plotLeft + chart.plotWidth / 2,
translateY: chart.plotTop + chart.plotHeight / 2,
scaleX: 0.001,
scaleY: 0.001
});
// Run the animation
}
else {
group.animate({
translateX: chart.plotLeft,
translateY: chart.plotTop,
scaleX: 1,
scaleY: 1
}, animation);
}
}
};
/**
* Animate in the new series. Depends on the drilldown.js module.
* @private
*/
MapSeries.prototype.animateDrilldown = function (init) {
var chart = this.chart,
group = this.group;
if (chart.renderer.isSVG) {
// Initialize the animation
if (init) {
// Scale down the group and place it in the center. This is a
// regression from <= v9.2, when it animated from the old point.
group.attr({
translateX: chart.plotLeft + chart.plotWidth / 2,
translateY: chart.plotTop + chart.plotHeight / 2,
scaleX: 0.1,
scaleY: 0.1,
opacity: 0.01
});
// Run the animation
}
else {
group.animate({
translateX: chart.plotLeft,
translateY: chart.plotTop,
scaleX: 1,
scaleY: 1,
opacity: 1
});
}
}
};
/**
* When drilling up, pull out the individual point graphics from the lower
* series and animate them into the origin point in the upper series.
* @private
*/
MapSeries.prototype.animateDrillupFrom = function () {
var chart = this.chart;
if (chart.renderer.isSVG) {
this.group.animate({
translateX: chart.plotLeft + chart.plotWidth / 2,
translateY: chart.plotTop + chart.plotHeight / 2,
scaleX: 0.1,
scaleY: 0.1,
opacity: 0.01
});
}
};
/**
* When drilling up, keep the upper series invisible until the lower series
* has moved into place.
* @private
*/
MapSeries.prototype.animateDrillupTo = function (init) {
ColumnSeries.prototype.animateDrillupTo.call(this, init);
};
MapSeries.prototype.clearBounds = function () {
this.points.forEach(function (point) {
delete point.bounds;
delete point.projectedPath;
});
delete this.bounds;
};
/**
* Allow a quick redraw by just translating the area group. Used for zooming
* and panning in capable browsers.
* @private
*/
MapSeries.prototype.doFullTranslate = function () {
return Boolean(this.isDirtyData ||
this.chart.isResizing ||
this.chart.renderer.isVML ||
!this.hasRendered);
};
/**
* Draw the data labels. Special for maps is the time that the data labels
* are drawn (after points), and the clipping of the dataLabelsGroup.
* @private
*/
MapSeries.prototype.drawMapDataLabels = function () {
Series.prototype.drawDataLabels.call(this);
if (this.dataLabelsGroup) {
this.dataLabelsGroup.clip(this.chart.clipRect);
}
};
/**
* Use the drawPoints method of column, that is able to handle simple
* shapeArgs. Extend it by assigning the tooltip position.
* @private
*/
MapSeries.prototype.drawPoints = function () {
var _this = this;
var _a = this,
chart = _a.chart,
group = _a.group,
svgTransform = _a.svgTransform;
var mapView = chart.mapView,
renderer = chart.renderer;
// Set a group that handles transform during zooming and panning in
// order to preserve clipping on series.group
if (!this.transformGroup) {
this.transformGroup = renderer.g().add(group);
this.transformGroup.survive = true;
}
// Draw the shapes again
if (this.doFullTranslate()) {
// Individual point actions.
if (chart.hasRendered && !chart.styledMode) {
this.points.forEach(function (point) {
// Restore state color on update/redraw (#3529)
if (point.shapeArgs) {
point.shapeArgs.fill = _this.pointAttribs(point, point.state).fill;
}
});
}
// Draw them in transformGroup
this.group = this.transformGroup;
ColumnSeries.prototype.drawPoints.apply(this);
this.group = group; // Reset
// Add class names
this.points.forEach(function (point) {
if (point.graphic) {
var className = '';
if (point.name) {
className +=
'highcharts-name-' +
point.name.replace(/ /g, '-').toLowerCase();
}
if (point.properties &&
point.properties['hc-key']) {
className +=
' highcharts-key-' +
point.properties['hc-key'].toLowerCase();
}
if (className) {
point.graphic.addClass(className);
}
// In styled mode, apply point colors by CSS
if (chart.styledMode) {
point.graphic.css(_this.pointAttribs(point, point.selected && 'select' || void 0));
}
}
});
}
// Apply the SVG transform
if (mapView && svgTransform) {
var strokeWidth_1 = pick(this.options[(this.pointAttrToOptions &&
this.pointAttrToOptions['stroke-width']) || 'borderWidth'], 1 // Styled mode
);
/*
Animate or move to the new zoom level. In order to prevent
flickering as the different transform components are set out of sync
(#5991), we run a fake animator attribute and set scale and
translation synchronously in the same step.
A possible improvement to the API would be to handle this in the
renderer or animation engine itself, to ensure that when we are
animating multiple properties, we make sure that each step for each
property is performed in the same step. Also, for symbols and for
transform properties, it should induce a single updateTransform and
symbolAttr call.
*/
var scale_1 = svgTransform.scaleX;
var flipFactor_1 = svgTransform.scaleY > 0 ? 1 : -1;
var transformGroup_1 = this.transformGroup;
if (renderer.globalAnimation && chart.hasRendered) {
var startTranslateX_1 = Number(transformGroup_1.attr('translateX')), startTranslateY_1 = Number(transformGroup_1.attr('translateY')), startScale_1 = Number(transformGroup_1.attr('scaleX'));
var step = function (now,
fx) {
var scaleStep = startScale_1 +
(scale_1 - startScale_1) * fx.pos;
transformGroup_1.attr({
translateX: (startTranslateX_1 +
(svgTransform.translateX - startTranslateX_1) * fx.pos),
translateY: (startTranslateY_1 +
(svgTransform.translateY - startTranslateY_1) * fx.pos),
scaleX: scaleStep,
scaleY: scaleStep * flipFactor_1
});
group.element.setAttribute('stroke-width', strokeWidth_1 / scaleStep);
};
transformGroup_1
.attr({ animator: 0 })
.animate({ animator: 1 }, { step: step });
// When dragging or first rendering, animation is off
}
else {
transformGroup_1.attr(svgTransform);
// Set the stroke-width directly on the group element so the
// children inherit it. We need to use setAttribute directly,
// because the stroke-widthSetter method expects a stroke color
// also to be set.
group.element.setAttribute('stroke-width', strokeWidth_1 / scale_1);
}
}
this.drawMapDataLabels();
};
/**
* Get the bounding box of all paths in the map combined.
*
*/
MapSeries.prototype.getProjectedBounds = function () {
if (!this.bounds) {
var MAX_VALUE_1 = Number.MAX_VALUE,
projection_1 = this.chart.mapView &&
this.chart.mapView.projection,
allBounds_1 = [];
// Find the bounding box of each point
(this.points || []).forEach(function (point) {
if (point.path || point.geometry) {
// @todo Try to puth these two conversions in
// MapPoint.applyOptions
if (typeof point.path === 'string') {
point.path = splitPath(point.path);
// Legacy one-dimensional array
}
else if (isArray(point.path) &&
point.path[0] === 'M') {
point.path = SVGRenderer.prototype.pathToSegments(point.path);
}
// The first time a map point is used, analyze its box
if (!point.bounds) {
var path = MapPoint.getProjectedPath(point,
projection_1),
properties = point.properties;
var x2_1 = -MAX_VALUE_1,
x1_1 = MAX_VALUE_1,
y2_1 = -MAX_VALUE_1,
y1_1 = MAX_VALUE_1,
validBounds_1;
path.forEach(function (seg) {
var x = seg[seg.length - 2];
var y = seg[seg.length - 1];
if (typeof x === 'number' &&
typeof y === 'number') {
x1_1 = Math.min(x1_1, x);
x2_1 = Math.max(x2_1, x);
y1_1 = Math.min(y1_1, y);
y2_1 = Math.max(y2_1, y);
validBounds_1 = true;
}
});
if (validBounds_1) {
// Cache point bounding box for use to position data
// labels, bubbles etc
var propMiddleX = (properties && properties['hc-middle-x']),
midX = (x1_1 + (x2_1 - x1_1) * pick(point.middleX,
isNumber(propMiddleX) ?
propMiddleX : 0.5)),
propMiddleY = (properties && properties['hc-middle-y']);
var middleYFraction = pick(point.middleY,
isNumber(propMiddleY) ? propMiddleY : 0.5);
// No geographic geometry, only path given => flip
if (!point.geometry) {
middleYFraction = 1 - middleYFraction;
}
var midY = y2_1 - (y2_1 - y1_1) * middleYFraction;
point.bounds = { midX: midX, midY: midY, x1: x1_1, y1: y1_1, x2: x2_1, y2: y2_1 };
point.labelrank = pick(point.labelrank,
// Bigger shape, higher rank
(x2_1 - x1_1) * (y2_1 - y1_1));
}
}
if (point.bounds) {
allBounds_1.push(point.bounds);
}
}
});
this.bounds = MapView.compositeBounds(allBounds_1);
}
return this.bounds;
};
/**
* Define hasData function for non-cartesian series. Returns true if the
* series has points at all.
* @private
*/
MapSeries.prototype.hasData = function () {
return !!this.processedXData.length; // != 0
};
/**
* Get presentational attributes. In the maps series this runs in both
* styled and non-styled mode, because colors hold data when a colorAxis is
* used.
* @private
*/
MapSeries.prototype.pointAttribs = function (point, state) {
var _a = point.series.chart,
mapView = _a.mapView,
styledMode = _a.styledMode;
var attr = styledMode ?
this.colorAttribs(point) :
ColumnSeries.prototype.pointAttribs.call(this,
point,
state);
// Individual stroke width
var pointStrokeWidth = point.options[(this.pointAttrToOptions &&
this.pointAttrToOptions['stroke-width']) || 'borderWidth'];
if (pointStrokeWidth && mapView) {
pointStrokeWidth /= mapView.getScale();
}
// In order for dash style to avoid being scaled, set the transformed
// stroke width on the item
if (attr.dashstyle && mapView && this.options.borderWidth) {
pointStrokeWidth = this.options.borderWidth / mapView.getScale();
}
attr['stroke-width'] = pick(pointStrokeWidth,
// By default set the stroke-width on the group element and let all
// point graphics inherit. That way we don't have to iterate over
// all points to update the stroke-width on zooming.
'inherit');
return attr;
};
/**
* Extend setData to join in mapData. If the allAreas option is true, all
* areas from the mapData are used, and those that don't correspond to a
* data value are given null values.
* @private
*/
MapSeries.prototype.setData = function (data, redraw, animation, updatePoints) {
var options = this.options,
chartOptions = this.chart.options.chart,
globalMapData = chartOptions && chartOptions.map,
mapData = options.mapData,
joinBy = this.joinBy,
pointArrayMap = options.keys || this.pointArrayMap,
dataUsed = [],
mapMap = {},
mapPoint,
mapTransforms = this.chart.mapTransforms,
props,
i;
// Collect mapData from chart options if not defined on series
if (!mapData && globalMapData) {
mapData = typeof globalMapData === 'string' ?
maps[globalMapData] :
globalMapData;
}
// Pick up numeric values, add index
// Convert Array point definitions to objects using pointArrayMap
if (data) {
data.forEach(function (val, i) {
var ix = 0;
if (isNumber(val)) {
data[i] = {
value: val
};
}
else if (isArray(val)) {
data[i] = {};
// Automatically copy first item to hc-key if there is
// an extra leading string
if (!options.keys &&
val.length > pointArrayMap.length &&
typeof val[0] === 'string') {
data[i]['hc-key'] = val[0];
++ix;
}
// Run through pointArrayMap and what's left of the
// point data array in parallel, copying over the values
for (var j = 0; j < pointArrayMap.length; ++j, ++ix) {
if (pointArrayMap[j] &&
typeof val[ix] !== 'undefined') {
if (pointArrayMap[j].indexOf('.') > 0) {
MapPoint.prototype.setNestedProperty(data[i], val[ix], pointArrayMap[j]);
}
else {
data[i][pointArrayMap[j]] =
val[ix];
}
}
}
}
if (joinBy && joinBy[0] === '_i') {
data[i]._i = i;
}
});
}
// this.getBox(data as any);
// Pick up transform definitions for chart
this.chart.mapTransforms = mapTransforms =
chartOptions.mapTransforms ||
mapData && mapData['hc-transform'] ||
mapTransforms;
// Cache cos/sin of transform rotation angle
if (mapTransforms) {
objectEach(mapTransforms, function (transform) {
if (transform.rotation) {
transform.cosAngle = Math.cos(transform.rotation);
transform.sinAngle = Math.sin(transform.rotation);
}
});
}
if (mapData) {
if (mapData.type === 'FeatureCollection') {
this.mapTitle = mapData.title;
mapData = H.geojson(mapData, this.type, this);
}
this.mapData = mapData;
this.mapMap = {};
for (i = 0; i < mapData.length; i++) {
mapPoint = mapData[i];
props = mapPoint.properties;
mapPoint._i = i;
// Copy the property over to root for faster access
if (joinBy[0] && props && props[joinBy[0]]) {
mapPoint[joinBy[0]] = props[joinBy[0]];
}
mapMap[mapPoint[joinBy[0]]] = mapPoint;
}
this.mapMap = mapMap;
// Registered the point codes that actually hold data
if (data && joinBy[1]) {
var joinKey_1 = joinBy[1];
data.forEach(function (pointOptions) {
var mapKey = getNestedProperty(joinKey_1,
pointOptions);
if (mapMap[mapKey]) {
dataUsed.push(mapMap[mapKey]);
}
});
}
if (options.allAreas) {
// this.getBox(mapData);
data = data || [];
// Registered the point codes that actually hold data
if (joinBy[1]) {
var joinKey_2 = joinBy[1];
data.forEach(function (pointOptions) {
dataUsed.push(getNestedProperty(joinKey_2, pointOptions));
});
}
// Add those map points that don't correspond to data, which
// will be drawn as null points
dataUsed = ('|' + dataUsed.map(function (point) {
return point && point[joinBy[0]];
}).join('|') + '|'); // Faster than array.indexOf
mapData.forEach(function (mapPoint) {
if (!joinBy[0] ||
dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) {
data.push(merge(mapPoint, { value: null }));
// #5050 - adding all areas causes the update
// optimization of setData to kick in, even though
// the point order has changed
updatePoints = false;
}
});
} /* else {
this.getBox(dataUsed); // Issue #4784
} */
}
Series.prototype.setData.call(this, data, redraw, animation, updatePoints);
this.processData();
this.generatePoints();
};
/**
* Extend setOptions by picking up the joinBy option and applying it to a
* series property.
* @private
*/
MapSeries.prototype.setOptions = function (itemOptions) {
var options = Series.prototype.setOptions.call(this,
itemOptions),
joinBy = options.joinBy,
joinByNull = joinBy === null;
if (joinByNull) {
joinBy = '_i';
}
joinBy = this.joinBy = splat(joinBy);
if (!joinBy[1]) {
joinBy[1] = joinBy[0];
}
return options;
};
/**
* Add the path option for data points. Find the max value for color
* calculation.
* @private
*/
MapSeries.prototype.translate = function () {
var series = this,
doFullTranslate = series.doFullTranslate(),
mapView = this.chart.mapView,
projection = mapView && mapView.projection;
// Recalculate box on updated data
if (this.chart.hasRendered && (this.isDirtyData || !this.hasRendered)) {
this.processData();
this.generatePoints();
delete this.bounds;
this.getProjectedBounds();
}
// Calculate the SVG transform
var svgTransform;
if (mapView) {
var scale = mapView.getScale();
var _a = mapView.projection.forward(mapView.center),
x = _a[0],
y = _a[1];
// When dealing with unprojected coordinates, y axis is flipped.
var flipFactor = mapView.projection.hasCoordinates ? -1 : 1;
var translateX = this.chart.plotWidth / 2 - x * scale,
translateY = this.chart.plotHeight / 2 - y * scale * flipFactor;
svgTransform = {
scaleX: scale,
scaleY: scale * flipFactor,
translateX: translateX,
translateY: translateY
};
this.svgTransform = svgTransform;
}
series.points.forEach(function (point) {
// Record the middle point (loosely based on centroid),
// determined by the middleX and middleY options.
if (svgTransform &&
point.bounds &&
isNumber(point.bounds.midX) &&
isNumber(point.bounds.midY)) {
point.plotX = point.bounds.midX * svgTransform.scaleX +
svgTransform.translateX;
point.plotY = point.bounds.midY * svgTransform.scaleY +
svgTransform.translateY;
}
if (doFullTranslate) {
point.shapeType = 'path';
point.shapeArgs = {
d: MapPoint.getProjectedPath(point, projection)
};
}
});
fireEvent(series, 'afterTranslate');
};
/**
* The map series is used for basic choropleth maps, where each map area has
* a color based on its value.
*
* @sample maps/demo/all-maps/
* Choropleth map
*
* @extends plotOptions.scatter
* @excluding marker, cluster
* @product highmaps
* @optionparent plotOptions.map
*/
MapSeries.defaultOptions = merge(ScatterSeries.defaultOptions, {
animation: false,
dataLabels: {
crop: false,
formatter: function () {
var numberFormatter = this.series.chart.numberFormatter;
var value = this.point.value;
return isNumber(value) ? numberFormatter(value, -1) : '';
},
inside: true,
overflow: false,
padding: 0,
verticalAlign: 'middle'
},
/**
* @ignore-option
*
* @private
*/
marker: null,
/**
* The color to apply to null points.
*
* In styled mode, the null point fill is set in the
* `.highcharts-null-point` class.
*
* @sample maps/demo/all-areas-as-null/
* Null color
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*
* @private
*/
nullColor: "#f7f7f7" /* neutralColor3 */,
/**
* Whether to allow pointer interaction like tooltips and mouse events
* on null points.
*
* @type {boolean}
* @since 4.2.7
* @apioption plotOptions.map.nullInteraction
*
* @private
*/
stickyTracking: false,
tooltip: {
followPointer: true,
pointFormat: '{point.name}: {point.value}<br/>'
},
/**
* @ignore-option
*
* @private
*/
turboThreshold: 0,
/**
* Whether all areas of the map defined in `mapData` should be rendered.
* If `true`, areas which don't correspond to a data point, are rendered
* as `null` points. If `false`, those areas are skipped.
*
* @sample maps/plotoptions/series-allareas-false/
* All areas set to false
*
* @type {boolean}
* @default true
* @product highmaps
* @apioption plotOptions.series.allAreas
*
* @private
*/
allAreas: true,
/**
* The border color of the map areas.
*
* In styled mode, the border stroke is given in the `.highcharts-point`
* class.
*
* @sample {highmaps} maps/plotoptions/series-border/
* Borders demo
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #cccccc
* @product highmaps
* @apioption plotOptions.series.borderColor
*
* @private
*/
borderColor: "#cccccc" /* neutralColor20 */,
/**
* The border width of each map area.
*
* In styled mode, the border stroke width is given in the
* `.highcharts-point` class.
*
* @sample maps/plotoptions/series-border/
* Borders demo
*
* @type {number}
* @default 1
* @product highmaps
* @apioption plotOptions.series.borderWidth
*
* @private
*/
borderWidth: 1,
/**
* @type {string}
* @default value
* @apioption plotOptions.map.colorKey
*/
/**
* What property to join the `mapData` to the value data. For example,
* if joinBy is "code", the mapData items with a specific code is merged
* into the data with the same code. For maps loaded from GeoJSON, the
* keys may be held in each point's `properties` object.
*
* The joinBy option can also be an array of two values, where the first
* points to a key in the `mapData`, and the second points to another
* key in the `data`.
*
* When joinBy is `null`, the map items are joined by their position in
* the array, which performs much better in maps with many data points.
* This is the recommended option if you are printing more than a
* thousand data points and have a backend that can preprocess the data
* into a parallel array of the mapData.
*
* @sample maps/plotoptions/series-border/
* Joined by "code"
* @sample maps/demo/geojson/
* GeoJSON joined by an array
* @sample maps/series/joinby-null/
* Simple data joined by null
*
* @type {string|Array<string>}
* @default hc-key
* @product highmaps
* @apioption plotOptions.series.joinBy
*
* @private
*/
joinBy: 'hc-key',
/**
* Define the z index of the series.
*
* @type {number}
* @product highmaps
* @apioption plotOptions.series.zIndex
*/
/**
* @apioption plotOptions.series.states
*
* @private
*/
states: {
/**
* @apioption plotOptions.series.states.hover
*/
hover: {
/** @ignore-option */
halo: null,
/**
* The color of the shape in this state.
*
* @sample maps/plotoptions/series-states-hover/
* Hover options
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highmaps
* @apioption plotOptions.series.states.hover.color
*/
/**
* The border color of the point in this state.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highmaps
* @apioption plotOptions.series.states.hover.borderColor
*/
/**
* The border width of the point in this state
*
* @type {number}
* @product highmaps
* @apioption plotOptions.series.states.hover.borderWidth
*/
/**
* The relative brightness of the point when hovered, relative
* to the normal point color.
*
* @type {number}
* @product highmaps
* @default 0.2
* @apioption plotOptions.series.states.hover.brightness
*/
brightness: 0.2
},
/**
* @apioption plotOptions.series.states.normal
*/
normal: {
/**
* @productdesc {highmaps}
* The animation adds some latency in order to reduce the effect
* of flickering when hovering in and out of for example an
* uneven coastline.
*
* @sample {highmaps} maps/plotoptions/series-states-animation-false/
* No animation of fill color
*
* @apioption plotOptions.series.states.normal.animation
*/
animation: true
},
/**
* @apioption plotOptions.series.states.select
*/
select: {
/**
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @default #cccccc
* @product highmaps
* @apioption plotOptions.series.states.select.color
*/
color: "#cccccc" /* neutralColor20 */
},
inactive: {
opacity: 1
}
}
});
return MapSeries;
}(ScatterSeries));
extend(MapSeries.prototype, {
type: 'map',
axisTypes: ColorMapMixin.SeriesMixin.axisTypes,
colorAttribs: ColorMapMixin.SeriesMixin.colorAttribs,
colorKey: ColorMapMixin.SeriesMixin.colorKey,
// When tooltip is not shared, this series (and derivatives) requires
// direct touch/hover. KD-tree does not apply.
directTouch: true,
// We need the points' bounding boxes in order to draw the data labels,
// so we skip it now and call it from drawPoints instead.
drawDataLabels: noop,
// No graph for the map series
drawGraph: noop,
drawLegendSymbol: LegendSymbol.drawRectangle,
forceDL: true,
getCenter: CU.getCenter,
getExtremesFromAll: true,
getSymbol: ColorMapMixin.SeriesMixin.getSymbol,
isCartesian: false,
parallelArrays: ColorMapMixin.SeriesMixin.parallelArrays,
pointArrayMap: ColorMapMixin.SeriesMixin.pointArrayMap,
pointClass: MapPoint,
// X axis and Y axis must have same translation slope
preserveAspectRatio: true,
searchPoint: noop,
trackerGroups: ColorMapMixin.SeriesMixin.trackerGroups,
// Get axis extremes from paths, not values
useMapGeometry: true
});
SeriesRegistry.registerSeriesType('map', MapSeries);
/* *
*
* Default Export
*
* */
/* *
*
* API Options
*
* */
/**
* A map data object containing a `geometry` or `path` definition and optionally
* additional properties to join in the `data` as per the `joinBy` option.
*
* @sample maps/demo/category-map/
* Map data and joinBy
*
* @type {Array<Highcharts.SeriesMapDataOptions>|*}
* @product highmaps
* @apioption series.mapData
*/
/**
* A `map` series. If the [type](#series.map.type) option is not specified, it
* is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.map
* @excluding dataParser, dataURL, marker
* @product highmaps
* @apioption series.map
*/
/**
* An array of data points for the series. For the `map` series type, points can
* be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `value` options. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `[hc-key, value]`. Example:
* ```js
* data: [
* ['us-ny', 0],
* ['us-mi', 5],
* ['us-tx', 3],
* ['us-ak', 5]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.map.turboThreshold),
* this option is not available.
* ```js
* data: [{
* value: 6,
* name: "Point2",
* color: "#00FF00"
* }, {
* value: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<number|Array<string,(number|null)>|null|*>}
* @product highmaps
* @apioption series.map.data
*/
/**
* Individual color for the point. By default the color is either used
* to denote the value, or pulled from the global `colors` array.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highmaps
* @apioption series.map.data.color
*/
/**
* Individual data label for each point. The options are the same as
* the ones for [plotOptions.series.dataLabels](
* #plotOptions.series.dataLabels).
*
* @sample maps/series/data-datalabels/
* Disable data labels for individual areas
*
* @type {Highcharts.DataLabelsOptions}
* @product highmaps
* @apioption series.map.data.dataLabels
*/
/**
* The `id` of a series in the [drilldown.series](#drilldown.series)
* array to use for a drilldown for this point.
*
* @sample maps/demo/map-drilldown/
* Basic drilldown
*
* @type {string}
* @product highmaps
* @apioption series.map.data.drilldown
*/
/**
* For map and mapline series types, the geometry of a point.
*
* To achieve a better separation between the structure and the data,
* it is recommended to use `mapData` to define the geometry instead
* of defining it on the data points themselves.
*
* The geometry object is compatible to that of a `feature` in geoJSON, so
* features of geoJSON can be passed directly into the `data`, optionally
* after first filtering and processing it.
*
* @sample maps/series/data-geometry/
* Geometry defined in data
*
* @type {Object}
* @since 9.3.0
* @product highmaps
* @apioption series.map.data.geometry
*/
/**
* The geometry type. Can be one of `LineString`, `Polygon`, `MultiLineString`
* or `MultiPolygon`.
*
* @type {string}
* @since 9.3.0
* @product highmaps
* @validvalue ["LineString", "Polygon", "MultiLineString", "MultiPolygon"]
* @apioption series.map.data.geometry.type
*/
/**
* The geometry coordinates in terms of arrays of `[longitude, latitude]`, or
* a two dimensional array of the same. The dimensionality must comply with the
* `type`.
*
* @type {Array<LonLatArray>|Array<Array<LonLatArray>>}
* @since 9.3.0
* @product highmaps
* @apioption series.map.data.geometry.coordinates
*/
/**
* An id for the point. This can be used after render time to get a
* pointer to the point object through `chart.get()`.
*
* @sample maps/series/data-id/
* Highlight a point by id
*
* @type {string}
* @product highmaps
* @apioption series.map.data.id
*/
/**
* When data labels are laid out on a map, Highmaps runs a simplified
* algorithm to detect collision. When two labels collide, the one with
* the lowest rank is hidden. By default the rank is computed from the
* area.
*
* @type {number}
* @product highmaps
* @apioption series.map.data.labelrank
*/
/**
* The relative mid point of an area, used to place the data label.
* Ranges from 0 to 1\. When `mapData` is used, middleX can be defined
* there.
*
* @type {number}
* @default 0.5
* @product highmaps
* @apioption series.map.data.middleX
*/
/**
* The relative mid point of an area, used to place the data label.
* Ranges from 0 to 1\. When `mapData` is used, middleY can be defined
* there.
*
* @type {number}
* @default 0.5
* @product highmaps
* @apioption series.map.data.middleY
*/
/**
* The name of the point as shown in the legend, tooltip, dataLabel
* etc.
*
* @sample maps/series/data-datalabels/
* Point names
*
* @type {string}
* @product highmaps
* @apioption series.map.data.name
*/
/**
* For map and mapline series types, the SVG path for the shape. For
* compatibily with old IE, not all SVG path definitions are supported,
* but M, L and C operators are safe.
*
* To achieve a better separation between the structure and the data,
* it is recommended to use `mapData` to define that paths instead
* of defining them on the data points themselves.
*
* For providing true geographical shapes based on longitude and latitude, use
* the `geometry` option instead.
*
* @sample maps/series/data-path/
* Paths defined in data
*
* @type {string}
* @product highmaps
* @apioption series.map.data.path
*/
/**
* The numeric value of the data point.
*
* @type {number|null}
* @product highmaps
* @apioption series.map.data.value
*/
/**
* Individual point events
*
* @extends plotOptions.series.point.events
* @product highmaps
* @apioption series.map.data.events
*/
''; // adds doclets above to the transpiled file
return MapSeries;
});
_registerModule(_modules, 'Series/MapLine/MapLineSeries.js', [_modules['Series/Map/MapSeries.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (MapSeries, SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Series = SeriesRegistry.series;
var extend = U.extend,
merge = U.merge;
/* *
*
* Class
*
* */
/**
* @private
* @class
* @name Highcharts.seriesTypes.mapline
*
* @augments Highcharts.Series
*/
var MapLineSeries = /** @class */ (function (_super) {
__extends(MapLineSeries, _super);
function MapLineSeries() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* *
*
* Properties
*
* */
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* Get presentational attributes
* @private
* @function Highcharts.seriesTypes.mapline#pointAttribs
*/
MapLineSeries.prototype.pointAttribs = function (point, state) {
var attr = MapSeries.prototype.pointAttribs.call(this,
point,
state);
// The difference from a map series is that the stroke takes the
// point color
attr.fill = this.options.fillColor;
return attr;
};
/**
* A mapline series is a special case of the map series where the value
* colors are applied to the strokes rather than the fills. It can also be
* used for freeform drawing, like dividers, in the map.
*
* @sample maps/demo/mapline-mappoint/
* Mapline and map-point chart
*
* @extends plotOptions.map
* @product highmaps
* @optionparent plotOptions.mapline
*/
MapLineSeries.defaultOptions = merge(MapSeries.defaultOptions, {
/**
* The width of the map line.
*/
lineWidth: 1,
/**
* Fill color for the map line shapes
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
fillColor: 'none'
});
return MapLineSeries;
}(MapSeries));
extend(MapLineSeries.prototype, {
type: 'mapline',
colorProp: 'stroke',
drawLegendSymbol: Series.prototype.drawLegendSymbol,
pointAttrToOptions: {
'stroke': 'color',
'stroke-width': 'lineWidth'
}
});
SeriesRegistry.registerSeriesType('mapline', MapLineSeries);
/* *
*
* Default Export
*
* */
/* *
*
* API Options
*
* */
/**
* A `mapline` series. If the [type](#series.mapline.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.mapline
* @excluding dataParser, dataURL, marker
* @product highmaps
* @apioption series.mapline
*/
/**
* An array of data points for the series. For the `mapline` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values
* will be interpreted as `value` options. Example:
*
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond
* to `[hc-key, value]`. Example:
*
* ```js
* data: [
* ['us-ny', 0],
* ['us-mi', 5],
* ['us-tx', 3],
* ['us-ak', 5]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of data
* points exceeds the series' [turboThreshold](#series.map.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* value: 6,
* name: "Point2",
* color: "#00FF00"
* }, {
* value: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<number|Array<string,(number|null)>|null|*>}
* @extends series.map.data
* @excluding drilldown
* @product highmaps
* @apioption series.mapline.data
*/
''; // adds doclets above to transpiled file
return MapLineSeries;
});
_registerModule(_modules, 'Series/MapPoint/MapPointPoint.js', [_modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var ScatterSeries = SeriesRegistry.seriesTypes.scatter;
var isNumber = U.isNumber,
merge = U.merge;
/* *
*
* Class
*
* */
var MapPointPoint = /** @class */ (function (_super) {
__extends(MapPointPoint, _super);
function MapPointPoint() {
/* *
*
* Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
_this.options = void 0;
_this.series = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
MapPointPoint.prototype.applyOptions = function (options, x) {
var mergedOptions = (typeof options.lat !== 'undefined' &&
typeof options.lon !== 'undefined' ?
merge(options,
this.series.chart.fromLatLonToPoint(options)) :
options);
return _super.prototype.applyOptions.call(this, mergedOptions, x);
};
MapPointPoint.prototype.isValid = function () {
return Boolean(this.options.geometry ||
(isNumber(this.x) && isNumber(this.y)));
};
return MapPointPoint;
}(ScatterSeries.prototype.pointClass));
/* *
*
* Default Export
*
* */
return MapPointPoint;
});
_registerModule(_modules, 'Series/MapPoint/MapPointSeries.js', [_modules['Core/Globals.js'], _modules['Series/MapPoint/MapPointPoint.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (H, MapPointPoint, SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var noop = H.noop;
var ScatterSeries = SeriesRegistry.seriesTypes.scatter;
var extend = U.extend,
fireEvent = U.fireEvent,
isNumber = U.isNumber,
merge = U.merge;
/* *
*
* Class
*
* */
/**
* @private
* @class
* @name Highcharts.seriesTypes.mappoint
*
* @augments Highcharts.Series
*/
var MapPointSeries = /** @class */ (function (_super) {
__extends(MapPointSeries, _super);
function MapPointSeries() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* *
*
* Properties
*
* */
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
MapPointSeries.prototype.drawDataLabels = function () {
_super.prototype.drawDataLabels.call(this);
if (this.dataLabelsGroup) {
this.dataLabelsGroup.clip(this.chart.clipRect);
}
};
MapPointSeries.prototype.translate = function () {
var _this = this;
var mapView = this.chart.mapView;
if (!this.processedXData) {
this.processData();
}
this.generatePoints();
// Create map based translation
if (mapView) {
var _a = mapView.projection,
forward_1 = _a.forward,
hasCoordinates_1 = _a.hasCoordinates;
this.points.forEach(function (p) {
var _a = p.x,
x = _a === void 0 ? void 0 : _a,
_b = p.y,
y = _b === void 0 ? void 0 : _b;
var geometry = p.options.geometry,
coordinates = (geometry &&
geometry.type === 'Point' &&
geometry.coordinates);
if (coordinates) {
var xy = forward_1(coordinates);
x = xy[0];
y = xy[1];
// Map bubbles getting geometry from shape
}
else if (p.bounds) {
x = p.bounds.midX;
y = p.bounds.midY;
}
if (isNumber(x) && isNumber(y)) {
var plotCoords = mapView.projectedUnitsToPixels({ x: x,
y: y });
p.plotX = plotCoords.x;
p.plotY = hasCoordinates_1 ?
plotCoords.y :
_this.chart.plotHeight - plotCoords.y;
}
else {
p.plotX = void 0;
p.plotY = void 0;
}
p.isInside = _this.isPointInside(p);
// Find point zone
p.zone = _this.zones.length ? p.getZone() : void 0;
});
}
fireEvent(this, 'afterTranslate');
};
/**
* A mappoint series is a special form of scatter series where the points
* can be laid out in map coordinates on top of a map.
*
* @sample maps/demo/mapline-mappoint/
* Map-line and map-point series.
*
* @extends plotOptions.scatter
* @product highmaps
* @optionparent plotOptions.mappoint
*/
MapPointSeries.defaultOptions = merge(ScatterSeries.defaultOptions, {
dataLabels: {
crop: false,
defer: false,
enabled: true,
formatter: function () {
return this.point.name;
},
overflow: false,
style: {
/** @internal */
color: "#000000" /* neutralColor100 */
}
}
});
return MapPointSeries;
}(ScatterSeries));
extend(MapPointSeries.prototype, {
type: 'mappoint',
axisTypes: ['colorAxis'],
forceDL: true,
isCartesian: false,
pointClass: MapPointPoint,
searchPoint: noop,
useMapGeometry: true // #16534
});
SeriesRegistry.registerSeriesType('mappoint', MapPointSeries);
/* *
*
* Default Export
*
* */
/* *
*
* API Options
*
* */
/**
* A `mappoint` series. If the [type](#series.mappoint.type) option
* is not specified, it is inherited from [chart.type](#chart.type).
*
*
* @extends series,plotOptions.mappoint
* @excluding dataParser, dataURL
* @product highmaps
* @apioption series.mappoint
*/
/**
* An array of data points for the series. For the `mappoint` series
* type, points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` and `pointInterval` given in the series options. If the axis
* has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond
* to `[hc-key, value]`. Example:
*
* ```js
* data: [
* ['us-ny', 0],
* ['us-mi', 5],
* ['us-tx', 3],
* ['us-ak', 5]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.mappoint.turboThreshold),
* this option is not available.
* ```js
* data: [{
* x: 1,
* y: 7,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 4,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<number|Array<number,(number|null)>|null|*>}
* @extends series.map.data
* @excluding labelrank, middleX, middleY, path, value
* @product highmaps
* @apioption series.mappoint.data
*/
/**
* The geometry of a point.
*
* To achieve a better separation between the structure and the data,
* it is recommended to use `mapData` to define the geometry instead
* of defining it on the data points themselves.
*
* The geometry object is compatible to that of a `feature` in geoJSON, so
* features of geoJSON can be passed directly into the `data`, optionally
* after first filtering and processing it.
*
* @sample maps/series/data-geometry/
* geometry defined in data
*
* @type {Object}
* @since 9.3.0
* @product highmaps
* @apioption series.mappoint.data.geometry
*/
/**
* The geometry type, which in case of the `mappoint` series is always `Point`.
*
* @type {string}
* @since 9.3.0
* @product highmaps
* @validvalue ["Point"]
* @apioption series.mappoint.data.geometry.type
*/
/**
* The geometry coordinates in terms of `[longitude, latitude]`.
*
* @type {Highcharts.LonLatArray}
* @since 9.3.0
* @product highmaps
* @apioption series.mappoint.data.geometry.coordinates
*/
/**
* The latitude of the point. Must be combined with the `lon` option
* to work. Overrides `x` and `y` values.
*
* @sample {highmaps} maps/demo/mappoint-latlon/
* Point position by lat/lon
*
* @type {number}
* @since 1.1.0
* @product highmaps
* @apioption series.mappoint.data.lat
*/
/**
* The longitude of the point. Must be combined with the `lon` option
* to work. Overrides `x` and `y` values.
*
* @sample {highmaps} maps/demo/mappoint-latlon/
* Point position by lat/lon
*
* @type {number}
* @since 1.1.0
* @product highmaps
* @apioption series.mappoint.data.lon
*/
/**
* The x coordinate of the point in terms of the map path coordinates.
*
* @sample {highmaps} maps/demo/mapline-mappoint/
* Map point demo
*
* @type {number}
* @product highmaps
* @apioption series.mappoint.data.x
*/
/**
* The x coordinate of the point in terms of the map path coordinates.
*
* @sample {highmaps} maps/demo/mapline-mappoint/
* Map point demo
*
* @type {number|null}
* @product highmaps
* @apioption series.mappoint.data.y
*/
''; // adds doclets above to transpiled file
return MapPointSeries;
});
_registerModule(_modules, 'Series/Bubble/BubbleLegendDefaults.js', [], function () {
/* *
*
* (c) 2010-2021 Highsoft AS
*
* Author: Paweł Potaczek
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
/* *
*
* Constants
*
* */
/**
* The bubble legend is an additional element in legend which
* presents the scale of the bubble series. Individual bubble ranges
* can be defined by user or calculated from series. In the case of
* automatically calculated ranges, a 1px margin of error is
* permitted.
*
* @since 7.0.0
* @product highcharts highstock highmaps
* @requires highcharts-more
* @optionparent legend.bubbleLegend
*/
var BubbleLegendDefaults = {
/**
* The color of the ranges borders,
can be also defined for an
* individual range.
*
* @sample highcharts/bubble-legend/similartoseries/
* Similar look to the bubble series
* @sample highcharts/bubble-legend/bordercolor/
* Individual bubble border color
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
borderColor: void 0,
/**
* The width of the ranges borders in pixels,
can be also
* defined for an individual range.
*/
borderWidth: 2,
/**
* An additional class name to apply to the bubble legend'
* circle graphical elements. This option does not replace
* default class names of the graphical element.
*
* @sample {highcharts} highcharts/css/bubble-legend/
* Styling by CSS
*
* @type {string}
*/
className: void 0,
/**
* The main color of the bubble legend. Applies to ranges,
if
* individual color is not defined.
*
* @sample highcharts/bubble-legend/similartoseries/
* Similar look to the bubble series
* @sample highcharts/bubble-legend/color/
* Individual bubble color
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
color: void 0,
/**
* An additional class name to apply to the bubble legend's
* connector graphical elements. This option does not replace
* default class names of the graphical element.
*
* @sample {highcharts} highcharts/css/bubble-legend/
* Styling by CSS
*
* @type {string}
*/
connectorClassName: void 0,
/**
* The color of the connector,
can be also defined
* for an individual range.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
connectorColor: void 0,
/**
* The length of the connectors in pixels. If labels are
* centered,
the distance is reduced to 0.
*
* @sample highcharts/bubble-legend/connectorandlabels/
* Increased connector length
*/
connectorDistance: 60,
/**
* The width of the connectors in pixels.
*
* @sample highcharts/bubble-legend/connectorandlabels/
* Increased connector width
*/
connectorWidth: 1,
/**
* Enable or disable the bubble legend.
*/
enabled: false,
/**
* Options for the bubble legend labels.
*/
labels: {
/**
* An additional class name to apply to the bubble legend
* label graphical elements. This option does not replace
* default class names of the graphical element.
*
* @sample {highcharts} highcharts/css/bubble-legend/
* Styling by CSS
*
* @type {string}
*/
className: void 0,
/**
* Whether to allow data labels to overlap.
*/
allowOverlap: false,
/**
* A format string for the bubble legend labels. Available
* variables are the same as for `formatter`.
*
* @sample highcharts/bubble-legend/format/
* Add a unit
*
* @type {string}
*/
format: '',
/**
* Available `this` properties are:
*
* - `this.value`: The bubble value.
*
* - `this.radius`: The radius of the bubble range.
*
* - `this.center`: The center y position of the range.
*
* @type {Highcharts.FormatterCallbackFunction<Highcharts.BubbleLegendFormatterContextObject>}
*/
formatter: void 0,
/**
* The alignment of the labels compared to the bubble
* legend. Can be one of `left`,
`center` or `right`.
*
* @sample highcharts/bubble-legend/connectorandlabels/
* Labels on left
*
* @type {Highcharts.AlignValue}
*/
align: 'right',
/**
* CSS styles for the labels.
*
* @type {Highcharts.CSSObject}
*/
style: {
/** @ignore-option */
fontSize: '10px',
/** @ignore-option */
color: "#000000" /* neutralColor100 */
},
/**
* The x position offset of the label relative to the
* connector.
*/
x: 0,
/**
* The y position offset of the label relative to the
* connector.
*/
y: 0
},
/**
* Miximum bubble legend range size. If values for ranges are
* not specified,
the `minSize` and the `maxSize` are calculated
* from bubble series.
*/
maxSize: 60,
/**
* Minimum bubble legend range size. If values for ranges are
* not specified,
the `minSize` and the `maxSize` are calculated
* from bubble series.
*/
minSize: 10,
/**
* The position of the bubble legend in the legend.
* @sample highcharts/bubble-legend/connectorandlabels/
* Bubble legend as last item in legend
*/
legendIndex: 0,
/**
* Options for specific range. One range consists of bubble,
* label and connector.
*
* @sample highcharts/bubble-legend/ranges/
* Manually defined ranges
* @sample highcharts/bubble-legend/autoranges/
* Auto calculated ranges
*
* @type {Array<*>}
*/
ranges: {
/**
* Range size value,
similar to bubble Z data.
* @type {number}
*/
value: void 0,
/**
* The color of the border for individual range.
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
borderColor: void 0,
/**
* The color of the bubble for individual range.
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
color: void 0,
/**
* The color of the connector for individual range.
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
connectorColor: void 0
},
/**
* Whether the bubble legend range value should be represented
* by the area or the width of the bubble. The default,
area,
* corresponds best to the human perception of the size of each
* bubble.
*
* @sample highcharts/bubble-legend/ranges/
* Size by width
*
* @type {Highcharts.BubbleSizeByValue}
*/
sizeBy: 'area',
/**
* When this is true,
the absolute value of z determines the
* size of the bubble. This means that with the default
* zThreshold of 0,
a bubble of value -1 will have the same size
* as a bubble of value 1,
while a bubble of value 0 will have a
* smaller size according to minSize.
*/
sizeByAbsoluteValue: false,
/**
* Define the visual z index of the bubble legend.
*/
zIndex: 1,
/**
* Ranges with with lower value than zThreshold,
are skipped.
*/
zThreshold: 0
};
/* *
*
* Default Export
*
* */
return BubbleLegendDefaults;
});
_registerModule(_modules, 'Series/Bubble/BubbleLegendItem.js', [_modules['Core/Color/Color.js'], _modules['Core/FormatUtilities.js'], _modules['Core/Globals.js'], _modules['Core/Utilities.js']], function (Color, F, H, U) {
/* *
*
* (c) 2010-2021 Highsoft AS
*
* Author: Paweł Potaczek
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var color = Color.parse;
var noop = H.noop;
var arrayMax = U.arrayMax,
arrayMin = U.arrayMin,
isNumber = U.isNumber,
merge = U.merge,
pick = U.pick,
stableSort = U.stableSort;
/**
* @interface Highcharts.BubbleLegendFormatterContextObject
*/ /**
* The center y position of the range.
* @name Highcharts.BubbleLegendFormatterContextObject#center
* @type {number}
*/ /**
* The radius of the bubble range.
* @name Highcharts.BubbleLegendFormatterContextObject#radius
* @type {number}
*/ /**
* The bubble value.
* @name Highcharts.BubbleLegendFormatterContextObject#value
* @type {number}
*/
''; // detach doclets above
/* *
*
* Class
*
* */
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* BubbleLegend class.
*
* @private
* @class
* @name Highcharts.BubbleLegend
* @param {Highcharts.LegendBubbleLegendOptions} options
* Options of BubbleLegendItem.
*
* @param {Highcharts.Legend} legend
* Legend of item.
*/
var BubbleLegendItem = /** @class */ (function () {
function BubbleLegendItem(options, legend) {
this.chart = void 0;
this.fontMetrics = void 0;
this.legend = void 0;
this.legendGroup = void 0;
this.legendItem = void 0;
this.legendItemHeight = void 0;
this.legendItemWidth = void 0;
this.legendSymbol = void 0;
this.maxLabel = void 0;
this.movementX = void 0;
this.ranges = void 0;
this.selected = void 0;
this.visible = void 0;
this.symbols = void 0;
this.options = void 0;
this.setState = noop;
this.init(options, legend);
}
/**
* Create basic bubbleLegend properties similar to item in legend.
*
* @private
* @function Highcharts.BubbleLegend#init
* @param {Highcharts.LegendBubbleLegendOptions} options
* Bubble legend options
* @param {Highcharts.Legend} legend
* Legend
*/
BubbleLegendItem.prototype.init = function (options, legend) {
this.options = options;
this.visible = true;
this.chart = legend.chart;
this.legend = legend;
};
/**
* Depending on the position option, add bubbleLegend to legend items.
*
* @private
* @function Highcharts.BubbleLegend#addToLegend
* @param {Array<(Highcharts.Point|Highcharts.Series)>} items
* All legend items
*/
BubbleLegendItem.prototype.addToLegend = function (items) {
// Insert bubbleLegend into legend items
items.splice(this.options.legendIndex, 0, this);
};
/**
* Calculate ranges, sizes and call the next steps of bubbleLegend
* creation.
*
* @private
* @function Highcharts.BubbleLegend#drawLegendSymbol
* @param {Highcharts.Legend} legend
* Legend instance
*/
BubbleLegendItem.prototype.drawLegendSymbol = function (legend) {
var chart = this.chart,
options = this.options,
itemDistance = pick(legend.options.itemDistance, 20),
ranges = options.ranges,
connectorDistance = options.connectorDistance;
var connectorSpace;
// Predict label dimensions
this.fontMetrics = chart.renderer.fontMetrics(options.labels.style.fontSize);
// Do not create bubbleLegend now if ranges or ranges valeus are not
// specified or if are empty array.
if (!ranges || !ranges.length || !isNumber(ranges[0].value)) {
legend.options.bubbleLegend.autoRanges = true;
return;
}
// Sort ranges to right render order
stableSort(ranges, function (a, b) {
return b.value - a.value;
});
this.ranges = ranges;
this.setOptions();
this.render();
// Get max label size
var maxLabel = this.getMaxLabelSize(),
radius = this.ranges[0].radius,
size = radius * 2;
// Space for connectors and labels.
connectorSpace =
connectorDistance - radius + maxLabel.width;
connectorSpace = connectorSpace > 0 ? connectorSpace : 0;
this.maxLabel = maxLabel;
this.movementX = options.labels.align === 'left' ?
connectorSpace : 0;
this.legendItemWidth = size + connectorSpace + itemDistance;
this.legendItemHeight = size + this.fontMetrics.h / 2;
};
/**
* Set style options for each bubbleLegend range.
*
* @private
* @function Highcharts.BubbleLegend#setOptions
*/
BubbleLegendItem.prototype.setOptions = function () {
var ranges = this.ranges,
options = this.options,
series = this.chart.series[options.seriesIndex],
baseline = this.legend.baseline,
bubbleAttribs = {
zIndex: options.zIndex,
'stroke-width': options.borderWidth
},
connectorAttribs = {
zIndex: options.zIndex,
'stroke-width': options.connectorWidth
},
labelAttribs = {
align: (this.legend.options.rtl ||
options.labels.align === 'left') ? 'right' : 'left',
zIndex: options.zIndex
},
fillOpacity = series.options.marker.fillOpacity,
styledMode = this.chart.styledMode;
// Allow to parts of styles be used individually for range
ranges.forEach(function (range, i) {
if (!styledMode) {
bubbleAttribs.stroke = pick(range.borderColor, options.borderColor, series.color);
bubbleAttribs.fill = pick(range.color, options.color, fillOpacity !== 1 ?
color(series.color).setOpacity(fillOpacity)
.get('rgba') :
series.color);
connectorAttribs.stroke = pick(range.connectorColor, options.connectorColor, series.color);
}
// Set options needed for rendering each range
ranges[i].radius = this.getRangeRadius(range.value);
ranges[i] = merge(ranges[i], {
center: (ranges[0].radius - ranges[i].radius +
baseline)
});
if (!styledMode) {
merge(true, ranges[i], {
bubbleAttribs: merge(bubbleAttribs),
connectorAttribs: merge(connectorAttribs),
labelAttribs: labelAttribs
});
}
}, this);
};
/**
* Calculate radius for each bubble range,
* used code from BubbleSeries.js 'getRadius' method.
*
* @private
* @function Highcharts.BubbleLegend#getRangeRadius
* @param {number} value
* Range value
* @return {number|null}
* Radius for one range
*/
BubbleLegendItem.prototype.getRangeRadius = function (value) {
var options = this.options,
seriesIndex = this.options.seriesIndex,
bubbleSeries = this.chart.series[seriesIndex],
zMax = options.ranges[0].value,
zMin = options.ranges[options.ranges.length - 1].value,
minSize = options.minSize,
maxSize = options.maxSize;
return bubbleSeries.getRadius.call(this, zMin, zMax, minSize, maxSize, value);
};
/**
* Render the legendSymbol group.
*
* @private
* @function Highcharts.BubbleLegend#render
*/
BubbleLegendItem.prototype.render = function () {
var renderer = this.chart.renderer,
zThreshold = this.options.zThreshold;
if (!this.symbols) {
this.symbols = {
connectors: [],
bubbleItems: [],
labels: []
};
}
// Nesting SVG groups to enable handleOverflow
this.legendSymbol = renderer.g('bubble-legend');
this.legendItem = renderer.g('bubble-legend-item');
// To enable default 'hideOverlappingLabels' method
this.legendSymbol.translateX = 0;
this.legendSymbol.translateY = 0;
this.ranges.forEach(function (range) {
if (range.value >= zThreshold) {
this.renderRange(range);
}
}, this);
// To use handleOverflow method
this.legendSymbol.add(this.legendItem);
this.legendItem.add(this.legendGroup);
this.hideOverlappingLabels();
};
/**
* Render one range, consisting of bubble symbol, connector and label.
*
* @private
* @function Highcharts.BubbleLegend#renderRange
* @param {Highcharts.LegendBubbleLegendRangesOptions} range
* Range options
*/
BubbleLegendItem.prototype.renderRange = function (range) {
var mainRange = this.ranges[0],
legend = this.legend,
options = this.options,
labelsOptions = options.labels,
chart = this.chart,
bubbleSeries = chart.series[options.seriesIndex],
renderer = chart.renderer,
symbols = this.symbols,
labels = symbols.labels,
elementCenter = range.center,
absoluteRadius = Math.abs(range.radius),
connectorDistance = options.connectorDistance || 0,
labelsAlign = labelsOptions.align,
rtl = legend.options.rtl,
borderWidth = options.borderWidth,
connectorWidth = options.connectorWidth,
posX = mainRange.radius || 0,
posY = elementCenter - absoluteRadius -
borderWidth / 2 + connectorWidth / 2,
fontMetrics = this.fontMetrics,
labelMovement = fontMetrics.f / 2 -
(fontMetrics.h - fontMetrics.f) / 2,
crispMovement = (posY % 1 ? 1 : 0.5) -
(connectorWidth % 2 ? 0 : 0.5),
styledMode = renderer.styledMode;
var connectorLength = rtl || labelsAlign === 'left' ?
-connectorDistance : connectorDistance;
// Set options for centered labels
if (labelsAlign === 'center') {
connectorLength = 0; // do not use connector
options.connectorDistance = 0;
range.labelAttribs.align = 'center';
}
var labelY = posY + options.labels.y,
labelX = posX + connectorLength + options.labels.x;
// Render bubble symbol
symbols.bubbleItems.push(renderer
.circle(posX, elementCenter + crispMovement, absoluteRadius)
.attr(styledMode ? {} : range.bubbleAttribs)
.addClass((styledMode ?
'highcharts-color-' +
bubbleSeries.colorIndex + ' ' :
'') +
'highcharts-bubble-legend-symbol ' +
(options.className || '')).add(this.legendSymbol));
// Render connector
symbols.connectors.push(renderer
.path(renderer.crispLine([
['M', posX, posY],
['L', posX + connectorLength, posY]
], options.connectorWidth))
.attr((styledMode ? {} : range.connectorAttribs))
.addClass((styledMode ?
'highcharts-color-' +
this.options.seriesIndex + ' ' : '') +
'highcharts-bubble-legend-connectors ' +
(options.connectorClassName || '')).add(this.legendSymbol));
// Render label
var label = renderer
.text(this.formatLabel(range),
labelX,
labelY + labelMovement)
.attr((styledMode ? {} : range.labelAttribs))
.css(styledMode ? {} : labelsOptions.style)
.addClass('highcharts-bubble-legend-labels ' +
(options.labels.className || '')).add(this.legendSymbol);
labels.push(label);
// To enable default 'hideOverlappingLabels' method
label.placed = true;
label.alignAttr = {
x: labelX,
y: labelY + labelMovement
};
};
/**
* Get the label which takes up the most space.
*
* @private
* @function Highcharts.BubbleLegend#getMaxLabelSize
*/
BubbleLegendItem.prototype.getMaxLabelSize = function () {
var labels = this.symbols.labels;
var maxLabel,
labelSize;
labels.forEach(function (label) {
labelSize = label.getBBox(true);
if (maxLabel) {
maxLabel = labelSize.width > maxLabel.width ?
labelSize : maxLabel;
}
else {
maxLabel = labelSize;
}
});
return maxLabel || {};
};
/**
* Get formatted label for range.
*
* @private
* @function Highcharts.BubbleLegend#formatLabel
* @param {Highcharts.LegendBubbleLegendRangesOptions} range
* Range options
* @return {string}
* Range label text
*/
BubbleLegendItem.prototype.formatLabel = function (range) {
var options = this.options,
formatter = options.labels.formatter,
format = options.labels.format;
var numberFormatter = this.chart.numberFormatter;
return format ? F.format(format, range) :
formatter ? formatter.call(range) :
numberFormatter(range.value, 1);
};
/**
* By using default chart 'hideOverlappingLabels' method, hide or show
* labels and connectors.
*
* @private
* @function Highcharts.BubbleLegend#hideOverlappingLabels
*/
BubbleLegendItem.prototype.hideOverlappingLabels = function () {
var chart = this.chart,
allowOverlap = this.options.labels.allowOverlap,
symbols = this.symbols;
if (!allowOverlap && symbols) {
chart.hideOverlappingLabels(symbols.labels);
// Hide or show connectors
symbols.labels.forEach(function (label, index) {
if (!label.newOpacity) {
symbols.connectors[index].hide();
}
else if (label.newOpacity !== label.oldOpacity) {
symbols.connectors[index].show();
}
});
}
};
/**
* Calculate ranges from created series.
*
* @private
* @function Highcharts.BubbleLegend#getRanges
* @return {Array<Highcharts.LegendBubbleLegendRangesOptions>}
* Array of range objects
*/
BubbleLegendItem.prototype.getRanges = function () {
var bubbleLegend = this.legend.bubbleLegend,
series = bubbleLegend.chart.series,
rangesOptions = bubbleLegend.options.ranges;
var ranges,
zData,
minZ = Number.MAX_VALUE,
maxZ = -Number.MAX_VALUE;
series.forEach(function (s) {
// Find the min and max Z, like in bubble series
if (s.isBubble && !s.ignoreSeries) {
zData = s.zData.filter(isNumber);
if (zData.length) {
minZ = pick(s.options.zMin, Math.min(minZ, Math.max(arrayMin(zData), s.options.displayNegative === false ?
s.options.zThreshold :
-Number.MAX_VALUE)));
maxZ = pick(s.options.zMax, Math.max(maxZ, arrayMax(zData)));
}
}
});
// Set values for ranges
if (minZ === maxZ) {
// Only one range if min and max values are the same.
ranges = [{ value: maxZ }];
}
else {
ranges = [
{ value: minZ },
{ value: (minZ + maxZ) / 2 },
{ value: maxZ, autoRanges: true }
];
}
// Prevent reverse order of ranges after redraw
if (rangesOptions.length && rangesOptions[0].radius) {
ranges.reverse();
}
// Merge ranges values with user options
ranges.forEach(function (range, i) {
if (rangesOptions && rangesOptions[i]) {
ranges[i] = merge(rangesOptions[i], range);
}
});
return ranges;
};
/**
* Calculate bubble legend sizes from rendered series.
*
* @private
* @function Highcharts.BubbleLegend#predictBubbleSizes
* @return {Array<number,number>}
* Calculated min and max bubble sizes
*/
BubbleLegendItem.prototype.predictBubbleSizes = function () {
var chart = this.chart,
fontMetrics = this.fontMetrics,
legendOptions = chart.legend.options,
floating = legendOptions.floating,
horizontal = legendOptions.layout === 'horizontal',
lastLineHeight = horizontal ? chart.legend.lastLineHeight : 0,
plotSizeX = chart.plotSizeX,
plotSizeY = chart.plotSizeY,
bubbleSeries = chart.series[this.options.seriesIndex],
pxSizes = bubbleSeries.getPxExtremes(),
minSize = Math.ceil(pxSizes.minPxSize),
maxPxSize = Math.ceil(pxSizes.maxPxSize),
plotSize = Math.min(plotSizeY,
plotSizeX);
var calculatedSize,
maxSize = bubbleSeries.options.maxSize;
// Calculate prediceted max size of bubble
if (floating || !(/%$/.test(maxSize))) {
calculatedSize = maxPxSize;
}
else {
maxSize = parseFloat(maxSize);
calculatedSize = ((plotSize + lastLineHeight -
fontMetrics.h / 2) * maxSize / 100) / (maxSize / 100 + 1);
// Get maxPxSize from bubble series if calculated bubble legend
// size will not affect to bubbles series.
if ((horizontal && plotSizeY - calculatedSize >=
plotSizeX) || (!horizontal && plotSizeX -
calculatedSize >= plotSizeY)) {
calculatedSize = maxPxSize;
}
}
return [minSize, Math.ceil(calculatedSize)];
};
/**
* Correct ranges with calculated sizes.
*
* @private
* @function Highcharts.BubbleLegend#updateRanges
* @param {number} min
* @param {number} max
*/
BubbleLegendItem.prototype.updateRanges = function (min, max) {
var bubbleLegendOptions = this.legend.options.bubbleLegend;
bubbleLegendOptions.minSize = min;
bubbleLegendOptions.maxSize = max;
bubbleLegendOptions.ranges = this.getRanges();
};
/**
* Because of the possibility of creating another legend line, predicted
* bubble legend sizes may differ by a few pixels, so it is necessary to
* correct them.
*
* @private
* @function Highcharts.BubbleLegend#correctSizes
*/
BubbleLegendItem.prototype.correctSizes = function () {
var legend = this.legend,
chart = this.chart,
bubbleSeries = chart.series[this.options.seriesIndex],
pxSizes = bubbleSeries.getPxExtremes(),
bubbleSeriesSize = pxSizes.maxPxSize,
bubbleLegendSize = this.options.maxSize;
if (Math.abs(Math.ceil(bubbleSeriesSize) - bubbleLegendSize) >
1) {
this.updateRanges(this.options.minSize, pxSizes.maxPxSize);
legend.render();
}
};
return BubbleLegendItem;
}());
/* *
*
* Default Export
*
* */
return BubbleLegendItem;
});
_registerModule(_modules, 'Series/Bubble/BubbleLegendComposition.js', [_modules['Series/Bubble/BubbleLegendDefaults.js'], _modules['Series/Bubble/BubbleLegendItem.js'], _modules['Core/DefaultOptions.js'], _modules['Core/Utilities.js']], function (BubbleLegendDefaults, BubbleLegendItem, D, U) {
/* *
*
* (c) 2010-2021 Highsoft AS
*
* Author: Paweł Potaczek
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var setOptions = D.setOptions;
var addEvent = U.addEvent,
objectEach = U.objectEach,
wrap = U.wrap;
/* *
*
* Namespace
*
* */
var BubbleLegendComposition;
(function (BubbleLegendComposition) {
/* *
*
* Constants
*
* */
var composedClasses = [];
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* If ranges are not specified, determine ranges from rendered bubble series
* and render legend again.
*/
function chartDrawChartBox(proceed, options, callback) {
var chart = this,
legend = chart.legend,
bubbleSeries = getVisibleBubbleSeriesIndex(chart) >= 0;
var bubbleLegendOptions,
bubbleSizes;
if (legend && legend.options.enabled && legend.bubbleLegend &&
legend.options.bubbleLegend.autoRanges && bubbleSeries) {
bubbleLegendOptions = legend.bubbleLegend.options;
bubbleSizes = legend.bubbleLegend.predictBubbleSizes();
legend.bubbleLegend.updateRanges(bubbleSizes[0], bubbleSizes[1]);
// Disable animation on init
if (!bubbleLegendOptions.placed) {
legend.group.placed = false;
legend.allItems.forEach(function (item) {
item.legendGroup.translateY = null;
});
}
// Create legend with bubbleLegend
legend.render();
chart.getMargins();
chart.axes.forEach(function (axis) {
if (axis.visible) { // #11448
axis.render();
}
if (!bubbleLegendOptions.placed) {
axis.setScale();
axis.updateNames();
// Disable axis animation on init
objectEach(axis.ticks, function (tick) {
tick.isNew = true;
tick.isNewLabel = true;
});
}
});
bubbleLegendOptions.placed = true;
// After recalculate axes, calculate margins again.
chart.getMargins();
// Call default 'drawChartBox' method.
proceed.call(chart, options, callback);
// Check bubble legend sizes and correct them if necessary.
legend.bubbleLegend.correctSizes();
// Correct items positions with different dimensions in legend.
retranslateItems(legend, getLinesHeights(legend));
}
else {
proceed.call(chart, options, callback);
// Allow color change on static bubble legend after click on legend
if (legend && legend.options.enabled && legend.bubbleLegend) {
legend.render();
retranslateItems(legend, getLinesHeights(legend));
}
}
}
/**
* Compose classes for use with Bubble series.
* @private
*
* @param {Highcharts.Chart} ChartClass
* Core chart class to use with Bubble series.
*
* @param {Highcharts.Legend} LegendClass
* Core legend class to use with Bubble series.
*
* @param {Highcharts.Series} SeriesClass
* Core series class to use with Bubble series.
*/
function compose(ChartClass, LegendClass, SeriesClass) {
if (composedClasses.indexOf(ChartClass) === -1) {
composedClasses.push(ChartClass);
setOptions({
// Set default bubble legend options
legend: {
bubbleLegend: BubbleLegendDefaults
}
});
wrap(ChartClass.prototype, 'drawChartBox', chartDrawChartBox);
}
if (composedClasses.indexOf(LegendClass) === -1) {
composedClasses.push(LegendClass);
addEvent(LegendClass, 'afterGetAllItems', onLegendAfterGetAllItems);
}
if (composedClasses.indexOf(SeriesClass) === -1) {
composedClasses.push(SeriesClass);
addEvent(SeriesClass, 'legendItemClick', onSeriesLegendItemClick);
}
}
BubbleLegendComposition.compose = compose;
/**
* Check if there is at least one visible bubble series.
*
* @private
* @function getVisibleBubbleSeriesIndex
* @param {Highcharts.Chart} chart
* Chart to check.
* @return {number}
* First visible bubble series index
*/
function getVisibleBubbleSeriesIndex(chart) {
var series = chart.series;
var i = 0;
while (i < series.length) {
if (series[i] &&
series[i].isBubble &&
series[i].visible &&
series[i].zData.length) {
return i;
}
i++;
}
return -1;
}
/**
* Calculate height for each row in legend.
*
* @private
* @function getLinesHeights
*
* @param {Highcharts.Legend} legend
* Legend to calculate from.
*
* @return {Array<Highcharts.Dictionary<number>>}
* Informations about line height and items amount
*/
function getLinesHeights(legend) {
var items = legend.allItems,
lines = [],
length = items.length;
var lastLine,
i = 0,
j = 0;
for (i = 0; i < length; i++) {
if (items[i].legendItemHeight) {
// for bubbleLegend
items[i].itemHeight = items[i].legendItemHeight;
}
if ( // Line break
items[i] === items[length - 1] ||
items[i + 1] &&
items[i]._legendItemPos[1] !==
items[i + 1]._legendItemPos[1]) {
lines.push({ height: 0 });
lastLine = lines[lines.length - 1];
// Find the highest item in line
for (j; j <= i; j++) {
if (items[j].itemHeight > lastLine.height) {
lastLine.height = items[j].itemHeight;
}
}
lastLine.step = i;
}
}
return lines;
}
/**
* Start the bubble legend creation process.
*/
function onLegendAfterGetAllItems(e) {
var legend = this,
bubbleLegend = legend.bubbleLegend,
legendOptions = legend.options,
options = legendOptions.bubbleLegend,
bubbleSeriesIndex = getVisibleBubbleSeriesIndex(legend.chart);
// Remove unnecessary element
if (bubbleLegend && bubbleLegend.ranges && bubbleLegend.ranges.length) {
// Allow change the way of calculating ranges in update
if (options.ranges.length) {
options.autoRanges =
!!options.ranges[0].autoRanges;
}
// Update bubbleLegend dimensions in each redraw
legend.destroyItem(bubbleLegend);
}
// Create bubble legend
if (bubbleSeriesIndex >= 0 &&
legendOptions.enabled &&
options.enabled) {
options.seriesIndex = bubbleSeriesIndex;
legend.bubbleLegend = new BubbleLegendItem(options, legend);
legend.bubbleLegend.addToLegend(e.allItems);
}
}
/**
* Toggle bubble legend depending on the visible status of bubble series.
*/
function onSeriesLegendItemClick() {
var series = this,
chart = series.chart,
visible = series.visible,
legend = series.chart.legend;
var status;
if (legend && legend.bubbleLegend) {
// Temporary correct 'visible' property
series.visible = !visible;
// Save future status for getRanges method
series.ignoreSeries = visible;
// Check if at lest one bubble series is visible
status = getVisibleBubbleSeriesIndex(chart) >= 0;
// Hide bubble legend if all bubble series are disabled
if (legend.bubbleLegend.visible !== status) {
// Show or hide bubble legend
legend.update({
bubbleLegend: { enabled: status }
});
legend.bubbleLegend.visible = status; // Restore default status
}
series.visible = visible;
}
}
/**
* Correct legend items translation in case of different elements heights.
*
* @private
* @function Highcharts.Legend#retranslateItems
*
* @param {Highcharts.Legend} legend
* Legend to translate in.
*
* @param {Array<Highcharts.Dictionary<number>>} lines
* Informations about line height and items amount
*/
function retranslateItems(legend, lines) {
var items = legend.allItems,
rtl = legend.options.rtl;
var orgTranslateX,
orgTranslateY,
movementX,
actualLine = 0;
items.forEach(function (item, index) {
orgTranslateX = item.legendGroup.translateX;
orgTranslateY = item._legendItemPos[1];
movementX = item.movementX;
if (movementX || (rtl && item.ranges)) {
movementX = rtl ?
orgTranslateX - item.options.maxSize / 2 :
orgTranslateX + movementX;
item.legendGroup.attr({ translateX: movementX });
}
if (index > lines[actualLine].step) {
actualLine++;
}
item.legendGroup.attr({
translateY: Math.round(orgTranslateY + lines[actualLine].height / 2)
});
item._legendItemPos[1] = orgTranslateY +
lines[actualLine].height / 2;
});
}
/* eslint-disable valid-jsdoc */
})(BubbleLegendComposition || (BubbleLegendComposition = {}));
/* *
*
* Default Export
*
* */
return BubbleLegendComposition;
});
_registerModule(_modules, 'Series/Bubble/BubblePoint.js', [_modules['Core/Series/Point.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (Point, SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var ScatterPoint = SeriesRegistry.seriesTypes.scatter.prototype.pointClass;
var extend = U.extend;
/* *
*
* Class
*
* */
var BubblePoint = /** @class */ (function (_super) {
__extends(BubblePoint, _super);
function BubblePoint() {
/* *
*
* Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
_this.options = void 0;
_this.series = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* @private
*/
BubblePoint.prototype.haloPath = function (size) {
return Point.prototype.haloPath.call(this,
// #6067
size === 0 ? 0 : (this.marker ? this.marker.radius || 0 : 0) + size);
};
return BubblePoint;
}(ScatterPoint));
/* *
*
* Class Prototype
*
* */
extend(BubblePoint.prototype, {
ttBelow: false
});
/* *
*
* Default Export
*
* */
return BubblePoint;
});
_registerModule(_modules, 'Series/Bubble/BubbleSeries.js', [_modules['Core/Axis/Axis.js'], _modules['Series/Bubble/BubbleLegendComposition.js'], _modules['Series/Bubble/BubblePoint.js'], _modules['Core/Color/Color.js'], _modules['Core/Globals.js'], _modules['Core/Series/Series.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (Axis, BubbleLegendComposition, BubblePoint, Color, H, Series, SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var color = Color.parse;
var noop = H.noop;
var _a = SeriesRegistry.seriesTypes,
ColumnSeries = _a.column,
ScatterSeries = _a.scatter;
var addEvent = U.addEvent,
arrayMax = U.arrayMax,
arrayMin = U.arrayMin,
clamp = U.clamp,
extend = U.extend,
isNumber = U.isNumber,
merge = U.merge,
pick = U.pick;
/* *
*
* Class
*
* */
var BubbleSeries = /** @class */ (function (_super) {
__extends(BubbleSeries, _super);
function BubbleSeries() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* *
*
* Properties
*
* */
_this.data = void 0;
_this.maxPxSize = void 0;
_this.minPxSize = void 0;
_this.options = void 0;
_this.points = void 0;
_this.radii = void 0;
_this.yData = void 0;
_this.zData = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* Perform animation on the bubbles
* @private
*/
BubbleSeries.prototype.animate = function (init) {
if (!init &&
this.points.length < this.options.animationLimit // #8099
) {
this.points.forEach(function (point) {
var graphic = point.graphic;
if (graphic && graphic.width) { // URL symbols don't have width
// Start values
if (!this.hasRendered) {
graphic.attr({
x: point.plotX,
y: point.plotY,
width: 1,
height: 1
});
}
// Run animation
graphic.animate(this.markerAttribs(point), this.options.animation);
}
}, this);
}
};
/**
* Get the radius for each point based on the minSize, maxSize and each
* point's Z value. This must be done prior to Series.translate because
* the axis needs to add padding in accordance with the point sizes.
* @private
*/
BubbleSeries.prototype.getRadii = function () {
var _this = this;
var len,
i,
zData = this.zData,
yData = this.yData,
radii = [],
value,
zExtremes = this.chart.bubbleZExtremes;
var _a = this.getPxExtremes(),
minPxSize = _a.minPxSize,
maxPxSize = _a.maxPxSize;
// Get the collective Z extremes of all bubblish series. The chart-level
// `bubbleZExtremes` are only computed once, and reset on `updatedData`
// in any member series.
if (!zExtremes) {
var zMin_1 = Number.MAX_VALUE;
var zMax_1 = -Number.MAX_VALUE;
var valid_1;
this.chart.series.forEach(function (otherSeries) {
if (otherSeries.bubblePadding && (otherSeries.visible ||
!_this.chart.options.chart.ignoreHiddenSeries)) {
var zExtremes_1 = otherSeries.getZExtremes();
if (zExtremes_1) {
zMin_1 = Math.min(zMin_1 || zExtremes_1.zMin, zExtremes_1.zMin);
zMax_1 = Math.max(zMax_1 || zExtremes_1.zMax, zExtremes_1.zMax);
valid_1 = true;
}
}
});
if (valid_1) {
zExtremes = { zMin: zMin_1, zMax: zMax_1 };
this.chart.bubbleZExtremes = zExtremes;
}
else {
zExtremes = { zMin: 0, zMax: 0 };
}
}
// Set the shape type and arguments to be picked up in drawPoints
for (i = 0, len = zData.length; i < len; i++) {
value = zData[i];
// Separate method to get individual radius for bubbleLegend
radii.push(this.getRadius(zExtremes.zMin, zExtremes.zMax, minPxSize, maxPxSize, value, yData[i]));
}
this.radii = radii;
};
/**
* Get the individual radius for one point.
* @private
*/
BubbleSeries.prototype.getRadius = function (zMin, zMax, minSize, maxSize, value, yValue) {
var options = this.options,
sizeByArea = options.sizeBy !== 'width',
zThreshold = options.zThreshold,
zRange = zMax - zMin,
pos = 0.5;
// #8608 - bubble should be visible when z is undefined
if (yValue === null || value === null) {
return null;
}
if (isNumber(value)) {
// When sizing by threshold, the absolute value of z determines
// the size of the bubble.
if (options.sizeByAbsoluteValue) {
value = Math.abs(value - zThreshold);
zMax = zRange = Math.max(zMax - zThreshold, Math.abs(zMin - zThreshold));
zMin = 0;
}
// Issue #4419 - if value is less than zMin, push a radius that's
// always smaller than the minimum size
if (value < zMin) {
return minSize / 2 - 1;
}
// Relative size, a number between 0 and 1
if (zRange > 0) {
pos = (value - zMin) / zRange;
}
}
if (sizeByArea && pos >= 0) {
pos = Math.sqrt(pos);
}
return Math.ceil(minSize + pos * (maxSize - minSize)) / 2;
};
/**
* Define hasData function for non-cartesian series.
* Returns true if the series has points at all.
* @private
*/
BubbleSeries.prototype.hasData = function () {
return !!this.processedXData.length; // != 0
};
/**
* @private
*/
BubbleSeries.prototype.pointAttribs = function (point, state) {
var markerOptions = this.options.marker,
fillOpacity = markerOptions.fillOpacity,
attr = Series.prototype.pointAttribs.call(this,
point,
state);
if (fillOpacity !== 1) {
attr.fill = color(attr.fill)
.setOpacity(fillOpacity)
.get('rgba');
}
return attr;
};
/**
* Extend the base translate method to handle bubble size
* @private
*/
BubbleSeries.prototype.translate = function () {
// Run the parent method
_super.prototype.translate.call(this);
this.getRadii();
this.translateBubble();
};
BubbleSeries.prototype.translateBubble = function () {
var _a = this,
data = _a.data,
radii = _a.radii;
var minPxSize = this.getPxExtremes().minPxSize;
// Set the shape type and arguments to be picked up in drawPoints
var i = data.length;
while (i--) {
var point = data[i];
var radius = radii ? radii[i] : 0; // #1737
if (isNumber(radius) && radius >= minPxSize / 2) {
// Shape arguments
point.marker = extend(point.marker, {
radius: radius,
width: 2 * radius,
height: 2 * radius
});
// Alignment box for the data label
point.dlBox = {
x: point.plotX - radius,
y: point.plotY - radius,
width: 2 * radius,
height: 2 * radius
};
}
else { // below zThreshold
// #1691
point.shapeArgs = point.plotY = point.dlBox = void 0;
}
}
};
BubbleSeries.prototype.getPxExtremes = function () {
var smallestSize = Math.min(this.chart.plotWidth,
this.chart.plotHeight);
var getPxSize = function (length) {
var isPercent;
if (typeof length === 'string') {
isPercent = /%$/.test(length);
length = parseInt(length, 10);
}
return isPercent ? smallestSize * length / 100 : length;
};
var minPxSize = getPxSize(pick(this.options.minSize, 8));
// Prioritize min size if conflict to make sure bubbles are
// always visible. #5873
var maxPxSize = Math.max(getPxSize(pick(this.options.maxSize, '20%')),
minPxSize);
return { minPxSize: minPxSize, maxPxSize: maxPxSize };
};
BubbleSeries.prototype.getZExtremes = function () {
var options = this.options,
zData = (this.zData || []).filter(isNumber);
if (zData.length) {
var zMin = pick(options.zMin,
clamp(arrayMin(zData),
options.displayNegative === false ?
(options.zThreshold || 0) :
-Number.MAX_VALUE,
Number.MAX_VALUE));
var zMax = pick(options.zMax,
arrayMax(zData));
if (isNumber(zMin) && isNumber(zMax)) {
return { zMin: zMin, zMax: zMax };
}
}
};
BubbleSeries.compose = BubbleLegendComposition.compose;
/**
* A bubble series is a three dimensional series type where each point
* renders an X, Y and Z value. Each points is drawn as a bubble where the
* position along the X and Y axes mark the X and Y values, and the size of
* the bubble relates to the Z value.
*
* @sample {highcharts} highcharts/demo/bubble/
* Bubble chart
*
* @extends plotOptions.scatter
* @excluding cluster
* @product highcharts highstock
* @requires highcharts-more
* @optionparent plotOptions.bubble
*/
BubbleSeries.defaultOptions = merge(ScatterSeries.defaultOptions, {
dataLabels: {
formatter: function () {
var numberFormatter = this.series.chart.numberFormatter;
var z = this.point.z;
return isNumber(z) ? numberFormatter(z, -1) : '';
},
inside: true,
verticalAlign: 'middle'
},
/**
* If there are more points in the series than the `animationLimit`, the
* animation won't run. Animation affects overall performance and
* doesn't work well with heavy data series.
*
* @since 6.1.0
*/
animationLimit: 250,
/**
* Whether to display negative sized bubbles. The threshold is given
* by the [zThreshold](#plotOptions.bubble.zThreshold) option, and negative
* bubbles can be visualized by setting
* [negativeColor](#plotOptions.bubble.negativeColor).
*
* @sample {highcharts} highcharts/plotoptions/bubble-negative/
* Negative bubbles
*
* @type {boolean}
* @default true
* @since 3.0
* @apioption plotOptions.bubble.displayNegative
*/
/**
* @extends plotOptions.series.marker
* @excluding enabled, enabledThreshold, height, radius, width
*/
marker: {
lineColor: null,
lineWidth: 1,
/**
* The fill opacity of the bubble markers.
*/
fillOpacity: 0.5,
/**
* In bubble charts, the radius is overridden and determined based
* on the point's data value.
*
* @ignore-option
*/
radius: null,
states: {
hover: {
radiusPlus: 0
}
},
/**
* A predefined shape or symbol for the marker. Possible values are
* "circle", "square", "diamond", "triangle" and "triangle-down".
*
* Additionally, the URL to a graphic can be given on the form
* `url(graphic.png)`. Note that for the image to be applied to
* exported charts, its URL needs to be accessible by the export
* server.
*
* Custom callbacks for symbol path generation can also be added to
* `Highcharts.SVGRenderer.prototype.symbols`. The callback is then
* used by its method name, as shown in the demo.
*
* @sample {highcharts} highcharts/plotoptions/bubble-symbol/
* Bubble chart with various symbols
* @sample {highcharts} highcharts/plotoptions/series-marker-symbol/
* General chart with predefined, graphic and custom markers
*
* @type {Highcharts.SymbolKeyValue|string}
* @since 5.0.11
*/
symbol: 'circle'
},
/**
* Minimum bubble size. Bubbles will automatically size between the
* `minSize` and `maxSize` to reflect the `z` value of each bubble.
* Can be either pixels (when no unit is given), or a percentage of
* the smallest one of the plot width and height.
*
* @sample {highcharts} highcharts/plotoptions/bubble-size/
* Bubble size
*
* @type {number|string}
* @since 3.0
* @product highcharts highstock
*/
minSize: 8,
/**
* Maximum bubble size. Bubbles will automatically size between the
* `minSize` and `maxSize` to reflect the `z` value of each bubble.
* Can be either pixels (when no unit is given), or a percentage of
* the smallest one of the plot width and height.
*
* @sample {highcharts} highcharts/plotoptions/bubble-size/
* Bubble size
*
* @type {number|string}
* @since 3.0
* @product highcharts highstock
*/
maxSize: '20%',
/**
* When a point's Z value is below the
* [zThreshold](#plotOptions.bubble.zThreshold)
* setting, this color is used.
*
* @sample {highcharts} highcharts/plotoptions/bubble-negative/
* Negative bubbles
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 3.0
* @product highcharts
* @apioption plotOptions.bubble.negativeColor
*/
/**
* Whether the bubble's value should be represented by the area or the
* width of the bubble. The default, `area`, corresponds best to the
* human perception of the size of each bubble.
*
* @sample {highcharts} highcharts/plotoptions/bubble-sizeby/
* Comparison of area and size
*
* @type {Highcharts.BubbleSizeByValue}
* @default area
* @since 3.0.7
* @apioption plotOptions.bubble.sizeBy
*/
/**
* When this is true, the absolute value of z determines the size of
* the bubble. This means that with the default `zThreshold` of 0, a
* bubble of value -1 will have the same size as a bubble of value 1,
* while a bubble of value 0 will have a smaller size according to
* `minSize`.
*
* @sample {highcharts} highcharts/plotoptions/bubble-sizebyabsolutevalue/
* Size by absolute value, various thresholds
*
* @type {boolean}
* @default false
* @since 4.1.9
* @product highcharts
* @apioption plotOptions.bubble.sizeByAbsoluteValue
*/
/**
* When this is true, the series will not cause the Y axis to cross
* the zero plane (or [threshold](#plotOptions.series.threshold) option)
* unless the data actually crosses the plane.
*
* For example, if `softThreshold` is `false`, a series of 0, 1, 2,
* 3 will make the Y axis show negative values according to the
* `minPadding` option. If `softThreshold` is `true`, the Y axis starts
* at 0.
*
* @since 4.1.9
* @product highcharts
*/
softThreshold: false,
states: {
hover: {
halo: {
size: 5
}
}
},
tooltip: {
pointFormat: '({point.x}, {point.y}), Size: {point.z}'
},
turboThreshold: 0,
/**
* The minimum for the Z value range. Defaults to the highest Z value
* in the data.
*
* @see [zMin](#plotOptions.bubble.zMin)
*
* @sample {highcharts} highcharts/plotoptions/bubble-zmin-zmax/
* Z has a possible range of 0-100
*
* @type {number}
* @since 4.0.3
* @product highcharts
* @apioption plotOptions.bubble.zMax
*/
/**
* @default z
* @apioption plotOptions.bubble.colorKey
*/
/**
* The minimum for the Z value range. Defaults to the lowest Z value
* in the data.
*
* @see [zMax](#plotOptions.bubble.zMax)
*
* @sample {highcharts} highcharts/plotoptions/bubble-zmin-zmax/
* Z has a possible range of 0-100
*
* @type {number}
* @since 4.0.3
* @product highcharts
* @apioption plotOptions.bubble.zMin
*/
/**
* When [displayNegative](#plotOptions.bubble.displayNegative) is `false`,
* bubbles with lower Z values are skipped. When `displayNegative`
* is `true` and a [negativeColor](#plotOptions.bubble.negativeColor)
* is given, points with lower Z is colored.
*
* @sample {highcharts} highcharts/plotoptions/bubble-negative/
* Negative bubbles
*
* @since 3.0
* @product highcharts
*/
zThreshold: 0,
zoneAxis: 'z'
});
return BubbleSeries;
}(ScatterSeries));
extend(BubbleSeries.prototype, {
alignDataLabel: ColumnSeries.prototype.alignDataLabel,
applyZones: noop,
bubblePadding: true,
buildKDTree: noop,
directTouch: true,
isBubble: true,
pointArrayMap: ['y', 'z'],
pointClass: BubblePoint,
parallelArrays: ['x', 'y', 'z'],
trackerGroups: ['group', 'dataLabelsGroup'],
specialGroup: 'group',
zoneAxis: 'z'
});
// On updated data in any series, delete the chart-level Z extremes cache
addEvent(BubbleSeries, 'updatedData', function (e) {
delete e.target.chart.bubbleZExtremes;
});
/* *
*
* Axis ?
*
* */
// Add logic to pad each axis with the amount of pixels necessary to avoid the
// bubbles to overflow.
Axis.prototype.beforePadding = function () {
var axis = this,
axisLength = this.len,
chart = this.chart,
pxMin = 0,
pxMax = axisLength,
isXAxis = this.isXAxis,
dataKey = isXAxis ? 'xData' : 'yData',
min = this.min,
range = this.max - min,
transA = axisLength / range,
hasActiveSeries;
// Handle padding on the second pass, or on redraw
this.series.forEach(function (series) {
if (series.bubblePadding &&
(series.visible || !chart.options.chart.ignoreHiddenSeries)) {
// Correction for #1673
axis.allowZoomOutside = true;
hasActiveSeries = true;
var data = series[dataKey];
if (isXAxis) {
series.getRadii(0, 0, series);
}
if (range > 0) {
var i = data.length;
while (i--) {
if (isNumber(data[i]) &&
axis.dataMin <= data[i] &&
data[i] <= axis.max) {
var radius = series.radii && series.radii[i] || 0;
pxMin = Math.min(((data[i] - min) * transA) - radius, pxMin);
pxMax = Math.max(((data[i] - min) * transA) + radius, pxMax);
}
}
}
}
});
// Apply the padding to the min and max properties
if (hasActiveSeries && range > 0 && !this.logarithmic) {
pxMax -= axisLength;
transA *= (axisLength +
Math.max(0, pxMin) - // #8901
Math.min(pxMax, axisLength)) / axisLength;
[
['min', 'userMin', pxMin],
['max', 'userMax', pxMax]
].forEach(function (keys) {
if (typeof pick(axis.options[keys[0]], axis[keys[1]]) === 'undefined') {
axis[keys[0]] += keys[2] / transA;
}
});
}
/* eslint-enable valid-jsdoc */
};
SeriesRegistry.registerSeriesType('bubble', BubbleSeries);
/* *
*
* Default Export
*
* */
/* *
*
* API Declarations
*
* */
/**
* @typedef {"area"|"width"} Highcharts.BubbleSizeByValue
*/
''; // detach doclets above
/* *
*
* API Options
*
* */
/**
* A `bubble` series. If the [type](#series.bubble.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.bubble
* @excluding dataParser, dataURL, stack
* @product highcharts highstock
* @requires highcharts-more
* @apioption series.bubble
*/
/**
* An array of data points for the series. For the `bubble` series type,
* points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values correspond
* to `x,y,z`. If the first value is a string, it is applied as the name of
* the point, and the `x` value is inferred. The `x` value can also be
* omitted, in which case the inner arrays should be of length 2\. Then the
* `x` value is automatically calculated, either starting at 0 and
* incremented by 1, or from `pointStart` and `pointInterval` given in the
* series options.
* ```js
* data: [
* [0, 1, 2],
* [1, 5, 5],
* [2, 0, 2]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.bubble.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 1,
* z: 1,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 5,
* z: 4,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<Array<(number|string),number>|Array<(number|string),number,number>|*>}
* @extends series.line.data
* @product highcharts
* @apioption series.bubble.data
*/
/**
* @extends series.line.data.marker
* @excluding enabledThreshold, height, radius, width
* @product highcharts
* @apioption series.bubble.data.marker
*/
/**
* The size value for each bubble. The bubbles' diameters are computed
* based on the `z`, and controlled by series options like `minSize`,
* `maxSize`, `sizeBy`, `zMin` and `zMax`.
*
* @type {number|null}
* @product highcharts
* @apioption series.bubble.data.z
*/
/**
* @excluding enabled, enabledThreshold, height, radius, width
* @apioption series.bubble.marker
*/
''; // adds doclets above to transpiled file
return BubbleSeries;
});
_registerModule(_modules, 'Series/MapBubble/MapBubblePoint.js', [_modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var _a = SeriesRegistry.seriesTypes,
BubbleSeries = _a.bubble,
MapSeries = _a.map;
var extend = U.extend,
merge = U.merge;
/* *
*
* Class
*
* */
var MapBubblePoint = /** @class */ (function (_super) {
__extends(MapBubblePoint, _super);
function MapBubblePoint() {
return _super !== null && _super.apply(this, arguments) || this;
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* @private
*/
MapBubblePoint.prototype.applyOptions = function (options, x) {
var point;
if (options &&
typeof options.lat !== 'undefined' &&
typeof options.lon !== 'undefined') {
point = _super.prototype.applyOptions.call(this, merge(options, this.series.chart.fromLatLonToPoint(options)), x);
}
else {
point = MapSeries.prototype.pointClass.prototype
.applyOptions.call(this, options, x);
}
return point;
};
/**
* @private
*/
MapBubblePoint.prototype.isValid = function () {
return typeof this.z === 'number';
};
return MapBubblePoint;
}(BubbleSeries.prototype.pointClass));
/* *
*
* Default Export
*
* */
return MapBubblePoint;
});
_registerModule(_modules, 'Series/MapBubble/MapBubbleSeries.js', [_modules['Series/Bubble/BubbleSeries.js'], _modules['Series/MapBubble/MapBubblePoint.js'], _modules['Series/Map/MapSeries.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (BubbleSeries, MapBubblePoint, MapSeries, SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var MapPointSeries = SeriesRegistry.seriesTypes.mappoint;
var extend = U.extend,
merge = U.merge;
/* *
*
* Class
*
* */
/**
* @private
* @class
* @name Highcharts.seriesTypes.mapbubble
*
* @augments Highcharts.Series
*/
var MapBubbleSeries = /** @class */ (function (_super) {
__extends(MapBubbleSeries, _super);
function MapBubbleSeries() {
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* *
*
* Properties
*
* */
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
}
MapBubbleSeries.prototype.translate = function () {
MapPointSeries.prototype.translate.call(this);
this.getRadii();
this.translateBubble();
};
/* *
*
* Static Properties
*
* */
MapBubbleSeries.compose = BubbleSeries.compose;
/**
* A map bubble series is a bubble series laid out on top of a map
* series, where each bubble is tied to a specific map area.
*
* @sample maps/demo/map-bubble/
* Map bubble chart
*
* @extends plotOptions.bubble
* @product highmaps
* @optionparent plotOptions.mapbubble
*/
MapBubbleSeries.defaultOptions = merge(BubbleSeries.defaultOptions, {
/**
* The main color of the series. This color affects both the fill
* and the stroke of the bubble. For enhanced control, use `marker`
* options.
*
* @sample {highmaps} maps/plotoptions/mapbubble-color/
* Pink bubbles
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @apioption plotOptions.mapbubble.color
*/
/**
* Whether to display negative sized bubbles. The threshold is
* given by the [zThreshold](#plotOptions.mapbubble.zThreshold)
* option, and negative bubbles can be visualized by setting
* [negativeColor](#plotOptions.bubble.negativeColor).
*
* @type {boolean}
* @default true
* @apioption plotOptions.mapbubble.displayNegative
*/
/**
* @sample {highmaps} maps/demo/map-bubble/
* Bubble size
*
* @apioption plotOptions.mapbubble.maxSize
*/
/**
* @sample {highmaps} maps/demo/map-bubble/
* Bubble size
*
* @apioption plotOptions.mapbubble.minSize
*/
/**
* When a point's Z value is below the
* [zThreshold](#plotOptions.mapbubble.zThreshold) setting, this
* color is used.
*
* @sample {highmaps} maps/plotoptions/mapbubble-negativecolor/
* Negative color below a threshold
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @apioption plotOptions.mapbubble.negativeColor
*/
/**
* Whether the bubble's value should be represented by the area or
* the width of the bubble. The default, `area`, corresponds best to
* the human perception of the size of each bubble.
*
* @type {Highcharts.BubbleSizeByValue}
* @default area
* @apioption plotOptions.mapbubble.sizeBy
*/
/**
* When this is true, the absolute value of z determines the size
* of the bubble. This means that with the default `zThreshold` of
* 0, a bubble of value -1 will have the same size as a bubble of
* value 1, while a bubble of value 0 will have a smaller size
* according to `minSize`.
*
* @sample {highmaps} highcharts/plotoptions/bubble-sizebyabsolutevalue/
* Size by absolute value, various thresholds
*
* @type {boolean}
* @default false
* @since 1.1.9
* @apioption plotOptions.mapbubble.sizeByAbsoluteValue
*/
/**
* The minimum for the Z value range. Defaults to the highest Z
* value in the data.
*
* @see [zMax](#plotOptions.mapbubble.zMin)
*
* @sample {highmaps} highcharts/plotoptions/bubble-zmin-zmax/
* Z has a possible range of 0-100
*
* @type {number}
* @since 1.0.3
* @apioption plotOptions.mapbubble.zMax
*/
/**
* The minimum for the Z value range. Defaults to the lowest Z value
* in the data.
*
* @see [zMax](#plotOptions.mapbubble.zMax)
*
* @sample {highmaps} highcharts/plotoptions/bubble-zmin-zmax/
* Z has a possible range of 0-100
*
* @type {number}
* @since 1.0.3
* @apioption plotOptions.mapbubble.zMin
*/
/**
* When [displayNegative](#plotOptions.mapbubble.displayNegative)
* is `false`, bubbles with lower Z values are skipped. When
* `displayNegative` is `true` and a
* [negativeColor](#plotOptions.mapbubble.negativeColor) is given,
* points with lower Z is colored.
*
* @sample {highmaps} maps/plotoptions/mapbubble-negativecolor/
* Negative color below a threshold
*
* @type {number}
* @default 0
* @apioption plotOptions.mapbubble.zThreshold
*/
animationLimit: 500,
tooltip: {
pointFormat: '{point.name}: {point.z}'
}
});
return MapBubbleSeries;
}(BubbleSeries));
extend(MapBubbleSeries.prototype, {
type: 'mapbubble',
axisTypes: ['colorAxis'],
getProjectedBounds: MapSeries.prototype.getProjectedBounds,
isCartesian: false,
// If one single value is passed, it is interpreted as z
pointArrayMap: ['z'],
pointClass: MapBubblePoint,
setData: MapSeries.prototype.setData,
setOptions: MapSeries.prototype.setOptions,
useMapGeometry: true,
xyFromShape: true
});
SeriesRegistry.registerSeriesType('mapbubble', MapBubbleSeries);
/* *
*
* Default Export
*
* */
/* *
*
* API Options
*
* */
/**
* A `mapbubble` series. If the [type](#series.mapbubble.type) option
* is not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.mapbubble
* @excluding dataParser, dataURL
* @product highmaps
* @apioption series.mapbubble
*/
/**
* An array of data points for the series. For the `mapbubble` series
* type, points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values
* will be interpreted as `z` options. Example:
*
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.mapbubble.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* z: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* z: 10,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<number|null|*>}
* @extends series.mappoint.data
* @excluding labelrank, middleX, middleY, path, value, x, y, lat, lon
* @product highmaps
* @apioption series.mapbubble.data
*/
/**
* While the `x` and `y` values of the bubble are determined by the
* underlying map, the `z` indicates the actual value that gives the
* size of the bubble.
*
* @sample {highmaps} maps/demo/map-bubble/
* Bubble
*
* @type {number|null}
* @product highmaps
* @apioption series.mapbubble.data.z
*/
/**
* @excluding enabled, enabledThreshold, height, radius, width
* @apioption series.mapbubble.marker
*/
''; // adds doclets above to transpiled file
return MapBubbleSeries;
});
_registerModule(_modules, 'Series/Heatmap/HeatmapPoint.js', [_modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var ScatterPoint = SeriesRegistry.seriesTypes.scatter.prototype.pointClass;
var clamp = U.clamp,
defined = U.defined,
extend = U.extend,
pick = U.pick;
/* *
*
* Class
*
* */
var HeatmapPoint = /** @class */ (function (_super) {
__extends(HeatmapPoint, _super);
function HeatmapPoint() {
/* *
*
* Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
_this.options = void 0;
_this.series = void 0;
_this.value = void 0;
_this.x = void 0;
_this.y = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* @private
*/
HeatmapPoint.prototype.applyOptions = function (options, x) {
var point = _super.prototype.applyOptions.call(this,
options,
x);
point.formatPrefix = point.isNull || point.value === null ?
'null' : 'point';
return point;
};
HeatmapPoint.prototype.getCellAttributes = function () {
var point = this,
series = point.series,
seriesOptions = series.options,
xPad = (seriesOptions.colsize || 1) / 2,
yPad = (seriesOptions.rowsize || 1) / 2,
xAxis = series.xAxis,
yAxis = series.yAxis,
markerOptions = point.options.marker || series.options.marker,
pointPlacement = series.pointPlacementToXValue(), // #7860
pointPadding = pick(point.pointPadding,
seriesOptions.pointPadding, 0),
cellAttr = {
x1: clamp(Math.round(xAxis.len -
(xAxis.translate(point.x - xPad,
false,
true,
false,
true, -pointPlacement) || 0)), -xAxis.len, 2 * xAxis.len),
x2: clamp(Math.round(xAxis.len -
(xAxis.translate(point.x + xPad,
false,
true,
false,
true, -pointPlacement) || 0)), -xAxis.len, 2 * xAxis.len),
y1: clamp(Math.round((yAxis.translate(point.y - yPad,
false,
true,
false,
true) || 0)), -yAxis.len, 2 * yAxis.len),
y2: clamp(Math.round((yAxis.translate(point.y + yPad,
false,
true,
false,
true) || 0)), -yAxis.len, 2 * yAxis.len)
};
var dimensions = [['width', 'x'], ['height', 'y']];
// Handle marker's fixed width, and height values including border
// and pointPadding while calculating cell attributes.
dimensions.forEach(function (dimension) {
var prop = dimension[0],
direction = dimension[1];
var start = direction + '1', end = direction + '2';
var side = Math.abs(cellAttr[start] - cellAttr[end]),
borderWidth = markerOptions &&
markerOptions.lineWidth || 0,
plotPos = Math.abs(cellAttr[start] + cellAttr[end]) / 2,
widthOrHeight = markerOptions && markerOptions[prop];
if (defined(widthOrHeight) && widthOrHeight < side) {
var halfCellSize = widthOrHeight / 2 + borderWidth / 2;
cellAttr[start] = plotPos - halfCellSize;
cellAttr[end] = plotPos + halfCellSize;
}
// Handle pointPadding
if (pointPadding) {
if (direction === 'y') {
start = end;
end = direction + '1';
}
cellAttr[start] += pointPadding;
cellAttr[end] -= pointPadding;
}
});
return cellAttr;
};
/**
* @private
*/
HeatmapPoint.prototype.haloPath = function (size) {
if (!size) {
return [];
}
var rect = this.shapeArgs;
return [
'M',
rect.x - size,
rect.y - size,
'L',
rect.x - size,
rect.y + rect.height + size,
rect.x + rect.width + size,
rect.y + rect.height + size,
rect.x + rect.width + size,
rect.y - size,
'Z'
];
};
/**
* Color points have a value option that determines whether or not it is
* a null point
* @private
*/
HeatmapPoint.prototype.isValid = function () {
// undefined is allowed
return (this.value !== Infinity &&
this.value !== -Infinity);
};
return HeatmapPoint;
}(ScatterPoint));
extend(HeatmapPoint.prototype, {
dataLabelOnNull: true,
moveToTopOnHover: true,
ttBelow: false
});
/* *
*
* Default Export
*
* */
return HeatmapPoint;
});
_registerModule(_modules, 'Series/Heatmap/HeatmapSeries.js', [_modules['Core/Color/Color.js'], _modules['Series/ColorMapMixin.js'], _modules['Series/Heatmap/HeatmapPoint.js'], _modules['Core/Legend/LegendSymbol.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Renderer/SVG/SVGRenderer.js'], _modules['Core/Utilities.js']], function (Color, ColorMapMixin, HeatmapPoint, LegendSymbol, SeriesRegistry, SVGRenderer, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Series = SeriesRegistry.series,
_a = SeriesRegistry.seriesTypes,
ColumnSeries = _a.column,
ScatterSeries = _a.scatter;
var symbols = SVGRenderer.prototype.symbols;
var extend = U.extend,
fireEvent = U.fireEvent,
isNumber = U.isNumber,
merge = U.merge,
pick = U.pick;
/* *
*
* Class
*
* */
/**
* @private
* @class
* @name Highcharts.seriesTypes.heatmap
*
* @augments Highcharts.Series
*/
var HeatmapSeries = /** @class */ (function (_super) {
__extends(HeatmapSeries, _super);
function HeatmapSeries() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* *
*
* Properties
*
* */
_this.colorAxis = void 0;
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
_this.valueMax = NaN;
_this.valueMin = NaN;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* @private
*/
HeatmapSeries.prototype.drawPoints = function () {
var _this = this;
// In styled mode, use CSS, otherwise the fill used in the style
// sheet will take precedence over the fill attribute.
var seriesMarkerOptions = this.options.marker || {};
if (seriesMarkerOptions.enabled || this._hasPointMarkers) {
Series.prototype.drawPoints.call(this);
this.points.forEach(function (point) {
if (point.graphic) {
point.graphic[_this.chart.styledMode ? 'css' : 'animate'](_this.colorAttribs(point));
// @todo
// Applying the border radius here is not optimal. It should
// be set in the shapeArgs or returned from `markerAttribs`.
// However, Series.drawPoints does not pick up markerAttribs
// to be passed over to `renderer.symbol`. Also, image
// symbols are not positioned by their top left corner like
// other symbols are. This should be refactored, then we
// could save ourselves some tests for .hasImage etc. And
// the evaluation of borderRadius would be moved to
// `markerAttribs`.
if (_this.options.borderRadius) {
point.graphic.attr({
r: _this.options.borderRadius
});
}
// Saving option for reapplying later
// when changing point's states (#16165)
(point.shapeArgs || {}).r = _this.options.borderRadius;
(point.shapeArgs || {}).d = point.graphic.pathArray;
if (point.value === null) { // #15708
point.graphic.addClass('highcharts-null-point');
}
}
});
}
};
/**
* @private
*/
HeatmapSeries.prototype.getExtremes = function () {
// Get the extremes from the value data
var _a = Series.prototype.getExtremes
.call(this,
this.valueData),
dataMin = _a.dataMin,
dataMax = _a.dataMax;
if (isNumber(dataMin)) {
this.valueMin = dataMin;
}
if (isNumber(dataMax)) {
this.valueMax = dataMax;
}
// Get the extremes from the y data
return Series.prototype.getExtremes.call(this);
};
/**
* Override to also allow null points, used when building the k-d-tree for
* tooltips in boost mode.
* @private
*/
HeatmapSeries.prototype.getValidPoints = function (points, insideOnly) {
return Series.prototype.getValidPoints.call(this, points, insideOnly, true);
};
/**
* Define hasData function for non-cartesian series. Returns true if the
* series has points at all.
* @private
*/
HeatmapSeries.prototype.hasData = function () {
return !!this.processedXData.length; // != 0
};
/**
* Override the init method to add point ranges on both axes.
* @private
*/
HeatmapSeries.prototype.init = function () {
var options;
Series.prototype.init.apply(this, arguments);
options = this.options;
// #3758, prevent resetting in setData
options.pointRange = pick(options.pointRange, options.colsize || 1);
// general point range
this.yAxis.axisPointRange = options.rowsize || 1;
// Bind new symbol names
symbols.ellipse = symbols.circle;
};
/**
* @private
*/
HeatmapSeries.prototype.markerAttribs = function (point, state) {
var pointMarkerOptions = point.marker || {},
seriesMarkerOptions = this.options.marker || {},
seriesStateOptions,
pointStateOptions,
shapeArgs = point.shapeArgs || {},
hasImage = point.hasImage,
attribs = {};
if (hasImage) {
return {
x: point.plotX,
y: point.plotY
};
}
// Setting width and height attributes on image does not affect on its
// dimensions.
if (state) {
seriesStateOptions = (seriesMarkerOptions.states[state] || {});
pointStateOptions = pointMarkerOptions.states &&
pointMarkerOptions.states[state] || {};
[['width', 'x'], ['height', 'y']].forEach(function (dimension) {
// Set new width and height basing on state options.
attribs[dimension[0]] = (pointStateOptions[dimension[0]] ||
seriesStateOptions[dimension[0]] ||
shapeArgs[dimension[0]]) + (pointStateOptions[dimension[0] + 'Plus'] ||
seriesStateOptions[dimension[0] + 'Plus'] || 0);
// Align marker by a new size.
attribs[dimension[1]] =
shapeArgs[dimension[1]] +
(shapeArgs[dimension[0]] -
attribs[dimension[0]]) / 2;
});
}
return state ? attribs : shapeArgs;
};
/**
* @private
*/
HeatmapSeries.prototype.pointAttribs = function (point, state) {
var series = this,
attr = Series.prototype.pointAttribs.call(series,
point,
state),
seriesOptions = series.options || {},
plotOptions = series.chart.options.plotOptions || {},
seriesPlotOptions = plotOptions.series || {},
heatmapPlotOptions = plotOptions.heatmap || {},
stateOptions,
brightness,
// Get old properties in order to keep backward compatibility
borderColor = (point && point.options.borderColor) ||
seriesOptions.borderColor ||
heatmapPlotOptions.borderColor ||
seriesPlotOptions.borderColor,
borderWidth = (point && point.options.borderWidth) ||
seriesOptions.borderWidth ||
heatmapPlotOptions.borderWidth ||
seriesPlotOptions.borderWidth ||
attr['stroke-width'];
// Apply lineColor, or set it to default series color.
attr.stroke = ((point && point.marker && point.marker.lineColor) ||
(seriesOptions.marker && seriesOptions.marker.lineColor) ||
borderColor ||
this.color);
// Apply old borderWidth property if exists.
attr['stroke-width'] = borderWidth;
if (state) {
stateOptions =
merge(seriesOptions.states[state], seriesOptions.marker &&
seriesOptions.marker.states[state], point &&
point.options.states &&
point.options.states[state] || {});
brightness = stateOptions.brightness;
attr.fill =
stateOptions.color ||
Color.parse(attr.fill).brighten(brightness || 0).get();
attr.stroke = stateOptions.lineColor;
}
return attr;
};
/**
* @private
*/
HeatmapSeries.prototype.setClip = function (animation) {
var series = this,
chart = series.chart;
Series.prototype.setClip.apply(series, arguments);
if (series.options.clip !== false || animation) {
series.markerGroup
.clip((animation || series.clipBox) && series.sharedClipKey ?
chart.sharedClips[series.sharedClipKey] :
chart.clipRect);
}
};
/**
* @private
*/
HeatmapSeries.prototype.translate = function () {
var series = this, options = series.options, symbol = options.marker && options.marker.symbol || 'rect', shape = symbols[symbol] ? symbol : 'rect', hasRegularShape = ['circle', 'square'].indexOf(shape) !== -1;
series.generatePoints();
series.points.forEach(function (point) {
var pointAttr,
sizeDiff,
hasImage,
cellAttr = point.getCellAttributes(),
shapeArgs = {};
shapeArgs.x = Math.min(cellAttr.x1, cellAttr.x2);
shapeArgs.y = Math.min(cellAttr.y1, cellAttr.y2);
shapeArgs.width = Math.max(Math.abs(cellAttr.x2 - cellAttr.x1), 0);
shapeArgs.height = Math.max(Math.abs(cellAttr.y2 - cellAttr.y1), 0);
hasImage = point.hasImage =
(point.marker && point.marker.symbol || symbol || '')
.indexOf('url') === 0;
// If marker shape is regular (symetric), find shorter
// cell's side.
if (hasRegularShape) {
sizeDiff = Math.abs(shapeArgs.width - shapeArgs.height);
shapeArgs.x = Math.min(cellAttr.x1, cellAttr.x2) +
(shapeArgs.width < shapeArgs.height ? 0 : sizeDiff / 2);
shapeArgs.y = Math.min(cellAttr.y1, cellAttr.y2) +
(shapeArgs.width < shapeArgs.height ? sizeDiff / 2 : 0);
shapeArgs.width = shapeArgs.height =
Math.min(shapeArgs.width, shapeArgs.height);
}
pointAttr = {
plotX: (cellAttr.x1 + cellAttr.x2) / 2,
plotY: (cellAttr.y1 + cellAttr.y2) / 2,
clientX: (cellAttr.x1 + cellAttr.x2) / 2,
shapeType: 'path',
shapeArgs: merge(true, shapeArgs, {
d: symbols[shape](shapeArgs.x, shapeArgs.y, shapeArgs.width, shapeArgs.height)
})
};
if (hasImage) {
point.marker = {
width: shapeArgs.width,
height: shapeArgs.height
};
}
extend(point, pointAttr);
});
fireEvent(series, 'afterTranslate');
};
/**
* A heatmap is a graphical representation of data where the individual
* values contained in a matrix are represented as colors.
*
* @productdesc {highcharts}
* Requires `modules/heatmap`.
*
* @sample highcharts/demo/heatmap/
* Simple heatmap
* @sample highcharts/demo/heatmap-canvas/
* Heavy heatmap
*
* @extends plotOptions.scatter
* @excluding animationLimit, connectEnds, connectNulls, cropThreshold,
* dashStyle, findNearestPointBy, getExtremesFromAll, jitter,
* linecap, lineWidth, pointInterval, pointIntervalUnit,
* pointRange, pointStart, shadow, softThreshold, stacking,
* step, threshold, cluster
* @product highcharts highmaps
* @optionparent plotOptions.heatmap
*/
HeatmapSeries.defaultOptions = merge(ScatterSeries.defaultOptions, {
/**
* Animation is disabled by default on the heatmap series.
*/
animation: false,
/**
* The border radius for each heatmap item.
*/
borderRadius: 0,
/**
* The border width for each heatmap item.
*/
borderWidth: 0,
/**
* Padding between the points in the heatmap.
*
* @type {number}
* @default 0
* @since 6.0
* @apioption plotOptions.heatmap.pointPadding
*/
/**
* @default value
* @apioption plotOptions.heatmap.colorKey
*/
/**
* The main color of the series. In heat maps this color is rarely used,
* as we mostly use the color to denote the value of each point. Unless
* options are set in the [colorAxis](#colorAxis), the default value
* is pulled from the [options.colors](#colors) array.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 4.0
* @product highcharts
* @apioption plotOptions.heatmap.color
*/
/**
* The column size - how many X axis units each column in the heatmap
* should span.
*
* @sample {highcharts} maps/demo/heatmap/
* One day
* @sample {highmaps} maps/demo/heatmap/
* One day
*
* @type {number}
* @default 1
* @since 4.0
* @product highcharts highmaps
* @apioption plotOptions.heatmap.colsize
*/
/**
* The row size - how many Y axis units each heatmap row should span.
*
* @sample {highcharts} maps/demo/heatmap/
* 1 by default
* @sample {highmaps} maps/demo/heatmap/
* 1 by default
*
* @type {number}
* @default 1
* @since 4.0
* @product highcharts highmaps
* @apioption plotOptions.heatmap.rowsize
*/
/**
* The color applied to null points. In styled mode, a general CSS class
* is applied instead.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
*/
nullColor: "#f7f7f7" /* neutralColor3 */,
dataLabels: {
formatter: function () {
var numberFormatter = this.series.chart.numberFormatter;
var value = this.point.value;
return isNumber(value) ? numberFormatter(value, -1) : '';
},
inside: true,
verticalAlign: 'middle',
crop: false,
overflow: false,
padding: 0 // #3837
},
/**
* @excluding radius, enabledThreshold
* @since 8.1
*/
marker: {
/**
* A predefined shape or symbol for the marker. When undefined, the
* symbol is pulled from options.symbols. Other possible values are
* `'circle'`, `'square'`,`'diamond'`, `'triangle'`,
* `'triangle-down'`, `'rect'`, and `'ellipse'`.
*
* Additionally, the URL to a graphic can be given on this form:
* `'url(graphic.png)'`. Note that for the image to be applied to
* exported charts, its URL needs to be accessible by the export
* server.
*
* Custom callbacks for symbol path generation can also be added to
* `Highcharts.SVGRenderer.prototype.symbols`. The callback is then
* used by its method name, as shown in the demo.
*
* @sample {highcharts} highcharts/plotoptions/series-marker-symbol/
* Predefined, graphic and custom markers
* @sample {highstock} highcharts/plotoptions/series-marker-symbol/
* Predefined, graphic and custom markers
*/
symbol: 'rect',
/** @ignore-option */
radius: 0,
lineColor: void 0,
states: {
/**
* @excluding radius, radiusPlus
*/
hover: {
/**
* Set the marker's fixed width on hover state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption plotOptions.heatmap.marker.states.hover.width
*/
/**
* Set the marker's fixed height on hover state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption plotOptions.heatmap.marker.states.hover.height
*/
/**
* The number of pixels to increase the width of the
* selected point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* 20px greater width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption plotOptions.heatmap.marker.states.hover.widthPlus
*/
/**
* The number of pixels to increase the height of the
* selected point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* 20px greater width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption plotOptions.heatmap.marker.states.hover.heightPlus
*/
/**
* The additional line width for a hovered point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-linewidthplus
* 5 pixels wider lineWidth on hover
* @sample {highmaps} maps/plotoptions/heatmap-marker-states-hover-linewidthplus
* 5 pixels wider lineWidth on hover
*/
lineWidthPlus: 0
},
/**
* @excluding radius
*/
select: {
/**
* Set the marker's fixed width on select state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption plotOptions.heatmap.marker.states.select.width
*/
/**
* Set the marker's fixed height on select state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption plotOptions.heatmap.marker.states.select.height
*/
/**
* The number of pixels to increase the width of the
* selected point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* 20px greater width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption plotOptions.heatmap.marker.states.select.widthPlus
*/
/**
* The number of pixels to increase the height of the
* selected point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* 20px greater width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption plotOptions.heatmap.marker.states.select.heightPlus
*/
}
}
},
clip: true,
/** @ignore-option */
pointRange: null,
tooltip: {
pointFormat: '{point.x}, {point.y}: {point.value}<br/>'
},
states: {
hover: {
/** @ignore-option */
halo: false,
/**
* How much to brighten the point on interaction. Requires the
* main color to be defined in hex or rgb(a) format.
*
* In styled mode, the hover brightening is by default replaced
* with a fill-opacity set in the `.highcharts-point:hover`
* rule.
*/
brightness: 0.2
}
}
});
return HeatmapSeries;
}(ScatterSeries));
extend(HeatmapSeries.prototype, {
/**
* @private
*/
alignDataLabel: ColumnSeries.prototype.alignDataLabel,
axisTypes: ColorMapMixin.SeriesMixin.axisTypes,
colorAttribs: ColorMapMixin.SeriesMixin.colorAttribs,
colorKey: ColorMapMixin.SeriesMixin.colorKey,
directTouch: true,
/**
* @private
*/
drawLegendSymbol: LegendSymbol.drawRectangle,
getExtremesFromAll: true,
getSymbol: Series.prototype.getSymbol,
parallelArrays: ColorMapMixin.SeriesMixin.parallelArrays,
pointArrayMap: ['y', 'value'],
pointClass: HeatmapPoint,
trackerGroups: ColorMapMixin.SeriesMixin.trackerGroups
});
SeriesRegistry.registerSeriesType('heatmap', HeatmapSeries);
/* *
*
* Default Export
*
* */
/* *
*
* API Declarations
*
* */
/**
* Heatmap series only. Padding between the points in the heatmap.
* @name Highcharts.Point#pointPadding
* @type {number|undefined}
*/
/**
* Heatmap series only. The value of the point, resulting in a color
* controled by options as set in the colorAxis configuration.
* @name Highcharts.Point#value
* @type {number|null|undefined}
*/
/* *
* @interface Highcharts.PointOptionsObject in parts/Point.ts
*/ /**
* Heatmap series only. Point padding for a single point.
* @name Highcharts.PointOptionsObject#pointPadding
* @type {number|undefined}
*/ /**
* Heatmap series only. The value of the point, resulting in a color controled
* by options as set in the colorAxis configuration.
* @name Highcharts.PointOptionsObject#value
* @type {number|null|undefined}
*/
''; // detach doclets above
/* *
*
* API Options
*
* */
/**
* A `heatmap` series. If the [type](#series.heatmap.type) option is
* not specified, it is inherited from [chart.type](#chart.type).
*
* @productdesc {highcharts}
* Requires `modules/heatmap`.
*
* @extends series,plotOptions.heatmap
* @excluding cropThreshold, dataParser, dataURL, pointRange, stack,
* @product highcharts highmaps
* @apioption series.heatmap
*/
/**
* An array of data points for the series. For the `heatmap` series
* type, points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values
* correspond to `x,y,value`. If the first value is a string, it is
* applied as the name of the point, and the `x` value is inferred.
* The `x` value can also be omitted, in which case the inner arrays
* should be of length 2\. Then the `x` value is automatically calculated,
* either starting at 0 and incremented by 1, or from `pointStart`
* and `pointInterval` given in the series options.
*
* ```js
* data: [
* [0, 9, 7],
* [1, 10, 4],
* [2, 6, 3]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of data
* points exceeds the series' [turboThreshold](#series.heatmap.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* x: 1,
* y: 3,
* value: 10,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 7,
* value: 10,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<Array<number>|*>}
* @extends series.line.data
* @product highcharts highmaps
* @apioption series.heatmap.data
*/
/**
* The color of the point. In heat maps the point color is rarely set
* explicitly, as we use the color to denote the `value`. Options for
* this are set in the [colorAxis](#colorAxis) configuration.
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highmaps
* @apioption series.heatmap.data.color
*/
/**
* The value of the point, resulting in a color controled by options
* as set in the [colorAxis](#colorAxis) configuration.
*
* @type {number}
* @product highcharts highmaps
* @apioption series.heatmap.data.value
*/
/**
* The x value of the point. For datetime axes,
* the X value is the timestamp in milliseconds since 1970.
*
* @type {number}
* @product highcharts highmaps
* @apioption series.heatmap.data.x
*/
/**
* The y value of the point.
*
* @type {number}
* @product highcharts highmaps
* @apioption series.heatmap.data.y
*/
/**
* Point padding for a single point.
*
* @sample maps/plotoptions/tilemap-pointpadding
* Point padding on tiles
*
* @type {number}
* @product highcharts highmaps
* @apioption series.heatmap.data.pointPadding
*/
/**
* @excluding radius, enabledThreshold
* @product highcharts highmaps
* @since 8.1
* @apioption series.heatmap.data.marker
*/
/**
* @excluding radius, enabledThreshold
* @product highcharts highmaps
* @since 8.1
* @apioption series.heatmap.marker
*/
/**
* @excluding radius, radiusPlus
* @product highcharts highmaps
* @apioption series.heatmap.marker.states.hover
*/
/**
* @excluding radius
* @product highcharts highmaps
* @apioption series.heatmap.marker.states.select
*/
/**
* @excluding radius, radiusPlus
* @product highcharts highmaps
* @apioption series.heatmap.data.marker.states.hover
*/
/**
* @excluding radius
* @product highcharts highmaps
* @apioption series.heatmap.data.marker.states.select
*/
/**
* Set the marker's fixed width on hover state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-linewidthplus
* 5 pixels wider lineWidth on hover
*
* @type {number|undefined}
* @default 0
* @product highcharts highmaps
* @apioption series.heatmap.marker.states.hover.lineWidthPlus
*/
/**
* Set the marker's fixed width on hover state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.marker.states.hover.width
*/
/**
* Set the marker's fixed height on hover state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.marker.states.hover.height
*/
/**
* The number of pixels to increase the width of the
* hovered point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* One day
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.marker.states.hover.widthPlus
*/
/**
* The number of pixels to increase the height of the
* hovered point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* One day
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.marker.states.hover.heightPlus
*/
/**
* The number of pixels to increase the width of the
* hovered point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* One day
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.marker.states.select.widthPlus
*/
/**
* The number of pixels to increase the height of the
* hovered point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* One day
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.marker.states.select.heightPlus
*/
/**
* Set the marker's fixed width on hover state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-linewidthplus
* 5 pixels wider lineWidth on hover
*
* @type {number|undefined}
* @default 0
* @product highcharts highmaps
* @apioption series.heatmap.data.marker.states.hover.lineWidthPlus
*/
/**
* Set the marker's fixed width on hover state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.data.marker.states.hover.width
*/
/**
* Set the marker's fixed height on hover state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.data.marker.states.hover.height
*/
/**
* The number of pixels to increase the width of the
* hovered point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* One day
*
* @type {number|undefined}
* @default undefined
* @product highcharts highstock
* @apioption series.heatmap.data.marker.states.hover.widthPlus
*/
/**
* The number of pixels to increase the height of the
* hovered point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* One day
*
* @type {number|undefined}
* @default undefined
* @product highcharts highstock
* @apioption series.heatmap.data.marker.states.hover.heightPlus
*/
/**
* Set the marker's fixed width on select state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.data.marker.states.select.width
*/
/**
* Set the marker's fixed height on select state.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-width
* 70px fixed marker's width and height on hover
*
* @type {number|undefined}
* @default undefined
* @product highcharts highmaps
* @apioption series.heatmap.data.marker.states.select.height
*/
/**
* The number of pixels to increase the width of the
* hovered point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* One day
*
* @type {number|undefined}
* @default undefined
* @product highcharts highstock
* @apioption series.heatmap.data.marker.states.select.widthPlus
*/
/**
* The number of pixels to increase the height of the
* hovered point.
*
* @sample {highcharts} maps/plotoptions/heatmap-marker-states-hover-widthplus
* One day
*
* @type {number|undefined}
* @default undefined
* @product highcharts highstock
* @apioption series.heatmap.data.marker.states.select.heightPlus
*/
''; // adds doclets above to transpiled file
return HeatmapSeries;
});
_registerModule(_modules, 'Extensions/GeoJSON.js', [_modules['Core/Chart/Chart.js'], _modules['Core/FormatUtilities.js'], _modules['Core/Globals.js'], _modules['Core/Utilities.js']], function (Chart, F, H, U) {
/* *
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var format = F.format;
var win = H.win;
var error = U.error,
extend = U.extend,
merge = U.merge,
wrap = U.wrap;
/**
* Represents the loose structure of a geographic JSON file.
*
* @interface Highcharts.GeoJSON
*/ /**
* Full copyright note of the geographic data.
* @name Highcharts.GeoJSON#copyright
* @type {string|undefined}
*/ /**
* Short copyright note of the geographic data suitable for watermarks.
* @name Highcharts.GeoJSON#copyrightShort
* @type {string|undefined}
*/ /**
* Additional meta information based on the coordinate reference system.
* @name Highcharts.GeoJSON#crs
* @type {Highcharts.Dictionary<any>|undefined}
*/ /**
* Data sets of geographic features.
* @name Highcharts.GeoJSON#features
* @type {Array<Highcharts.GeoJSONFeature>}
*/ /**
* Map projections and transformations to be used when calculating between
* lat/lon and chart values. Required for lat/lon support on maps. Allows
* resizing, rotating, and moving portions of a map within its projected
* coordinate system while still retaining lat/lon support. If using lat/lon
* on a portion of the map that does not match a `hitZone`, the definition with
* the key `default` is used.
* @name Highcharts.GeoJSON#hc-transform
* @type {Highcharts.Dictionary<Highcharts.GeoJSONTranslation>|undefined}
*/ /**
* Title of the geographic data.
* @name Highcharts.GeoJSON#title
* @type {string|undefined}
*/ /**
* Type of the geographic data. Type of an optimized map collection is
* `FeatureCollection`.
* @name Highcharts.GeoJSON#type
* @type {string|undefined}
*/ /**
* Version of the geographic data.
* @name Highcharts.GeoJSON#version
* @type {string|undefined}
*/
/**
* Data set of a geographic feature.
* @interface Highcharts.GeoJSONFeature
* @extends Highcharts.Dictionary<*>
*/ /**
* Data type of the geographic feature.
* @name Highcharts.GeoJSONFeature#type
* @type {string}
*/
/**
* Describes the map projection and transformations applied to a portion of
* a map.
* @interface Highcharts.GeoJSONTranslation
*/ /**
* The coordinate reference system used to generate this portion of the map.
* @name Highcharts.GeoJSONTranslation#crs
* @type {string}
*/ /**
* Define the portion of the map that this defintion applies to. Defined as a
* GeoJSON polygon feature object, with `type` and `coordinates` properties.
* @name Highcharts.GeoJSONTranslation#hitZone
* @type {Highcharts.Dictionary<*>|undefined}
*/ /**
* Property for internal use for maps generated by Highsoft.
* @name Highcharts.GeoJSONTranslation#jsonmarginX
* @type {number|undefined}
*/ /**
* Property for internal use for maps generated by Highsoft.
* @name Highcharts.GeoJSONTranslation#jsonmarginY
* @type {number|undefined}
*/ /**
* Property for internal use for maps generated by Highsoft.
* @name Highcharts.GeoJSONTranslation#jsonres
* @type {number|undefined}
*/ /**
* Specifies clockwise rotation of the coordinates after the projection, but
* before scaling and panning. Defined in radians, relative to the coordinate
* system origin.
* @name Highcharts.GeoJSONTranslation#rotation
* @type {number|undefined}
*/ /**
* The scaling factor applied to the projected coordinates.
* @name Highcharts.GeoJSONTranslation#scale
* @type {number|undefined}
*/ /**
* Property for internal use for maps generated by Highsoft.
* @name Highcharts.GeoJSONTranslation#xoffset
* @type {number|undefined}
*/ /**
* X offset of projected coordinates after scaling.
* @name Highcharts.GeoJSONTranslation#xpan
* @type {number|undefined}
*/ /**
* Property for internal use for maps generated by Highsoft.
* @name Highcharts.GeoJSONTranslation#yoffset
* @type {number|undefined}
*/ /**
* Y offset of projected coordinates after scaling.
* @name Highcharts.GeoJSONTranslation#ypan
* @type {number|undefined}
*/
/**
* Result object of a map transformation.
*
* @interface Highcharts.MapCoordinateObject
*/ /**
* X coordinate on the map.
* @name Highcharts.MapCoordinateObject#x
* @type {number}
*/ /**
* Y coordinate on the map.
* @name Highcharts.MapCoordinateObject#y
* @type {number|null}
*/
/**
* A latitude/longitude object.
*
* @interface Highcharts.MapLatLonObject
*/ /**
* The latitude.
* @name Highcharts.MapLatLonObject#lat
* @type {number}
*/ /**
* The longitude.
* @name Highcharts.MapLatLonObject#lon
* @type {number}
*/
/**
* An array of longitude, latitude.
*
* @typedef {Array<number>} Highcharts.LonLatArray
*/
''; // detach doclets above
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Test for point in polygon. Polygon defined as array of [x,y] points.
* @private
*/
function pointInPolygon(point, polygon) {
var i,
j,
rel1,
rel2,
c = false,
x = point.x,
y = point.y;
for (i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
rel1 = polygon[i][1] > y;
rel2 = polygon[j][1] > y;
if (rel1 !== rel2 &&
(x < (polygon[j][0] -
polygon[i][0]) * (y - polygon[i][1]) /
(polygon[j][1] - polygon[i][1]) +
polygon[i][0])) {
c = !c;
}
}
return c;
}
/**
* Highmaps only. Get point from latitude and longitude using specified
* transform definition.
*
* @requires modules/map
*
* @sample maps/series/latlon-transform/
* Use specific transformation for lat/lon
*
* @function Highcharts.Chart#transformFromLatLon
*
* @param {Highcharts.MapLatLonObject} latLon
* A latitude/longitude object.
*
* @param {*} transform
* The transform definition to use as explained in the
* {@link https://www.highcharts.com/docs/maps/latlon|documentation}.
*
* @return {Highcharts.MapCoordinateObject}
* An object with `x` and `y` properties.
*/
Chart.prototype.transformFromLatLon = function (latLon, transform) {
/**
* Allows to manually load the proj4 library from Highcharts options
* instead of the `window`.
* In case of loading the library from a `script` tag,
* this option is not needed, it will be loaded from there by default.
*
* @type {Function}
* @product highmaps
* @apioption chart.proj4
*/
var proj4 = this.options.chart.proj4 || win.proj4;
if (!proj4) {
error(21, false, this);
return {
x: 0,
y: null
};
}
var _a = transform.jsonmarginX,
jsonmarginX = _a === void 0 ? 0 : _a,
_b = transform.jsonmarginY,
jsonmarginY = _b === void 0 ? 0 : _b,
_c = transform.jsonres,
jsonres = _c === void 0 ? 1 : _c,
_d = transform.scale,
scale = _d === void 0 ? 1 : _d,
_e = transform.xoffset,
xoffset = _e === void 0 ? 0 : _e,
_f = transform.xpan,
xpan = _f === void 0 ? 0 : _f,
_g = transform.yoffset,
yoffset = _g === void 0 ? 0 : _g,
_h = transform.ypan,
ypan = _h === void 0 ? 0 : _h;
var projected = proj4(transform.crs,
[latLon.lon,
latLon.lat]),
cosAngle = transform.cosAngle ||
(transform.rotation && Math.cos(transform.rotation)),
sinAngle = transform.sinAngle ||
(transform.rotation && Math.sin(transform.rotation)),
rotated = transform.rotation ? [
projected[0] * cosAngle + projected[1] * sinAngle,
-projected[0] * sinAngle + projected[1] * cosAngle
] : projected;
return {
x: ((rotated[0] - xoffset) * scale + xpan) * jsonres + jsonmarginX,
y: -(((yoffset - rotated[1]) * scale + ypan) * jsonres - jsonmarginY)
};
};
/**
* Highmaps only. Get latLon from point using specified transform definition.
* The method returns an object with the numeric properties `lat` and `lon`.
*
* @requires modules/map
*
* @sample maps/series/latlon-transform/
* Use specific transformation for lat/lon
*
* @function Highcharts.Chart#transformToLatLon
*
* @param {Highcharts.Point|Highcharts.MapCoordinateObject} point
* A `Point` instance, or any object containing the properties `x` and
* `y` with numeric values.
*
* @param {*} transform
* The transform definition to use as explained in the
* {@link https://www.highcharts.com/docs/maps/latlon|documentation}.
*
* @return {Highcharts.MapLatLonObject|undefined}
* An object with `lat` and `lon` properties.
*/
Chart.prototype.transformToLatLon = function (point, transform) {
var proj4 = this.options.chart.proj4 || win.proj4;
if (!proj4) {
error(21, false, this);
return;
}
if (point.y === null) {
return;
}
var _a = transform.jsonmarginX,
jsonmarginX = _a === void 0 ? 0 : _a,
_b = transform.jsonmarginY,
jsonmarginY = _b === void 0 ? 0 : _b,
_c = transform.jsonres,
jsonres = _c === void 0 ? 1 : _c,
_d = transform.scale,
scale = _d === void 0 ? 1 : _d,
_e = transform.xoffset,
xoffset = _e === void 0 ? 0 : _e,
_f = transform.xpan,
xpan = _f === void 0 ? 0 : _f,
_g = transform.yoffset,
yoffset = _g === void 0 ? 0 : _g,
_h = transform.ypan,
ypan = _h === void 0 ? 0 : _h;
var normalized = {
x: ((point.x - jsonmarginX) / jsonres - xpan) / scale + xoffset,
y: ((point.y - jsonmarginY) / jsonres + ypan) / scale + yoffset
},
cosAngle = transform.cosAngle ||
(transform.rotation && Math.cos(transform.rotation)),
sinAngle = transform.sinAngle ||
(transform.rotation && Math.sin(transform.rotation)),
// Note: Inverted sinAngle to reverse rotation direction
projected = win.proj4(transform.crs, 'WGS84',
transform.rotation ? {
x: normalized.x * cosAngle + normalized.y * -sinAngle,
y: normalized.x * sinAngle + normalized.y * cosAngle
} : normalized);
return { lat: projected.y, lon: projected.x };
};
/**
* Highmaps only. Calculate latitude/longitude values for a point. Returns an
* object with the numeric properties `lat` and `lon`.
*
* @requires modules/map
*
* @sample maps/demo/latlon-advanced/
* Advanced lat/lon demo
*
* @function Highcharts.Chart#fromPointToLatLon
*
* @param {Highcharts.Point|Highcharts.MapCoordinateObject} point
* A `Point` instance or anything containing `x` and `y` properties with
* numeric values.
*
* @return {Highcharts.MapLatLonObject|undefined}
* An object with `lat` and `lon` properties.
*/
Chart.prototype.fromPointToLatLon = function (point) {
var transforms = this.mapTransforms;
if (!transforms) {
error(22, false, this);
return;
}
for (var transform in transforms) {
if (Object.hasOwnProperty.call(transforms, transform) &&
transforms[transform].hitZone &&
pointInPolygon(point, transforms[transform].hitZone.coordinates[0])) {
return this.transformToLatLon(point, transforms[transform]);
}
}
return this.transformToLatLon(point, transforms['default'] // eslint-disable-line dot-notation
);
};
/**
* Highmaps only. Get chart coordinates from latitude/longitude. Returns an
* object with x and y values corresponding to the `xAxis` and `yAxis`.
*
* @requires modules/map
*
* @sample maps/series/latlon-to-point/
* Find a point from lat/lon
*
* @function Highcharts.Chart#fromLatLonToPoint
*
* @param {Highcharts.MapLatLonObject} latLon
* Coordinates.
*
* @return {Highcharts.MapCoordinateObject}
* X and Y coordinates in terms of chart axis values.
*/
Chart.prototype.fromLatLonToPoint = function (latLon) {
var transforms = this.mapTransforms,
transform,
coords;
if (!transforms) {
error(22, false, this);
return {
x: 0,
y: null
};
}
for (transform in transforms) {
if (Object.hasOwnProperty.call(transforms, transform) &&
transforms[transform].hitZone) {
coords = this.transformFromLatLon(latLon, transforms[transform]);
if (pointInPolygon(coords, transforms[transform].hitZone.coordinates[0])) {
return coords;
}
}
}
return this.transformFromLatLon(latLon, transforms['default'] // eslint-disable-line dot-notation
);
};
/**
* Highmaps only. Restructure a GeoJSON object in preparation to be read
* directly by the
* {@link https://api.highcharts.com/highmaps/plotOptions.series.mapData|series.mapData}
* option. The GeoJSON will be broken down to fit a specific Highcharts type,
* either `map`, `mapline` or `mappoint`. Meta data in GeoJSON's properties
* object will be copied directly over to {@link Point.properties} in Highmaps.
*
* @requires modules/map
*
* @sample maps/demo/geojson/
* Simple areas
* @sample maps/demo/geojson-multiple-types/
* Multiple types
*
* @function Highcharts.geojson
*
* @param {Highcharts.GeoJSON} geojson
* The GeoJSON structure to parse, represented as a JavaScript object
* rather than a JSON string.
*
* @param {string} [hType=map]
* The Highmaps series type to prepare for. Setting "map" will return
* GeoJSON polygons and multipolygons. Setting "mapline" will return
* GeoJSON linestrings and multilinestrings. Setting "mappoint" will
* return GeoJSON points and multipoints.
*
* @return {Array<*>}
* An object ready for the `mapData` option.
*/
H.geojson = function (geojson, hType, series) {
if (hType === void 0) { hType = 'map'; }
var mapData = [];
var path = [];
geojson.features.forEach(function (feature) {
var geometry = feature.geometry || {},
type = geometry.type,
coordinates = geometry.coordinates,
properties = feature.properties,
pointOptions;
path = [];
if ((hType === 'map' || hType === 'mapbubble') &&
(type === 'Polygon' || type === 'MultiPolygon')) {
if (coordinates.length) {
pointOptions = { geometry: { coordinates: coordinates, type: type } };
}
}
else if (hType === 'mapline' &&
(type === 'LineString' ||
type === 'MultiLineString')) {
if (coordinates.length) {
pointOptions = { geometry: { coordinates: coordinates, type: type } };
}
}
else if (hType === 'mappoint' && type === 'Point') {
if (coordinates.length) {
pointOptions = { geometry: { coordinates: coordinates, type: type } };
}
}
if (pointOptions) {
mapData.push(extend(pointOptions, {
name: properties.name || properties.NAME,
/**
* In Highmaps, when data is loaded from GeoJSON, the GeoJSON
* item's properies are copied over here.
*
* @requires modules/map
* @name Highcharts.Point#properties
* @type {*}
*/
properties: properties
}));
}
});
// Create a credits text that includes map source, to be picked up in
// Chart.addCredits
if (series && geojson.copyrightShort) {
series.chart.mapCredits = format(series.chart.options.credits.mapText, { geojson: geojson });
series.chart.mapCreditsFull = format(series.chart.options.credits.mapTextFull, { geojson: geojson });
}
return mapData;
};
// Override addCredits to include map source by default
wrap(Chart.prototype, 'addCredits', function (proceed, credits) {
credits = merge(true, this.options.credits, credits);
// Disable credits link if map credits enabled. This to allow for in-text
// anchors.
if (this.mapCredits) {
credits.href = null;
}
proceed.call(this, credits);
// Add full map credits to hover
if (this.credits && this.mapCreditsFull) {
this.credits.attr({
title: this.mapCreditsFull
});
}
});
});
_registerModule(_modules, 'masters/modules/map.src.js', [_modules['Core/Globals.js'], _modules['Core/Axis/Color/ColorAxis.js'], _modules['Series/MapBubble/MapBubbleSeries.js'], _modules['Core/Chart/MapChart.js']], function (Highcharts, ColorAxis, MapBubbleSeries, MapChart) {
var G = Highcharts;
G.ColorAxis = ColorAxis;
G.MapChart = MapChart;
G.mapChart = G.Map = MapChart.mapChart;
G.maps = MapChart.maps;
ColorAxis.compose(G.Chart, G.Fx, G.Legend, G.Series);
MapBubbleSeries.compose(G.Chart, G.Legend, G.Series);
});
})); |
import type { Reducer, Store } from "redux";
declare module "redux-oidc" {
declare type UserManager = {
signinRedirect: (data?: {
data: {
redirectUrl: string
}
}) => Promise<*>,
signoutRedirect: () => Promise<*>
};
declare type User<P> = {
id_token: string,
access_token: string,
token_type: string,
scope: string,
expires_at: number,
+expires_in: ?boolean,
+expired: ?boolean,
+scopes: Array<string>,
profile: P,
state: {
redirectUrl: string
}
};
declare type UserManagerSettings = {|
client_id: string,
authority: string,
redirect_uri: string,
response_type?: string,
scope?: string,
loadUserInfo?: boolean,
silent_redirect_uri?: string,
automaticSilentRenew?: boolean,
accessTokenExpiringNotificationTime?: number,
silentRequestTimeout?: number,
filterProtocolClaims?: boolean
|};
declare type OidcReducerState = {
user: ?User<*>
};
declare type OidcReducer = Reducer<OidcReducerState, *>;
declare function createUserManager(
settings: UserManagerSettings
): UserManager;
declare var reducer: OidcReducer;
declare class CallbackComponent extends React$Component<{
userManager: UserManager,
successCallback: (user?: User<*>) => mixed,
errorCallback?: () => mixed
}> {}
declare class OidcProvider extends React$Component<{
store: Store<*, *>,
userManager: UserManager
}> {}
declare function processSilentRenew(): void;
}
|
// common (server and client) github methods
Meteor.methods({
//////////////////
// REPO MANAGEMENT
//////////////////
updateRepo() { // update when repo was last updated
return Meteor.users.update(
{"_id": Meteor.userId()},
{$set : {
"profile.lastUpdated": new Date(),
}});
},
loadRepo(gr) { // load a repo into code pilot
Meteor.call("setRepo", gr); // set the active project / repo
Meteor.call("initBranches", gr); // get all the possible branches
const branch = gr.repo.default_branch;
Meteor.call("setBranch", branch); // set branch
Meteor.call("initCommits"); // pull commit history for gr repo
// if has loaded files, then just set the repo
var anyFile = Files.findOne({repo: gr._id})
if (anyFile) return true;
Meteor.call("loadHead", branch); // load the head of gr branch into CP
const full = `${gr.repo.owner.login}/${gr.repo.name}`;
Meteor.call("addMessage", `started working on repo - ${full}`);
},
setRepo(gr) { // set git repo & default branch
return Meteor.users.update(
{"_id": Meteor.userId()},
{$set : {
"profile.repo": gr._id,
"profile.repoName": gr.repo.name,
"profile.repoOwner": gr.repo.owner.login,
"profile.repoBranch": gr.repo.owner.default_branch
}});
},
forkRepo(user, repo) { // create a fork
try { // if the repo exists/isForkable
Meteor.call("getRepo", user, repo);
// try to post a forked version on GH
Meteor.call("postRepo", user, repo);
// pull in the forked version
Meteor.call("getAllRepos");
} catch (err) { // this repo won't no fork
toastr.error(`couldn't fork repo '${repo}'`);
}
},
////////////////////
// BRANCH MANAGEMENT
////////////////////
// for the current repo, just overwrite branches with new
initBranches(gr) { // get all branches for this repo
const brs = Meteor.call("getBranches", gr); // res from github
Repos.update(gr._id, { $set: {branches: brs }});
},
addBranch(bn) { // create a new branch from branchname (bn)
const repo = Repos.findOne(Meteor.user().profile.repo);
const branch = Meteor.user().profile.repoBranch;
const parent = Meteor.call("getBranch", branch).commit.sha;
const newBranch = Meteor.call("postBranch", bn, parent);
Meteor.call("initBranches", repo);
Meteor.call("setBranch", bn);
Meteor.call("addMessage", `created branch - ${bn}`);
},
loadBranch(bn) { // load a repo into code pilot
Meteor.call("setBranch", bn); // set branch for current user
Meteor.call("initCommits"); // pull commit history for this repo
Meteor.call("loadHead", bn); // load the head of this branch into CP
Meteor.call("addMessage", `started working on branch - ${bn}`);
},
setBranch(bn) { // set branch name
return Meteor.users.update(
{"_id": Meteor.userId()},
{$set : {
"profile.repoBranch": bn,
}});
},
});
|
// Sets up a testing environment suitable for testing generated JS.
var _ = require('underscore');
var assert = require('assert');
var dependencies = require('../lib/dependencies');
var html = require('../lib/html');
var fs = require('fs');
var path = require('path');
var render = require('../lib/render');
var document;
var files = fs.readdirSync(__dirname);
var LOAD_WIDGETS = _.compact(files.map(function(x) {
if (x.match(/\.oak\.html$/)) {
return { filename: path.resolve(__dirname, x), type: 'oak' };
}
}));
function testBasic() {
var widget = new Widget(['foo']);
var model = { text: 'my button' };
widget.render(document.body, null, model);
assert.equal(widget.el('mydiv'), document.querySelector('div.foo > div'));
assert.equal(widget.el('mydiv').textContent, 'Foo my button.');
widget.emit('fill')({ text: 'new text' });
assert.equal(widget.el('mydiv').textContent, 'Foo new text.');
widget.dispose();
assert.ok(!document.querySelector('div.foo'));
}
function testList() {
var widget = new Widget(['list']);
var model = {
children: [
{ type: 'header', value: 'Numbers' },
{ type: 'item', value: 1 },
{ type: 'item', value: 2 }
]
};
widget.render(document.body, null, model);
var lis = document.querySelectorAll('li');
assert.equal(lis.length, 3);
assert.equal(lis[0].firstChild.tagName, 'H2');
assert.equal(lis[1].textContent, '1');
assert.equal(lis[2].textContent, '2');
assert.equal(widget.children().length, 3);
assert.equal(widget.children()[0].el(), lis[0]);
assert.equal(widget.children()[1].el(), lis[1]);
assert.equal(widget.children()[2].el(), lis[2]);
}
function testContainer() {
var widget = new Widget(['container']);
var model = { type: 'child', x: 'spam' };
widget.render(document.body, null, model);
assert.equal(widget.el().tagName, 'DIV');
//TODO
//var p = widget.el().firstElementChild;
//assert.equal(p.tagName, 'P');
//assert.equal(p.textContent, 'A paragraph of spam!');
}
// Set up browser-like environment.
document = html.parseHTML('').ownerDocument;
var utilJsName = path.resolve(__dirname, '../lib/public/util.js');
var utiljs = fs.readFileSync(utilJsName, 'utf-8');
eval(utiljs);
var widgetJsName = path.resolve(__dirname, '../lib/public/widget.js');
var widgetjs = fs.readFileSync(widgetJsName, 'utf-8');
eval(widgetjs);
// Generate tree and test our generated code.
var tree = new dependencies.tree(LOAD_WIDGETS, function(tree) {
var genwidgetjs = render.widgetJS(tree);
try {
eval(genwidgetjs);
testBasic();
testList();
testContainer();
} catch(e) {
console.log('genwidgetjs:');
console.log(genwidgetjs);
throw e;
}
});
|
var mediaTypes = require('../../mediaTypes');
// node-memcached implements string: 0, json: 2, binary: 4, numeric: 8
var nodeMcFlagMap = {
'text/plain': 0,
'application/json': 2,
'application/x-tome': 2,
'application/octet-stream': 4
};
var nodeMcFlagReverseMap = {
0: 'text/plain',
2: 'application/json',
4: 'application/octet-stream'
};
/**
* Turns uint32 into a max 4 char string.
* The node.js Buffer class provides a good uint32 conversion algorithm that we want to use.
*
* @param {number} flags
* @returns {string}
*/
function flagsToStr(flags) {
if (!flags) {
return;
}
var buff = new Buffer(4);
buff.writeUInt32BE(flags, 0);
// return a 0-byte terminated or 4-byte string
switch (0) {
case buff[0]:
return;
case buff[1]:
return buff.toString('utf8', 0, 1);
case buff[2]:
return buff.toString('utf8', 0, 2);
case buff[3]:
return buff.toString('utf8', 0, 3);
default:
return buff.toString();
}
}
/**
* Turns a max 4 char string into a uint32.
* The node.js Buffer class provides a good uint32 conversion algorithm that we want to use.
*
* @param {string} str
* @returns {number}
*/
function strToFlags(str) {
if (!str) {
return;
}
var buff = new Buffer([0, 0, 0, 0]);
buff.write(str, 0, 4, 'ascii');
return buff.readUInt32BE(0);
}
/**
* Turns a mediaType into a flags uint32
*
* @param {string} mediaType The mediaType to create flags for.
* @param {string} [flagStyle] The flag style to use. Use "node-memcached" for legacy compatibility.
* @returns {*}
*/
exports.createFlags = function (mediaType, flagStyle) {
// node-memcached compatibility
if (flagStyle === 'node-memcached' && nodeMcFlagMap.hasOwnProperty(mediaType)) {
return nodeMcFlagMap[mediaType];
}
// file ext approach
var mediaTypeApi = mediaTypes.getMediaType(mediaType);
if (mediaTypeApi) {
return strToFlags(mediaTypeApi.fileExt);
}
// fallback to buffer (node-memcached style)
return nodeMcFlagMap['application/octet-stream'];
};
/**
* Turns uint32 flags into a mediaType
*
* @param {number} flags
* @returns {string|undefined} The mediaType or undefined if undetectable
*/
exports.parseFlags = function (flags) {
if (typeof flags !== 'number') {
return;
}
// if the number is 0, 2 or 4, it's likely to have been created by node-memcached (or by
// us using the node-memcached flagging style)
// alternatively we assume flags represents a file extension
if (nodeMcFlagReverseMap[flags]) {
return nodeMcFlagReverseMap[flags];
}
var mediaTypeApi = mediaTypes.getByFileExt(flagsToStr(flags));
if (mediaTypeApi) {
return mediaTypeApi.mediaType;
}
};
/**
* Serializer for VaultValues for CouchbaseVault instances
*
* @param {VaultValue} value The VaultValue to serialize
* @returns {Object} An object containing the serialized data and the flags to store with it
*/
exports.serialize = function (value) {
if (Buffer.isBuffer(value.data)) {
return value.data;
}
// throws exceptions on failure
return value.setEncoding(['utf8']).data;
};
/**
* Deserializer for populating VaultValues from a CouchbaseVault
*
* @param {*} data The serialized data
* @param {string} [mediaType] The mediaType as detected through the flags
* @param {VaultValue} value The VaultValue to populate
*/
exports.deserialize = function (data, mediaType, value) {
// encoding should always be utf8, but we do a buffer check just in case
var encoding = Buffer.isBuffer(data) ? 'buffer' : 'utf8';
value.setDataFromVault(mediaType, data, encoding);
};
/**
* Creates a key from a topic and an index
*
* @param {string} topic The topic to target
* @param {Object} index The index to target
* @returns {string} The generated key
*/
exports.createKey = function (topic, index) {
// eg: weapons/actorId:123/bag:main
// eg: weapons/guildId:123
var key = topic + '', props, i;
if (index) {
props = Object.keys(index);
props.sort();
for (i = 0; i < props.length; i++) {
key += '/' + props[i] + ':' + index[props[i]];
}
}
return key;
};
/**
* Override this to have a custom shard behavior (takes a VaultValue as first argument)
*
* @returns {undefined}
*/
exports.shard = function (/* value */) {
return undefined;
};
|
function require(jspath) {
var scriptName = "seed.dev.js";
var r = new RegExp("(^|(.*?\\/))(" + scriptName + ")(\\?|$)"),
s = document.getElementsByTagName('script'),
src, m, l = "";
for(var i=0, len=s.length; i<len; i++) {
src = s[i].getAttribute('src');
if(src) {
m = src.match(r);
if(m) {
l = m[1];
break;
}
}
}
document.write('<script type="text/javascript" src="'+ l + jspath+'"><\/script>');
}
require("src/seed.js");
require("src/util.js");
require("src/grid.js");
require("src/source.js");
require("src/cache.js");
|
/**
* Provides requestAnimationFrame in a cross browser way.
* http://paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
if ( !window.requestAnimationFrame ) {
window.requestAnimationFrame = ( function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || // comment out if FF4 is slow (it caps framerate at ~30fps: https://bugzilla.mozilla.org/show_bug.cgi?id=630127)
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {
window.setTimeout( callback, 1000 / 40 );
};
} )();
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import Button from '../src';
describe('<Button /> component', function() {
it('should button exist', function() {
let _instance = ReactTestUtils.renderIntoDocument(<Button />);
expect(ReactTestUtils.isCompositeComponent(_instance)).toBeTruthy();
});
});
|
'use strict';
const _ = require( 'lodash' );
const bunyan = require( 'bunyan' );
const serializers = _.cloneDeep( bunyan.stdSerializers );
serializers.req = require( './serializers/req.js' );
module.exports = serializers;
|
'use strict';
var peleg = module.exports = exports = require('./lib');
|
'use strict'
var template = require('./toolbar.html')
function PlaylistToolbar($state, Mopidy) {
return {
restrict: 'E',
templateUrl: template,
scope: {
onPlayAll: '&'
},
controller: function($scope, $state) {
$scope.back = back;
function back() {
return $state.go('^')
}
}
}
}
module.exports = PlaylistToolbar |
// ==UserScript==
// @match http://battlelog.battlefield.com/*
// @run-at document-end
// ==/UserScript==
/* Battlelog Hacks
* http://benalman.com/
* Copyright (c) 2012 "Cowboy" Ben Alman; Licensed MIT */
var elem = document.createElement("script");
elem.src = "http://localhost:8000/";
document.body.appendChild(elem);
|
'use strict';
const assert = require('assert');
const context = require('../helpers/context');
describe('response.is(type)', function () {
it('should ignore params', function () {
const res = context().response;
res.type = 'text/html; charset=utf-8';
res.is('text/*').should.equal('text/html');
});
describe('when no type is set', function () {
it('should return false', function () {
const res = context().response;
assert(res.is() === false);
assert(res.is('html') === false);
});
});
describe('when given no types', function () {
it('should return the type', function () {
const res = context().response;
res.type = 'text/html; charset=utf-8';
res.is().should.equal('text/html');
});
});
describe('given one type', function () {
it('should return the type or false', function () {
const res = context().response;
res.type = 'image/png';
res.is('png').should.equal('png');
res.is('.png').should.equal('.png');
res.is('image/png').should.equal('image/png');
res.is('image/*').should.equal('image/png');
res.is('*/png').should.equal('image/png');
res.is('jpeg').should.be.false;
res.is('.jpeg').should.be.false;
res.is('image/jpeg').should.be.false;
res.is('text/*').should.be.false;
res.is('*/jpeg').should.be.false;
});
});
describe('given multiple types', function () {
it('should return the first match or false', function () {
const res = context().response;
res.type = 'image/png';
res.is('png').should.equal('png');
res.is('.png').should.equal('.png');
res.is('text/*', 'image/*').should.equal('image/png');
res.is('image/*', 'text/*').should.equal('image/png');
res.is('image/*', 'image/png').should.equal('image/png');
res.is('image/png', 'image/*').should.equal('image/png');
res.is(['text/*', 'image/*']).should.equal('image/png');
res.is(['image/*', 'text/*']).should.equal('image/png');
res.is(['image/*', 'image/png']).should.equal('image/png');
res.is(['image/png', 'image/*']).should.equal('image/png');
res.is('jpeg').should.be.false;
res.is('.jpeg').should.be.false;
res.is('text/*', 'application/*').should.be.false;
res.is('text/html', 'text/plain', 'application/json; charset=utf-8').should.be.false;
});
});
describe('when Content-Type: application/x-www-form-urlencoded', function () {
it('should match "urlencoded"', function () {
const res = context().response;
res.type = 'application/x-www-form-urlencoded';
res.is('urlencoded').should.equal('urlencoded');
res.is('json', 'urlencoded').should.equal('urlencoded');
res.is('urlencoded', 'json').should.equal('urlencoded');
});
});
});
|
/**
* @file surgeonCaseDetailMain.controller.js
* @namespace nocc.surgeon.controllers
* @author abidibo <abidibo@gmail.com>
*/
(function () {
'use strict';
angular
.module('nocc.surgeon.controllers')
.controller('SurgeonCaseDetailMainCtrl', SurgeonCaseDetailMainCtrl);
SurgeonCaseDetailMainCtrl.$inject = ['$rootScope', '$scope', '$state', '$window', 'authenticationService', 'contactService', 'caseService', 'therapeuticProposalService', 'therapyCardService', 'endTherapyCardService', 'followupService', 'dialogs', 'request', 'STATUS', 'THERAPEUTIC_PROPOSAL_TYPES', 'FU_STATUS_DICT', 'FU_TYPE_DICT'];
/**
* @namespace SurgeonCaseDetailMainCtrl
* @description Controller of the surgeon case detail view
* @permissions hasProfile
*/
function SurgeonCaseDetailMainCtrl($rootScope, $scope, $state, $window, authenticationService, contactService, caseService, therapeuticProposalService, therapyCardService, endTherapyCardService, followupService, dialogs, request, STATUS, THERAPEUTIC_PROPOSAL_TYPES, FU_STATUS_DICT, FU_TYPE_DICT) {
// inherits the $scope.model object from the parent controller
$scope.bar.actions = [];
switch($scope.model.caseObj.status) {
case STATUS.open:
statusOpen($scope, $state, $window, dialogs, caseService, STATUS);
break;
case STATUS.doctor_association:
statusDoctorAssociation($rootScope, $scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES);
break;
case STATUS.proposals:
statusProposals($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES);
break;
case STATUS.proposal_accepted:
statusProposalAccepted($scope, $state, $window, dialogs, caseService, therapyCardService, request, STATUS);
break;
case STATUS.therapy_card:
statusTherapyCard($scope, $window, dialogs, caseService, STATUS);
break;
case STATUS.started:
statusStarted($rootScope, $scope, $state, $window, dialogs, caseService, therapeuticProposalService, followupService, endTherapyCardService, request, STATUS, FU_STATUS_DICT, FU_TYPE_DICT);
break;
case STATUS.revaluation:
statusRevalutation($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES);
break;
case STATUS.revaluation_proposal:
statusRevaluationProposal($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES);
break;
case STATUS.revaluation_proposal_accepted:
statusRevaluationProposalAccepted($scope, $state, $window, dialogs, caseService, therapeuticProposalService, therapyCardService, request, STATUS);
break;
case STATUS.revaluation_therapy_card:
statusRevaluationTherapyCard($scope, $state, $window, dialogs, caseService, STATUS);
break;
case STATUS.revaluation_started:
statusRevaluationStarted($scope, $state, $window, dialogs, caseService, endTherapyCardService, request, STATUS);
break;
case STATUS.revaluation_ended:
case STATUS.completed:
statusCompleted($scope, $state, $window, dialogs, caseService, STATUS);
break;
case STATUS.adjuvant:
statusAdjuvant($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES);
break;
case STATUS.adjuvant_proposal:
statusAdjuvantProposal($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES);
break;
case STATUS.adjuvant_proposal_accepted:
statusAdjuvantProposalAccepted($scope, $state, $window, dialogs, caseService, therapyCardService, request, STATUS);
break;
case STATUS.adjuvant_therapy_card:
statusAdjuvantTherapyCard($scope, $state, $window, dialogs, caseService, STATUS);
break;
case STATUS.adjuvant_started:
statusAdjuvantStarted($scope, $state, $window, dialogs, caseService, therapeuticProposalService, followupService, endTherapyCardService, request, STATUS, FU_STATUS_DICT, FU_TYPE_DICT);
break;
case STATUS.ended:
statusEnded($scope, $state, $window, dialogs, caseService, therapeuticProposalService, contactService, followupService, request, STATUS, FU_STATUS_DICT, FU_TYPE_DICT);
break;
case STATUS.final_fu_ended:
statusFinalFUEnded($scope, $state, $window, dialogs, caseService, STATUS);
break;
case STATUS.relapse:
statusRelapse($scope, $state, $window, dialogs, caseService, STATUS);
break;
}
}
/**
* Open status
* Surgeon has to associate an oncologist and a radiotherapist who have to accept the case. I one of them refuses then the
* surgeon must choose another doctor till someone accepts
*/
function statusOpen($scope, $state, $window, dialogs, caseService, STATUS) {
$scope.associateOncologist = function() {
dialogs.create('surgeon/templates/associate_oncologist.tpl.html', 'SurgeonAssociateOncologistCtrl', $scope, { copy: false });
};
$scope.associateRadiotherapist = function() {
dialogs.create('surgeon/templates/associate_radiotherapist.tpl.html', 'SurgeonAssociateRadiotherapistCtrl', $scope, { copy: false });
};
$scope.associateObservers = function() {
dialogs.create('surgeon/templates/associate_observers.tpl.html', 'SurgeonAssociateObserversCtrl', $scope, { copy: false });
};
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler passare alla creazione delle proposte terapeutiche?', 'Accertati di aver inserito gli esami clinici iniziali prima di proseguire, perché dopo non potrai più inserirli!', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.doctor_association).then(function(response) {
//$state.go('case.detail.surgeon.main', {}, {reload: true});
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
/**
* Doctor association status
* Surgeon has to define two therapeutic proposals that will be voted by the other doctoes in the next step
*/
function statusDoctorAssociation($rootScope, $scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES) {
$scope.data = {
first_tp: null,
second_tp: null
};
therapeuticProposalService.list($scope.model.caseObj.id, THERAPEUTIC_PROPOSAL_TYPES.initial).then(function(response) {
response.data.forEach(function(tp) {
if(tp.priority == 1) {
$scope.data.first_tp = tp;
}
else {
$scope.data.second_tp = tp;
}
});
}, function(response) {
console.log('error'); // @TODO
});
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.createTherapeuticProposal = function(tpn, priority) {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, priority: priority, tp_type: 'initial'}, { copy: false });
};
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.editTherapeuticProposal = function(tpn) {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, tp_type: 'initial'}, { copy: false });
};
$scope.duplicateTherapeuticProposal = function() {
var dlg = dialogs.confirm('Sicuro di voler duplicare la proposta primaria?', '', { size: 'sm' });
dlg.result.then(function(btn){
// {Object} tp therapeutic proposal
var complete = function(tp) {
// if this is a group discussion therapeutic proposal then its saved as the accepted one
$scope.data.second_tp = tp;
$rootScope.$broadcast('update_notifications');
};
var second_tp = angular.copy($scope.data.first_tp);
// reset id to allow creation
second_tp.id = null;
second_tp.priority = 2;
therapeuticProposalService.create($scope.model.caseObj.id, second_tp).then(function(response) {
$scope.data.second_tp = response.data;
// setup sections counter and total. When counter reaches total sections are all saved
$scope.sections_cnt = 0;
$scope.sections_tot = second_tp.sections.length;
// create sections
second_tp.sections.forEach(function(section) {
// reset id to allow creation
section.id = null;
section.therapeutic_proposal = $scope.data.second_tp.id;
therapeuticProposalService.createSection($scope.model.caseObj.id, $scope.data.second_tp.id, section).then(function(response) {
$scope.sections_cnt++;
if($scope.sections_cnt === $scope.sections_tot) {
complete(response.data);
}
});
});
});
},function(btn){
// cancel
});
};
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler passare alla votazione delle proposte terapeutiche?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.proposals).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
/**
* Proposals status
* Surgeon waits for the other doctors to vote the proposals. If none is accepted then after a group discussion a new proposal
* must be inserted which is the definitive one
*/
function statusProposals($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES) {
$scope.data = {
first_tp: null,
second_tp: null,
accepted_tp: null
};
therapeuticProposalService.list($scope.model.caseObj.id, THERAPEUTIC_PROPOSAL_TYPES.initial).then(function(response) {
$scope.data.pollingComplete = therapeuticProposalService.pollingComplete(response.data);
$scope.data.accepted_tp = therapeuticProposalService.accepted(response.data);
response.data.forEach(function(tp) {
if(!tp.group_discussion && tp.priority == 1) { //@TODO add negation for other fields (followup, revaluation etc...)
$scope.data.first_tp = tp;
}
else if(!tp.group_discussion) {
$scope.data.second_tp = tp;
}
});
}, function(response) {
console.log('error'); // @TODO
});
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.createTherapeuticProposal = function(tpn) {
if(!$scope.data.pollingComplete || $scope.data.accepted_tp) {
console.log('error');
return;
}
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, priority: 0, group_discussion: true, tp_type: 'initial'}, { copy: false });
};
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.editTherapeuticProposal = function(tpn) {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, tp_type: 'initial'}, { copy: false });
};
$scope.freezeTpAndForwardStep = function() {
if(!$scope.data.accepted_tp) {
console.log('error');
}
else {
therapeuticProposalService.setAccepted($scope.model.caseObj.id, $scope.data.accepted_tp.id).then(function(response) {
caseService.gotoStatus($scope.model.caseObj, STATUS.proposal_accepted).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
}, function() {
console.log('error'); // @TODO
});
}
};
}
/**
* Proposal accepted status
* The doctors involved in the therapeutic proposal must provide their "section" info of the therapy card
* When done the surgeon must bublish the therapy card
*/
function statusProposalAccepted($scope, $state, $window, dialogs, caseService, therapyCardService, request, STATUS) {
$scope.edit_section = false;
$scope.data = {};
therapyCardService.getInitial($scope.model.caseObj).then(function(response) {
$scope.data.tc = response.data;
$scope.data.tc.sections.forEach(function(section) {
if(section.dispenser == $scope.model.caseObj.surgeon_contact_obj.id && $scope.model.caseObj.surgeon_contact_obj.doctor.user.id == request.user.id) {
$scope.edit_section = true;
$scope.data.section = section;
}
});
});
$scope.$watch('data.tc.sections', function (value) {
if(value) {
var written = 0;
var total = $scope.data.tc.sections.length;
$scope.data.tc.sections.forEach(function(section) {
if(section.text) {
written++;
}
});
$scope.card_complete = written == total ? true : false;
}
});
// tcn: name of the $scope.data property which stores the therapy card
$scope.editTherapyCard = function(tcn) {
dialogs.create('surgeon/templates/edit_therapy_card.tpl.html', 'SurgeonEditTherapyCardCtrl', {scope: $scope, tcn: 'tc', tc_type: 'initial'}, { copy: false });
};
// tcsn: name of the $scope.data property which stores the therapy card section
$scope.editTherapyCardSection = function() {
dialogs.create('doctor/templates/edit_therapy_card_section.tpl.html', 'DoctorEditTherapyCardSectionCtrl', {scope: $scope, tcn: 'tc', tcsn: 'section'}, { copy: false });
};
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler pubblicare la scheda terapeutica?', 'Attenzione! Una volta pubblicata non potrà essere ulteriormente modificata.', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.therapy_card).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
/**
* Started status
* Surgeon starts the therapy, and the end therapy card are prefilled by the system
*/
function statusTherapyCard($scope, $window, dialogs, caseService, STATUS) {
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler avviare la terapia?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.started).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
/**
* Started status
* The doctors involved in the therapy can ask for a FU, and must provide the end therapy section info
* When all involved doctors have provided such info and declared the therapy concluded, the surgeon can
* forward the status
*/
function statusStarted($rootScope, $scope, $state, $window, dialogs, caseService, therapeuticProposalService, followupService, endTherapyCardService, request, STATUS, FU_STATUS_DICT, FU_TYPE_DICT) {
$scope.edit_section = false;
$scope.therapy_is_completed = false;
$scope.data = {
followups: null,
FU_STATUS_DICT: FU_STATUS_DICT
};
therapeuticProposalService.getInitialTherapeuticProposal($scope.model.caseObj).then(function(response) {
$scope.tp = response.data;
}, function() {
console.log('error'); // @TODO
});
//////////// END CARD THERAPY
endTherapyCardService.getInitial($scope.model.caseObj).then(function(response) {
$scope.data.etc = response.data;
});
// etcn: name of the $scope.data property which stores the end therapy card
$scope.editEndTherapyCard = function(tcn) {
dialogs.create('surgeon/templates/edit_end_therapy_card.tpl.html', 'SurgeonEditEndTherapyCardCtrl', {scope: $scope, etcn: 'etc', etc_type: 'initial'}, { copy: false });
};
// etcsn: name of the $scope.data property which stores the end therapy card section
$scope.editEndTherapyCardSection = function() {
dialogs.create('doctor/templates/edit_end_therapy_card_section.tpl.html', 'DoctorEditEndTherapyCardSectionCtrl', {scope: $scope, etcn: 'etc', etcsn: 'section'}, { copy: false });
};
$scope.$watch('data.etc', function (value) {
if(value) {
$scope.data.section = endTherapyCardService.userSectionDispenser('surgeon', request.user.id, $scope.model.caseObj, $scope.data.etc);
$scope.edit_section = $scope.data.section === null ? false : true;
$scope.therapy_is_completed = endTherapyCardService.isCompleted($scope.data.etc);
}
});
//////////// FOLLOW UP
followupService.list($scope.model.caseObj.id, FU_TYPE_DICT.initial, [FU_STATUS_DICT.to_be_accepted, FU_STATUS_DICT.accepted]).then(function(response) {
$scope.data.followups = response.data;
}, function() {
console.log('error'); // @TODO
});
$scope.acceptFU = function(followup) {
var dlg = dialogs.confirm('Sicuro di voler accettare la data proposta per il Follow Up?', '', { size: 'sm' });
dlg.result.then(function(btn){
var index = $scope.data.followups.indexOf(followup);
followupService.accept(followup['case'], followup.id).then(function(response) {
$scope.data.followups[index] = response.data;
}, function() {
console.log('error');
});
$rootScope.$broadcast('update_notifications');
},function(btn){
// cancel
});
};
$scope.refuseFU = function(followup) {
dialogs.create('surgeon/templates/refuse_fu.tpl.html', 'SurgeonRefuseFUCtrl', {scope: $scope, followup: followup}, { copy: false });
$rootScope.$broadcast('update_notifications');
};
$scope.closeFollowUp = function(followup) {
var dlg = dialogs.confirm('Sicuro di voler chiudere il Follow Up?', '', { size: 'sm' });
dlg.result.then(function(btn){
var index = $scope.data.followups.indexOf(followup);
followupService.close(followup['case'], followup).then(function(response) {
$scope.data.followups.splice(index, 1);
}, function() {
console.log('error');
});
$rootScope.$broadcast('update_notifications');
},function(btn){
// cancel
});
};
$scope.forwardStatusRevaluation = function() {
var dlg = dialogs.confirm('Sicuro di voler passare alla rivalutazione?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.revaluation).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
$scope.forwardStatusCompleted = function() {
var dlg = dialogs.confirm('Sicuro di voler chiudere la terapia?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.completed).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
/**
* Status Revaluation
*/
function statusRevalutation($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES) {
$scope.data = {
tp: null
};
therapeuticProposalService.list($scope.model.caseObj.id, THERAPEUTIC_PROPOSAL_TYPES.revaluation).then(function(response) {
if(response.data.length === 1) {
$scope.data.tp = response.data[0];
}
}, function(response) {
console.log('error'); // @TODO
});
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.createTherapeuticProposal = function() {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: 'tp', priority: 1, tp_type: 'revaluation'}, { copy: false });
};
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.editTherapeuticProposal = function(tpn) {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, tp_type: 'revaluation'}, { copy: false });
};
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler passare alla votazione della proposta terapeutica?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.revaluation_proposal).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
/**
* Status Revaluation Proposal
*/
function statusRevaluationProposal($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES) {
$scope.data = {
tp: null,
accepted_tp: null
};
therapeuticProposalService.list($scope.model.caseObj.id, THERAPEUTIC_PROPOSAL_TYPES.revaluation).then(function(response) {
$scope.data.pollingComplete = therapeuticProposalService.pollingComplete(response.data);
$scope.data.accepted_tp = therapeuticProposalService.accepted(response.data);
response.data.forEach(function(tp) {
if(!tp.group_discussion) { //@TODO add negation for other fields (followup, revaluation etc...)
$scope.data.tp = tp;
}
});
}, function(response) {
console.log('error'); // @TODO
});
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.createTherapeuticProposal = function(tpn) {
if(!$scope.data.pollingComplete || $scope.data.accepted_tp) {
console.log('error');
return;
}
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, priority: 0, group_discussion: true, tp_type: 'revaluation'}, { copy: false });
};
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.editTherapeuticProposal = function(tpn) {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, tp_type: 'revaluation'}, { copy: false });
};
$scope.freezeTpAndForwardStep = function() {
if(!$scope.data.accepted_tp) {
console.log('error');
}
else {
therapeuticProposalService.setAccepted($scope.model.caseObj.id, $scope.data.accepted_tp.id).then(function(response) {
caseService.gotoStatus($scope.model.caseObj, STATUS.revaluation_proposal_accepted).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
}, function() {
console.log('error'); // @TODO
});
}
};
}
/**
* Revaluation proposal accepted
* doctors must fill the revaluation therapy card
*/
function statusRevaluationProposalAccepted($scope, $state, $window, dialogs, caseService, therapeuticProposalService, therapyCardService, request, STATUS) {
$scope.edit_section = false;
$scope.data = {};
therapyCardService.getRevaluation($scope.model.caseObj).then(function(response) {
$scope.data.tc = response.data;
$scope.data.tc.sections.forEach(function(section) {
if(section.dispenser == $scope.model.caseObj.surgeon_contact_obj.id && $scope.model.caseObj.surgeon_contact_obj.doctor.user.id == request.user.id) {
$scope.edit_section = true;
$scope.data.section = section;
}
});
});
$scope.$watch('data.tc.sections', function (value) {
if(value) {
var written = 0;
var total = $scope.data.tc.sections.length;
$scope.data.tc.sections.forEach(function(section) {
if(section.text) {
written++;
}
});
$scope.card_complete = written == total ? true : false;
}
});
// tcn: name of the $scope.data property which stores the therapy card
$scope.editTherapyCard = function(tcn) {
dialogs.create('surgeon/templates/edit_therapy_card.tpl.html', 'SurgeonEditTherapyCardCtrl', {scope: $scope, tcn: 'tc', tc_type: 'revaluation'}, { copy: false });
};
// tcsn: name of the $scope.data property which stores the therapy card section
$scope.editTherapyCardSection = function() {
dialogs.create('doctor/templates/edit_therapy_card_section.tpl.html', 'DoctorEditTherapyCardSectionCtrl', {scope: $scope, tcn: 'tc', tcsn: 'section'}, { copy: false });
};
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler pubblicare la scheda terapeutica di rivalutazione?', 'Attenzione! Una volta pubblicata non potrà essere ulteriormente modificata.', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.revaluation_therapy_card).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
function statusRevaluationTherapyCard($scope, $state, $window, dialogs, caseService, STATUS) {
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler avviare la rivalutazione?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.revaluation_started).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
function statusRevaluationStarted($scope, $state, $window, dialogs, caseService, endTherapyCardService, request, STATUS) {
$scope.data = {};
//////////// END CARD THERAPY
endTherapyCardService.getRevaluation($scope.model.caseObj).then(function(response) {
$scope.data.etc = response.data;
});
// etcn: name of the $scope.data property which stores the end therapy card
$scope.editEndTherapyCard = function(tcn) {
dialogs.create('surgeon/templates/edit_end_therapy_card.tpl.html', 'SurgeonEditEndTherapyCardCtrl', {scope: $scope, etcn: 'etc', etc_type: 'revaluation'}, { copy: false });
};
// etcsn: name of the $scope.data property which stores the end therapy card section
$scope.editEndTherapyCardSection = function() {
dialogs.create('doctor/templates/edit_end_therapy_card_section.tpl.html', 'DoctorEditEndTherapyCardSectionCtrl', {scope: $scope, etcn: 'etc', etcsn: 'section'}, { copy: false });
};
$scope.$watch('data.etc', function (value) {
if(value) {
$scope.data.section = endTherapyCardService.userSectionDispenser('surgeon', request.user.id, $scope.model.caseObj, $scope.data.etc);
$scope.edit_section = $scope.data.section === null ? false : true;
$scope.therapy_is_completed = endTherapyCardService.isCompleted($scope.data.etc);
}
});
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler chiudere la rivalutazione?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.revaluation_ended).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
function statusCompleted($scope, $state, $window, dialogs, caseService, STATUS) {
$scope.forwardStatusAdjuvant = function() {
var dlg = dialogs.confirm('Sicuro di voler iniziare una terapia adiuvante?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.adjuvant).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
$scope.forwardStatusEnded = function() {
var dlg = dialogs.confirm('Sicuro di voler chiudere la terapia?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.ended).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
/**
* Status Adjuvant
*/
function statusAdjuvant($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES) {
$scope.data = {
tp: null
};
therapeuticProposalService.list($scope.model.caseObj.id, THERAPEUTIC_PROPOSAL_TYPES.adjuvant).then(function(response) {
if(response.data.length === 1) {
$scope.data.tp = response.data[0];
}
}, function(response) {
console.log('error'); // @TODO
});
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.createTherapeuticProposal = function() {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: 'tp', priority: 1, tp_type: 'adjuvant'}, { copy: false });
};
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.editTherapeuticProposal = function(tpn) {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, tp_type: 'adjuvant'}, { copy: false });
};
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler passare alla votazione della proposta terapeutica?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.adjuvant_proposal).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
/**
* Status Adjuvant Proposal
*/
function statusAdjuvantProposal($scope, $state, $window, dialogs, caseService, therapeuticProposalService, STATUS, THERAPEUTIC_PROPOSAL_TYPES) {
$scope.data = {
tp: null,
accepted_tp: null
};
therapeuticProposalService.list($scope.model.caseObj.id, THERAPEUTIC_PROPOSAL_TYPES.adjuvant).then(function(response) {
$scope.data.pollingComplete = therapeuticProposalService.pollingComplete(response.data);
$scope.data.accepted_tp = therapeuticProposalService.accepted(response.data);
response.data.forEach(function(tp) {
if(!tp.group_discussion) { //@TODO add negation for other fields (followup, revaluation etc...)
$scope.data.tp = tp;
}
});
}, function(response) {
console.log('error'); // @TODO
});
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.createTherapeuticProposal = function(tpn) {
if(!$scope.data.pollingComplete || $scope.data.accepted_tp) {
console.log('error');
return;
}
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, priority: 0, group_discussion: true, tp_type: 'adjuvant'}, { copy: false });
};
// tpn: name of the $scope.data property which stores the therapeutic proposal
$scope.editTherapeuticProposal = function(tpn) {
dialogs.create('surgeon/templates/create_edit_therapeutic_proposal.tpl.html', 'SurgeonCreateEditTherapeuticProposalCtrl', {scope: $scope, tpn: tpn, tp_type: 'adjuvant'}, { copy: false });
};
$scope.freezeTpAndForwardStep = function() {
if(!$scope.data.accepted_tp) {
console.log('error');
}
else {
therapeuticProposalService.setAccepted($scope.model.caseObj.id, $scope.data.accepted_tp.id).then(function(response) {
caseService.gotoStatus($scope.model.caseObj, STATUS.adjuvant_proposal_accepted).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
}, function() {
console.log('error'); // @TODO
});
}
};
}
function statusAdjuvantProposalAccepted($scope, $state, $window, dialogs, caseService, therapyCardService, request, STATUS) {
$scope.edit_section = false;
$scope.data = {};
therapyCardService.getAdjuvant($scope.model.caseObj).then(function(response) {
console.log(response.data);
$scope.data.tc = response.data;
$scope.data.tc.sections.forEach(function(section) {
if(section.dispenser == $scope.model.caseObj.surgeon_contact_obj.id && $scope.model.caseObj.surgeon_contact_obj.doctor.user.id == request.user.id) {
$scope.edit_section = true;
$scope.data.section = section;
}
});
});
$scope.$watch('data.tc.sections', function (value) {
if(value) {
var written = 0;
var total = $scope.data.tc.sections.length;
$scope.data.tc.sections.forEach(function(section) {
if(section.text) {
written++;
}
});
$scope.card_complete = written == total ? true : false;
}
});
// tcn: name of the $scope.data property which stores the therapy card
$scope.editTherapyCard = function(tcn) {
dialogs.create('surgeon/templates/edit_therapy_card.tpl.html', 'SurgeonEditTherapyCardCtrl', {scope: $scope, tcn: 'tc', tc_type: 'adjuvant'}, { copy: false });
};
// tcsn: name of the $scope.data property which stores the therapy card section
$scope.editTherapyCardSection = function() {
dialogs.create('doctor/templates/edit_therapy_card_section.tpl.html', 'DoctorEditTherapyCardSectionCtrl', {scope: $scope, tcn: 'tc', tcsn: 'section'}, { copy: false });
};
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler pubblicare la scheda terapeutica?', 'Attenzione! Una volta pubblicata non potrà essere ulteriormente modificata.', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.adjuvant_therapy_card).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
function statusAdjuvantTherapyCard($scope, $state, $window, dialogs, caseService, STATUS) {
$scope.forwardStatus = function() {
var dlg = dialogs.confirm('Sicuro di voler avviare la terapia adiuvante?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.adjuvant_started).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
/**
* Status Adjuvant Started
*/
function statusAdjuvantStarted($scope, $state, $window, dialogs, caseService, therapeuticProposalService, followupService, endTherapyCardService, request, STATUS, FU_STATUS_DICT, FU_TYPE_DICT) {
$scope.edit_section = false;
$scope.therapy_is_completed = false;
$scope.data = {
followups: null,
FU_STATUS_DICT: FU_STATUS_DICT
};
therapeuticProposalService.getAdjuvantTherapeuticProposal($scope.model.caseObj).then(function(response) {
$scope.tp = response.data;
console.log($scope.tp);
}, function() {
console.log('error'); // @TODO
});
//////////// END CARD THERAPY
endTherapyCardService.getAdjuvant($scope.model.caseObj).then(function(response) {
$scope.data.etc = response.data;
});
// etcn: name of the $scope.data property which stores the end therapy card
$scope.editEndTherapyCard = function(tcn) {
dialogs.create('surgeon/templates/edit_end_therapy_card.tpl.html', 'SurgeonEditEndTherapyCardCtrl', {scope: $scope, etcn: 'etc', etc_type: 'adjuvant'}, { copy: false });
};
// etcsn: name of the $scope.data property which stores the end therapy card section
$scope.editEndTherapyCardSection = function() {
dialogs.create('doctor/templates/edit_end_therapy_card_section.tpl.html', 'DoctorEditEndTherapyCardSectionCtrl', {scope: $scope, etcn: 'etc', etcsn: 'section'}, { copy: false });
};
$scope.$watch('data.etc', function (value) {
if(value) {
$scope.data.section = endTherapyCardService.userSectionDispenser('surgeon', request.user.id, $scope.model.caseObj, $scope.data.etc);
$scope.edit_section = $scope.data.section === null ? false : true;
$scope.therapy_is_completed = endTherapyCardService.isCompleted($scope.data.etc);
}
});
//////////// FOLLOW UP
followupService.list($scope.model.caseObj.id, FU_TYPE_DICT.adjuvant, [FU_STATUS_DICT.to_be_accepted, FU_STATUS_DICT.accepted]).then(function(response) {
$scope.data.followups = response.data;
}, function() {
console.log('error'); // @TODO
});
$scope.acceptFU = function(followup) {
var dlg = dialogs.confirm('Sicuro di voler accettare la data proposta per il Follow Up?', '', { size: 'sm' });
dlg.result.then(function(btn){
var index = $scope.data.followups.indexOf(followup);
followupService.accept(followup['case'], followup.id).then(function(response) {
$scope.data.followups[index] = response.data;
}, function() {
console.log('error');
});
},function(btn){
// cancel
});
};
$scope.refuseFU = function(followup) {
dialogs.create('surgeon/templates/refuse_fu.tpl.html', 'SurgeonRefuseFUCtrl', {scope: $scope, followup: followup}, { copy: false });
};
$scope.closeFollowUp = function(followup) {
var dlg = dialogs.confirm('Sicuro di voler chiudere il Follow Up?', '', { size: 'sm' });
dlg.result.then(function(btn){
var index = $scope.data.followups.indexOf(followup);
followupService.close(followup['case'], followup).then(function(response) {
$scope.data.followups.splice(index, 1);
}, function() {
console.log('error');
});
},function(btn){
// cancel
});
};
$scope.forwardStatusEnded = function() {
var dlg = dialogs.confirm('Sicuro di voler chiudere la terapia?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.adjuvant_ended).then(function(response) {
caseService.gotoStatus($scope.model.caseObj, STATUS.ended).then(function(response) {
$window.location.reload();
}, function() { console.log('error'); });
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
}
function statusEnded($scope, $state, $window, dialogs, caseService, therapeuticProposalService, contactService, followupService, request, STATUS, FU_STATUS_DICT, FU_TYPE_DICT) {
var morning_limit = [8, 13];
var afternoon_limit = [13, 19];
$scope.data = {
followup: null,
followups: [],
FU_STATUS_DICT: FU_STATUS_DICT
};
contactService.get($scope.model.caseObj.surgeon_contact_obj.doctor.user.username, $scope.model.caseObj.surgeon_contact_obj.id).then(function(response) {
$scope.surgeon_contact = response.data;
}, function(response) {
console.log('error'); // @TODO
});
followupService.list($scope.model.caseObj.id, FU_TYPE_DICT.final, [FU_STATUS_DICT.to_be_accepted, FU_STATUS_DICT.refused, FU_STATUS_DICT.accepted, FU_STATUS_DICT.finalized]).then(function(response) {
$scope.data.followups = response.data;
$scope.data.followups.forEach(function(fu) {
if(fu.doctor_contact.doctor.user.id == request.user.id) {
$scope.data.followup = fu;
}
});
}, function() {
console.log('error'); // @TODO
});
/**
* Filter calendar entries in order to make selectable only surgeon availability dates
*/
$scope.beforeRender = function ($view, $dates, $leftDate, $upDate, $rightDate) {
for (var i = 0, len = $dates.length; i < len; i++) {
var date = $dates[i];
if($view == 'day' && $scope.surgeon_contact.exceptions.indexOf(moment(date.localDateValue()).format('YYYY-MM-DD')) != -1) {
date.selectable = false;
}
else {
var day = moment(date.localDateValue()).format('dddd').toLowerCase();
if($view == 'day' && $scope.surgeon_contact[day] === 0) {
date.selectable = false;
}
if($view == 'hour') {
date.selectable = false;
var hour = moment(date.localDateValue()).format('H');
var dateobj = new Date(date.utcDateValue);
if( ($scope.surgeon_contact[day] == 1 || $scope.surgeon_contact[day] == 3) &&
(hour >= morning_limit[0] && hour <= morning_limit[1]) ) {
date.selectable = true;
}
if( ($scope.surgeon_contact[day] == 2 || $scope.surgeon_contact[day] == 3) &&
(hour >= afternoon_limit[0] && hour <= afternoon_limit[1]) ) {
date.selectable = true;
}
}
if($view == 'minute') {
if(/\d\d*:[^03]\d [AP]M/.test(date.display) || /\d\d*:\d[^0] [AP]M/.test(date.display)) {
date.selectable = false;
}
}
}
}
};
$scope.createFU = function() {
dialogs.create('doctor/templates/create_fu.tpl.html', 'DoctorCreateEditFUCtrl', {scope: $scope, type: 'final'}, { copy: false });
};
$scope.closeFollowUp = function(followup) {
var dlg = dialogs.confirm('Sicuro di voler chiudere il Follow Up?', '', { size: 'sm' });
dlg.result.then(function(btn){
var index = $scope.data.followups.indexOf(followup);
followupService.close(followup['case'], followup).then(function(response) {
caseService.gotoStatus($scope.model.caseObj, STATUS.final_fu_ended).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
}, function() {
console.log('error');
});
},function(btn){
// cancel
});
};
}
function statusFinalFUEnded($scope, $state, $window, dialogs, caseService, STATUS) {
$scope.data = {
forward: false
};
$scope.$watch('data.forward', function (value) {
if(value) {
caseService.gotoStatus($scope.model.caseObj, STATUS.relapse).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
}
});
$scope.forwardStatusClosed = function() {
var dlg = dialogs.confirm('Sicuro di voler chiudere il caso?', '', { size: 'sm' });
dlg.result.then(function(btn){
caseService.gotoStatus($scope.model.caseObj, STATUS.closed).then(function(response) {
$window.location.reload();
}, function() {
console.log('error'); // @TODO
});
},function(btn){
// cancel
});
};
$scope.openRelapse = function() {
dialogs.create('surgeon/templates/case_detail_relapse.tpl.html', 'SurgeonCaseDetailRelapse', { scope: $scope }, { copy: false });
};
}
function statusRelapse($scope, $state, $window, dialogs, caseService, STATUS) {
caseService.getRelapse($scope.model.caseObj).then(function(response) {
$scope.relapse = response.data;
}, function() {
console.log('error'); // @TODO
});
}
})();
|
import { connect } from 'react-redux'
import { setDate, initializeApp, fetchData } from '../actions'
import App from '../components/App'
const mapStateToProps = (state, ownProps) => {
return {
senderId: ownProps.params.senderId
}
}
const mapDispatchToProps = (dispatch) => {
return {
initializeApp: (senderId) => {
dispatch(initializeApp(senderId)).then(() => { dispatch(fetchData()) })
}
}
}
const InitializedApp = connect(mapStateToProps, mapDispatchToProps)(App)
export default InitializedApp |
app.factory('PostsFactory', ['$http', '$q',
function PostsFactory($http, $q) {
// interface
var service = {
data: [],
getAllPosts: getAllPosts,
getPostById: getPostById,
callMe: callMe
};
// implementation
function getAllPosts(filepath) {
var def = $q.defer();
$http.get(filepath)
.success(function(data) {
service.data = data;
def.resolve(data);
})
.error(function() {
def.reject("Failed to retrieve data");
});
return def.promise;
}
function getPostById(username) {
var def = $q.defer();
var restUrl = "api/users.php?username="+username;
// alert(restUrl);
$http.get(restUrl)
.success(function(data) {
service.data = data;
def.resolve(data);
})
.error(function() {
def.reject("Failed to retrieve data");
});
return def.promise;
}
function callMe(arg){
return arg;
}
return service;
}]); |
var Backbone = require("backbone"),
resource = require("../../controller/resource.js"),
AdsModel;
require("backbone-relational");
require("backbone-relational-hal");
AdsModel = Backbone.RelationalHalResource.extend({
initialize: function () {
resource.getRootHal(function (uri) {
this.url = uri;
this.fetch();
}.bind(this));
}
});
module.exports = AdsModel; |
const Park = require('../models/park');
const Slot = require('../models/slot');
const dummyParks = [
new Park({
title: 'park1',
position: {
lat: 6.927079,
lng: 79.891244
},
icon: 'mp.png'
}),
new Park({
title: 'park2',
position: {
lat: 6.927079,
lng: 79.862244
},
icon: 'mp.png'
}),
new Park({
title: 'park3',
position: {
lat: 6.927079,
lng: 79.823244
},
icon: 'mp.png'
})
];
module.exports = () => {
Park.remove().exec();
Slot.remove().exec();
dummyParks.forEach((park) => {
park.save();
const dummySlots = [
new Slot({title: park.title + ' slot 1', isReserved: false, isReservePending:false, park: park._id}),
new Slot({title: park.title + ' slot 2', isReserved: false, isReservePending:false, park: park._id}),
new Slot({title: park.title + ' slot 2', isReserved: false, isReservePending:false, park: park._id}),
];
dummySlots.forEach(slot => slot.save());
});
} |
$('#title').text('Dragon Shire');
$('#wrapper').css('background-color', '').css('background-image', 'url("http://i.imgur.com/OcFygJu.jpg")');
$('#blue-name .overlay-text').text('Blue Team');
$('#red-name .overlay-text').text('Red Team');
var seconds = 5;
setTimeout( demo, 5000);
countdown = setInterval(function() { seconds--; $('#timer-pool').text(seconds); if (seconds == 0) { $('#timer-pool').text(''); clearInterval(countdown); } }, 1000);
function updateValue(data) {
console.log(data);
$('#'+data.id+'-video').attr('src', getHeroVideo(data.value)).removeClass('hide').addClass('video-' + data.value + ' animated');
$('#'+data.id+' .overlay-hero').removeClass('hide').addClass('animated');
$('#'+data.id+'-hero').text(properName(data.value));
}
function demo() {
var base = 3000;
updateValue({ id: 'blue-p1-name', value: 'iDream' });
updateValue({ id: 'blue-p2-name', value: 'DunkTrain' });
updateValue({ id: 'blue-p3-name', value: 'k1pro' });
updateValue({ id: 'blue-p4-name', value: 'King Caffiene' });
updateValue({ id: 'blue-p5-name', value: 'Biceps' });
updateValue({ id: 'red-p1-name', value: 'Glaurung' });
updateValue({ id: 'red-p2-name', value: 'Kaeyoh' });
updateValue({ id: 'red-p3-name', value: 'Dreadnaught' });
updateValue({ id: 'red-p4-name', value: 'Sold1er' });
updateValue({ id: 'red-p5-name', value: 'Arthelon' });
$('#blue-b1 .overlay-bg').removeClass('waiting').addClass('animated myturn');
// $('#blue-b1 .overlay-player').removeClass('hide').addClass('animated');
setTimeout( function() { updateValue({ id: 'blue-b1', value: 'uther' }); $('#red-b1 .overlay-bg').removeClass('waiting').addClass('animated myturn'); /* $('#red-b1 .overlay-player').removeClass('hide').addClass('animated'); */ }, base*1);
setTimeout( function() { updateValue({ id: 'red-b1', value: 'illidan' }); $('#blue-p1 .overlay-bg').removeClass('waiting').addClass('animated myturn'); }, base*2);
setTimeout( function() { updateValue({ id: 'blue-p1', value: 'the-lost-vikings' }); $('#red-p1 .overlay-bg').removeClass('waiting').addClass('animated myturn'); $('#red-p2 .overlay-bg').removeClass('waiting').addClass('animated myturn');}, base*3);
setTimeout( function() { updateValue({ id: 'red-p1', value: 'diablo' }); }, base*4);
setTimeout( function() { updateValue({ id: 'red-p2', value: 'sylvanas' }); $('#blue-p2 .overlay-bg').removeClass('waiting').addClass('animated myturn'); $('#blue-p3 .overlay-bg').removeClass('waiting').addClass('animated myturn'); }, base*5);
setTimeout( function() { updateValue({ id: 'blue-p2', value: 'tyrande' }); }, base*6);
setTimeout( function() { updateValue({ id: 'blue-p3', value: 'jaina' }); $('#red-p3 .overlay-bg').removeClass('waiting').addClass('animated myturn'); $('#red-p4 .overlay-bg').removeClass('waiting').addClass('animated myturn'); }, base*7);
setTimeout( function() { updateValue({ id: 'red-p3', value: 'rehgar' }); }, base*8);
setTimeout( function() { updateValue({ id: 'red-p4', value: 'zeratul' }); $('#blue-p4 .overlay-bg').removeClass('waiting').addClass('animated myturn'); $('#blue-p5 .overlay-bg').removeClass('waiting').addClass('animated myturn'); }, base*9);
setTimeout( function() { updateValue({ id: 'blue-p4', value: 'muradin' }); }, base*10);
setTimeout( function() { updateValue({ id: 'blue-p5', value: 'tassadar' }); $('#red-p5 .overlay-bg').removeClass('waiting').addClass('animated myturn'); }, base*11);
setTimeout( function() { updateValue({ id: 'red-p5', value: 'abathur' }); }, base*12);
setTimeout( function() { $('.overlay-message').removeClass('hide').addClass('animated'); }, base*12+1000);
return true;
} |
import React from "react";
import ControlsExample from "./controls";
import SimpleExample from "./simple";
import EventsExample from "./events";
import VectorLayersExample from "./vector-layers";
import EditableExample from "./editable";
const examples = <div>
<h1>React-Leaflet examples</h1>
<h2>Editable</h2>
<EditableExample />
<h2>Custom controls</h2>
<ControlsExample />
<h2>Popup with Marker</h2>
<SimpleExample />
<h2>Events</h2>
<p>Click the map to show a marker at your detected location</p>
<EventsExample />
<h2>Vector layers</h2>
<VectorLayersExample />
</div>;
React.render(examples, document.getElementById("app"));
|
'use strict';
var util = require('util');
var request = require('request');
var ipapi = require('../package.json');
exports = module.exports = new IpGeo();
function IpGeo() {
this.ipgeo = function(ip) {
var api = (typeof(ipapi.ipapi) == 'undefined') ? 'undefined' : ipapi.ipapi;
switch (api) {
case 'ip-api.com':
return this.ipapi(ip);
case 'ipinfo.io':
return this.ipinfoio(ip);
default:
return console.log('api error: ' + api);
}
}
this.ipcn = function(ip) {
var url = 'http://ip.cn';
url = (typeof(ip) == 'undefined') ? url : url + '/index.php?ip=' + ip;
var options = {
url: url,
headers: {
'User-Agent':
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
'Content-Type' : 'application/x-www-form-urlencoded'
}
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
var re = /\d+\.\d+\.\d+\.\d+/;
var ip = body.match(re);
var addr, ca = '';
if (util.isArray(ip)) {
re = /来自:(.[^<]+)</; // chinese info
ca = body.match(re);
if (util.isArray(ca) && ca.length > 1) {
ca = ca[1].substr(0,30);
}
re = /GeoIP:(.[^<]+)</; // english info
addr = body.match(re);
if (util.isArray(addr) && addr.length > 1) {
addr = addr[1].substr(0,50);
}
ca = (ca) ? ca.trim() : '';
addr = (addr) ? addr.trim() : '';
console.log("IP: %s %s %s", ip[0], addr, ca);
} else {
console.log('ip not found');
}
} else {
console.log('http error:', response.statusCode);
}
});
}
this.telize = function(ip) {
var header = {
url: 'http://www.telize.com/geoip/' + ip,
headers: {
'User-Agent':
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)'
}
}
request(header, function (err, response, body) {
if (!err && response.statusCode == 200) {
request(header, function (err, response, body) {
if (err) throw err;
var r = JSON.parse(body);
console.log('IP: %s', r['ip']);
console.log('%s, %s, %s', r['city'], r['region'], r['country']);
console.log('UTC %s %s, %s %s, %s', r['offset'], r['timezone'], r['longitude'], r['latitude'], r['country_code']);
console.log('ISP: %s', r['isp']);
//for (var key in r) {console.log(" %s: %s", key, r[key]);}
//console.log(r);
});
} else {
console.log('http error:', response.statusCode);
}
});
}
this.ipinfoio = function(ip) {
var ip = (typeof(ip) == 'undefined') ? '' : ip + '/';
var options = {
url: 'http://ipinfo.io/' + ip + 'json',
headers: {
'User-Agent':
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)'
}
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
var r = JSON.parse(body);
console.log('IP: %s LOC: %s %s, %s, %s %s', r['ip'], r['loc']
, r['city'], r['region'], r['country']
, typeof r['postal'] == 'undefined' ? '' : 'PC: ' + r['postal']);
console.log('ISP: %s', r['org']);
} else {
console.log('http error:', response.statusCode);
}
});
}
this.ipapi = function(ip) {
var ip = (typeof(ip) == 'undefined') ? '' : '/' + ip;
var options = {
url: 'http://ip-api.com/json' + ip,
headers: {
'User-Agent':
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)'
}
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
var r = JSON.parse(body);
console.log('IP: %s %s, %s, %s', r['query'], r['city'], r['regionName'], r['country']);
console.log('TIMEZONE: %s, LOCATION: %s %s, %s', r['timezone'], r['lon'], r['lat'], r['countryCode']);
console.log('ISP: %s - %s', r['isp'], r['org']);
//console.log(r);
} else {
console.log('http error:', response.statusCode);
}
});
}
}
|
var logger = require('../util/logger')(__filename),
async = require('async'),
userDao = require('../dao/user'),
privacyDao = require('../dao/privacy'),
eventDao = require('../dao/event'),
gPlusDao = require('../dao/gplus'),
geo = require('../util/geo'),
time = require('../util/time'),
util = require('../util/util'),
ObjectID = require('mongodb').ObjectID;
function userEvents(user, event, callback) {
var search = {
user: user._id
};
if (event) {
search['_id'] = new ObjectID(event);
}
eventDao.get(search, function(err, userEvents) {
adjustStartAndEndTime(userEvents);
callback(err, userEvents);
});
}
function samePlace(place1, place2) {
return place1.lat === place2.lat && place1.lgn === place2.lgn;
}
function reduceOverlappingTimeEvents(events) {
for (var i = events.length - 1; i >= 1; i--) {
for (var j = i - 1; j >= 0; j--) {
if (events[i].user === events[j].user && samePlace(events[i].location, events[j].location)) {
var interval = time.overlay([events[i].start.dateTime, events[i].end.dateTime], [events[j].start.dateTime, events[j].end.dateTime], 0);
if (interval.overlay) {
events[j].start.dateTime = Math.min(events[i].start.dateTime, events[j].start.dateTime);
events[j].end.dateTime = Math.max(events[i].end.dateTime, events[j].end.dateTime);
events[j].events = events[j].events.concat(events[i].events);
events.splice(i, 1);
break;
}
}
}
}
}
function adjustStartAndEndTime(events) {
var now = (new Date()).getTime();
var tomorrow = now + 24 * 60 * 60 * 1000;
events.forEach(function(event) {
event.start = Math.max(event.start, now);
event.end = Math.min(event.end, tomorrow);
});
}
function userContacts(user, callback) {
gPlusDao.get(user._id, function(err, contact) {
callback(err, contact.contacts);
});
}
function contactsInfo(contacts, callback) {
gPlusDao.find({
_id: {
$in: contacts
}
},
{
name: 1,
profile: 1,
email: 1,
locale: 1,
photo: 1
}
, callback);
}
function getContactEvents(contacts, callback) {
contacts = contacts || [];
eventDao.get({
user: {
$in: contacts
}
}, function(err, contactEvents) {
callback(err, contactEvents);
});
}
function filterFutureEvents(userEvents, contactEvents, callback) {
var nearUsers = [];
try {
userEvents.forEach(function(userEvent) {
contactEvents.forEach(function(contactEvent) {
var distance = geo.distance(userEvent.location.coordinates, contactEvent.location.coordinates);
var interval = time.overlay([userEvent.start, userEvent.end], [contactEvent.start, contactEvent.end]);
if (interval.overlay && distance < 30000) {
var nearUser = {
id: contactEvent.user,
location: contactEvent.location,
location_me: userEvent.location,
formatted_address: userEvent.formatted_address,
distance: distance,
overlappingTime: interval,
time: {
start: contactEvent.start,
end: contactEvent.end
},
time_me: {
start: userEvent.start,
end: userEvent.end
}
};
nearUsers.push(nearUser);
}
});
});
callback(null, nearUsers);
} catch (e) {
callback(e, null);
}
}
function contactEvents(user, cbk) {
logger.info('Searching contacts for the user ' + user.name + " ...");
async.waterfall([
function(callback) {
userContacts(user, function(err, contacts) {
callback(err, contacts);
});
},
function(contacts, callback) {
logger.info('Found ' + contacts.length + ' contacts of the user ' + user.name);
getContactEvents(contacts, function(err, contactEvents) {
callback(err, contacts, contactEvents);
});
},
function(contactIds, contactEvents, callback) {
logger.info('Found ' + contactEvents.length + ' contacts events for the user ' + user.name);
contactsInfo(contactIds, function(err, contacts) {
contactEvents.forEach(function(contactEvent) {
for (var i = 0; i < contacts.length; i++) {
var contact = contacts[i];
if (contact._id === contactEvent.user) {
for (var key in contact) {
contactEvent[key] = contact[key];
}
break;
}
}
});
callback(err, contactEvents);
});
}
], function(err, contactEvents) {
if (err) {
return cbk(err);
}
adjustStartAndEndTime(contactEvents);
cbk(null, contactEvents);
});
}
function futureNearestContacts(user, event, cbk) {
logger.info('Searching future contacts for the user ' + user.name + " ...");
async.waterfall([
function(callback) {
userEvents(user, event, callback);
},
function(userEvents, callback) {
logger.info('Found ' + userEvents.length + ' future events for the user ' + user.name);
userContacts(user, function(err, contacts) {
callback(err, userEvents, contacts);
});
},
function(userEvents, contacts, callback) {
logger.info('Found ' + contacts.length + ' contacts of the user ' + user.name);
getContactEvents(contacts, function(err, contactEvents) {
callback(err, userEvents, contacts, contactEvents);
});
},
function(userEvents, contacts, contactEvents, callback) {
logger.info('There are ' + contactEvents.length + ' contact events for the user ' + user.name + ' after the reduction');
filterFutureEvents(userEvents, contactEvents, function(err, nearEvents) {
callback(err, userEvents, contacts, contactEvents, nearEvents);
});
},
function(userEvents, contacts, contactEvents, nearEvents, callback) {
logger.info('Found ' + nearEvents.length + ' near future events for the user ' + user.name);
var nearContacts = [];
nearEvents.forEach(function(nearEvent) {
nearContacts.push(nearEvent.id);
});
contactsInfo(nearContacts, function(err, contacts) {
nearEvents.forEach(function(nearEvent) {
for (var i = 0; i < contacts.length; i++) {
var contact = contacts[i];
if (contact._id === nearEvent.id) {
for (var key in contact) {
nearEvent[key] = contact[key];
}
break;
}
}
});
callback(err, userEvents, contacts, contactEvents, nearEvents);
});
}
], function(err, userEvents, contacts, contactEvents, nearEvents) {
if (err) {
return cbk(err);
}
adjustStartAndEndTime(nearEvents);
cbk(null, nearEvents);
});
}
function nearestContacts(user, callback) {
userContacts(user, function(err, userContacts) {
if (err)
return callback(err);
userDao.nearestContacts(user, userContacts, function(err, nearContacts) {
if (err) {
return callback(err);
}
async.each(nearContacts, function(contact, cbk) {
privacyDao.get(contact._id, function(err, data) {
if (err)
cbk(err);
else {
if (data && data.privacy)
contact.privacy = data.privacy;
cbk(null);
}
});
}, function(err) {
if (err)
return callback(err, null);
callback(null, nearContacts);
});
});
});
}
module.exports = {
futureNearestContacts: futureNearestContacts,
reduceOverlappingTimeEvents: reduceOverlappingTimeEvents,
userEvents: function(user, callback) {
userEvents(user, undefined, callback);
},
contactEvents: contactEvents,
nearestContacts: nearestContacts
}; |
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var AvQueue = React.createClass({
displayName: 'AvQueue',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: "M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z" })
);
}
});
module.exports = AvQueue; |
/* eslint ember/order-in-components: 0 */
import Component from '@ember/component';
export default Component.extend({
showSessionAttendanceRequired: false,
showSessionSupplemental: false,
showSessionSpecialAttireRequired: false,
showSessionSpecialEquipmentRequired: false,
});
|
import React, {Component} from 'react';
import DateTimePicker from 'src/DateTimePicker';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import RaisedButton from 'src/RaisedButton';
import Dialog from 'src/Dialog';
import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/DateTimePicker.json';
import 'scss/containers/app/modules/date/DateInDialog.scss';
class DateTimePickerExamples extends Component {
constructor(props) {
super(props);
this.state = {
DateTimePickerVisible: {}
};
}
show = id => {
const {DateTimePickerVisible} = this.state;
DateTimePickerVisible[id] = true;
this.setState({
DateTimePickerVisible
});
};
hide = id => {
const {DateTimePickerVisible} = this.state;
DateTimePickerVisible[id] = false;
this.setState({
DateTimePickerVisible
});
};
onChangeHandle = value => {
console.log(value);
};
render() {
const {DateTimePickerVisible} = this.state;
return (
<div className="example date-time-picker-examples">
<h2 className="example-title">Date Time Picker</h2>
<p>
<span>Date Time Picker</span>
is used to select a date and time.
</p>
<h2 className="example-title">Examples</h2>
<Widget>
<WidgetHeader className="example-header" title="Basic"/>
<div className="widget-content">
<div className="example-content">
<div className="examples-wrapper">
<p><code>Date Time Picker</code> simple example.</p>
<DateTimePicker value=''
onChange={this.onChangeHandle}/>
</div>
</div>
</div>
</Widget>
<Widget>
<WidgetHeader className="example-header" title="With value"/>
<div className="widget-content">
<div className="example-content">
<div className="examples-wrapper">
<p><code>Date Time Picker</code> using the <code>value</code> property to set initial
date and time.</p>
<DateTimePicker value='2017-04-21 12:23:10'
onChange={this.onChangeHandle}/>
</div>
</div>
</div>
</Widget>
<Widget>
<WidgetHeader className="example-header" title="With maxVale and minValue"/>
<div className="widget-content">
<div className="example-content">
<div className="examples-wrapper">
<p><code>Date Time Picker</code> using the <code>maxValue</code> property
and <code>minValue</code>
property to set date selectable range.</p>
<DateTimePicker value='2017-04-21 12:23:10'
maxValue="2017-09-12 12:23:00"
minValue='2017-01-01 12:55:55'
onChange={this.onChangeHandle}/>
</div>
</div>
</div>
</Widget>
<Widget>
<WidgetHeader className="example-header" title="With placeholder and dateFormat"/>
<div className="widget-content">
<div className="example-content">
<div className="examples-wrapper">
<p><code>Date Time Picker</code> using the <code>placeholder</code> property to set
default value and using the <code>dateFormat</code> property to format date time.
</p>
<DateTimePicker value='2017-04-21 12:23:10'
maxValue="2017-09-12 12:23:00"
minValue='2017-01-01 12:55:55'
dateFormat="YYYY/MM/DD HH:mm"
placeholder="2017-05-03 11:05:20"
onChange={this.onChangeHandle}/>
</div>
</div>
</div>
</Widget>
<Widget>
<WidgetHeader className="example-header" title="In Dialog"/>
<div className="widget-content">
<div className="example-content">
<div className="examples-wrapper">
<p><code>Date Time Picker</code> using the <code>placeholder</code> property to set
default value and using the <code>dateFormat</code> property to format date time.
</p>
<RaisedButton className="trigger-button dialog-button"
value="Show Dialog"
onClick={() => this.show(1)}/>
<Dialog visible={DateTimePickerVisible[1]}
onRequestClose={() => this.hide(1)}>
{
dialogContentEl =>
<div className="popover-dialog-content-scroller">
<DateTimePicker value='2017-04-21 12:23:10'
maxValue="2017-09-12 12:23:00"
minValue='2017-01-01 12:55:55'
dateFormat="YYYY/MM/DD HH:mm"
placeholder="2017-05-03 11:05:20"
parentEl={dialogContentEl}
onChange={this.onChangeHandle}/>
</div>
}
</Dialog>
</div>
</div>
</div>
</Widget>
<h2 className="example-title">Properties</h2>
<PropTypeDescTable data={doc}/>
</div>
);
}
}
export default DateTimePickerExamples;
|
var config = require('./wdio.conf.js').config
config.capabilities = [
{
maxInstances: 1,
browserName: 'phantomjs',
'phantomjs.binary.path': require('phantomjs2').path
}
]
config.specs = [
'./test/e2e/**/*.failsafe.js'
]
config.port = 4444
exports.config = config
|
'use strict';
const getType = require('./getType');
module.exports = function buildOptions(opts, defaultOpts) {
const rawOpts = typeof opts === 'string' ? {functionName: opts} : opts;
const options = Object.assign(Object.assign({}, defaultOpts), opts);
if (typeof options.pluralRule === 'string')
switch (options.pluralRule) {
case 'tr':
options.pluralRule = 0; break;
case 'de':
case 'es':
case 'en':
options.pluralRule = 1; break;
case 'be':
case 'ru':
case 'uk':
options.pluralRule = 7; break;
default:
throw new Error('`opts.pluralRule` got unsupported alias value `' + options.pluralRule + '`.');
}
const {pluralRule} = options;
if (!(
pluralRule >= 0 &&
pluralRule <= 16 &&
pluralRule !== 3
)) throw new Error('`opts.pluralRule` expected to have value [0; 16] exluding 3, got `' + options.pluralRule + '`.');
return options;
};
|
var $require = require('proxyquire');
var expect = require('chai').expect;
var sinon = require('sinon');
var factory = require('../app/service');
var mongodb = require('mongodb');
describe('service', function() {
it('should export factory function', function() {
expect(factory).to.be.a('function');
});
it('should be annotated', function() {
expect(factory['@singleton']).to.equal(true);
expect(factory['@implements']).to.deep.equal([ 'http://i.bixbyjs.org/mongodb', 'http://i.bixbyjs.org/IService' ]);
expect(factory['@name']).to.equal('mongodb');
expect(factory['@port']).to.equal(27017);
expect(factory['@protocol']).to.equal('tcp');
});
describe('API', function() {
var _keyring = { get: function(){} };
var _client = new mongodb.MongoClient();
var MongoClientStub = sinon.stub().returns(_client);
var api = $require('../app/service',
{ 'mongodb': { MongoClient: MongoClientStub } }
)(_keyring);
describe('.createConnection', function() {
beforeEach(function() {
_client.s.options = {};
sinon.stub(_keyring, 'get').withArgs('mongodb.example.com').yieldsAsync(null, { username: 'root', password: 'keyboard cat' })
.withArgs('mongodb.example.org').yieldsAsync(null)
.withArgs('localhost').yieldsAsync(null, { username: 'jaredhanson', password: 'h0m35w337h0m3' });
sinon.stub(_client, 'connect').callsFake(function() {
var self = this;
process.nextTick(function() {
self.emit('open');
});
});
});
afterEach(function() {
MongoClientStub.resetHistory();
});
it('should construct client and connect', function(done) {
var client = api.createConnection({ name: 'mongodb.example.com', port: 27017 });
expect(MongoClientStub).to.have.been.calledOnceWithExactly('mongodb://mongodb.example.com:27017/insignature-tokens-development').and.calledWithNew;
expect(client).to.be.an.instanceof(mongodb.MongoClient);
client.once('open', function() {
expect(client.s.options).to.deep.equal({ auth: { user: 'root', password: 'keyboard cat' } });
done();
});
}); // should construct client and connect
it('should construct client, add listener and connect', function(done) {
var client = api.createConnection({ name: 'mongodb.example.com', port: 27017 }, function() {
expect(this).to.be.an.instanceof(mongodb.MongoClient);
expect(client.s.options).to.deep.equal({ auth: { user: 'root', password: 'keyboard cat' } });
done();
});
expect(MongoClientStub).to.have.been.calledOnceWithExactly('mongodb://mongodb.example.com:27017/insignature-tokens-development').and.calledWithNew;
expect(client).to.be.an.instanceof(mongodb.MongoClient);
}); // should construct client, add listener and connect
it('should construct client and connect without credentials', function(done) {
var client = api.createConnection({ name: 'mongodb.example.org', port: 27017 });
expect(MongoClientStub).to.have.been.calledOnceWithExactly('mongodb://mongodb.example.org:27017/insignature-tokens-development').and.calledWithNew;
expect(client).to.be.an.instanceof(mongodb.MongoClient);
client.once('open', function() {
expect(client.s.options).to.deep.equal({});
done();
});
}); // should construct client and connect without credentials
it('should construct client and connect to address', function(done) {
var client = api.createConnection({ name: 'localhost', address: '127.0.0.1', port: 27017 });
expect(MongoClientStub).to.have.been.calledOnceWithExactly('mongodb://127.0.0.1:27017/insignature-tokens-development').and.calledWithNew;
expect(client).to.be.an.instanceof(mongodb.MongoClient);
client.once('open', function() {
expect(client.s.options).to.deep.equal({ auth: { user: 'jaredhanson', password: 'h0m35w337h0m3' } });
done();
});
}); // should construct client and connect
}); // .createConnection
}); // API
}); // service
|
'use strict';
/* jshint -W030 */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../../lib/data-types')
, Sequelize = require('../../../index')
, moment = require('moment')
, sinon = require('sinon')
, Promise = Sequelize.Promise
, current = Support.sequelize
, dialect = Support.getTestDialect();
describe(Support.getTestDialectTeaser('HasMany'), function() {
describe('Model.associations', function() {
it('should store all assocations when associting to the same table multiple times', function() {
var User = this.sequelize.define('User', {})
, Group = this.sequelize.define('Group', {});
Group.hasMany(User);
Group.hasMany(User, { foreignKey: 'primaryGroupId', as: 'primaryUsers' });
Group.hasMany(User, { foreignKey: 'secondaryGroupId', as: 'secondaryUsers' });
expect(Object.keys(Group.associations)).to.deep.equal(['Users', 'primaryUsers', 'secondaryUsers']);
});
});
describe('get', function () {
if (current.dialect.supports.groupedLimit) {
describe('multiple', function () {
it('should fetch associations for multiple instances', function () {
var User = this.sequelize.define('User', {})
, Task = this.sequelize.define('Task', {});
User.Tasks = User.hasMany(Task, {as: 'tasks'});
return this.sequelize.sync({force: true}).then(function () {
return Promise.join(
User.create({
id: 1,
tasks: [
{},
{},
{}
]
}, {
include: [User.Tasks]
}),
User.create({
id: 2,
tasks: [
{}
]
}, {
include: [User.Tasks]
}),
User.create({
id: 3
})
);
}).then(function (users) {
return User.Tasks.get(users).then(function (result) {
expect(result[users[0].id].length).to.equal(3);
expect(result[users[1].id].length).to.equal(1);
expect(result[users[2].id].length).to.equal(0);
});
});
});
it('should fetch associations for multiple instances with limit and order', function () {
var User = this.sequelize.define('User', {})
, Task = this.sequelize.define('Task', {
title: DataTypes.STRING
});
User.Tasks = User.hasMany(Task, {as: 'tasks'});
return this.sequelize.sync({force: true}).then(function () {
return Promise.join(
User.create({
tasks: [
{title: 'b'},
{title: 'd'},
{title: 'c'},
{title: 'a'}
]
}, {
include: [User.Tasks]
}),
User.create({
tasks: [
{title: 'a'},
{title: 'c'},
{title: 'b'}
]
}, {
include: [User.Tasks]
})
);
}).then(function (users) {
return User.Tasks.get(users, {
limit: 2,
order: [
['title', 'ASC']
]
}).then(function (result) {
expect(result[users[0].id].length).to.equal(2);
expect(result[users[0].id][0].title).to.equal('a');
expect(result[users[0].id][1].title).to.equal('b');
expect(result[users[1].id].length).to.equal(2);
expect(result[users[1].id][0].title).to.equal('a');
expect(result[users[1].id][1].title).to.equal('b');
});
});
});
it('should fetch multiple layers of associations with limit and order with separate=true', function () {
var User = this.sequelize.define('User', {})
, Task = this.sequelize.define('Task', {
title: DataTypes.STRING
})
, SubTask = this.sequelize.define('SubTask', {
title: DataTypes.STRING
});
User.Tasks = User.hasMany(Task, {as: 'tasks'});
Task.SubTasks = Task.hasMany(SubTask, {as: 'subtasks'});
return this.sequelize.sync({force: true}).then(function() {
return Promise.join(
User.create({
id: 1,
tasks: [
{title: 'b', subtasks: [
{title:'c'},
{title:'a'}
]},
{title: 'd'},
{title: 'c', subtasks: [
{title:'b'},
{title:'a'},
{title:'c'}
]},
{title: 'a', subtasks: [
{title:'c'},
{title:'a'},
{title:'b'}
]}
]
}, {
include: [{association: User.Tasks, include: [Task.SubTasks]}]
}),
User.create({
id: 2,
tasks: [
{title: 'a', subtasks: [
{title:'b'},
{title:'a'},
{title:'c'}
]},
{title: 'c', subtasks: [
{title:'a'}
]},
{title: 'b', subtasks: [
{title:'a'},
{title:'b'}
]}
]
}, {
include: [{association: User.Tasks, include: [Task.SubTasks]}]
})
);
}).then(function(users) {
return User.findAll({
include: [{
association: User.Tasks,
limit: 2,
order: [['title', 'ASC']],
separate: true,
as: 'tasks',
include: [
{
association: Task.SubTasks,
order: [['title', 'DESC']],
separate: true,
as: 'subtasks'
}
]
}],
order: [
['id', 'ASC']
]
}).then(function(users) {
expect(users[0].tasks.length).to.equal(2);
expect(users[0].tasks[0].title).to.equal('a');
expect(users[0].tasks[0].subtasks.length).to.equal(3);
expect(users[0].tasks[0].subtasks[0].title).to.equal('c');
expect(users[0].tasks[0].subtasks[1].title).to.equal('b');
expect(users[0].tasks[0].subtasks[2].title).to.equal('a');
expect(users[0].tasks[1].title).to.equal('b');
expect(users[0].tasks[1].subtasks.length).to.equal(2);
expect(users[0].tasks[1].subtasks[0].title).to.equal('c');
expect(users[0].tasks[1].subtasks[1].title).to.equal('a');
expect(users[1].tasks.length).to.equal(2);
expect(users[1].tasks[0].title).to.equal('a');
expect(users[1].tasks[0].subtasks.length).to.equal(3);
expect(users[1].tasks[0].subtasks[0].title).to.equal('c');
expect(users[1].tasks[0].subtasks[1].title).to.equal('b');
expect(users[1].tasks[0].subtasks[2].title).to.equal('a');
expect(users[1].tasks[1].title).to.equal('b');
expect(users[1].tasks[1].subtasks.length).to.equal(2);
expect(users[1].tasks[1].subtasks[0].title).to.equal('b');
expect(users[1].tasks[1].subtasks[1].title).to.equal('a');
});
});
});
it('should fetch associations for multiple instances with limit and order and a belongsTo relation', function () {
var User = this.sequelize.define('User', {})
, Task = this.sequelize.define('Task', {
title: DataTypes.STRING,
categoryId: {
type: DataTypes.INTEGER,
field: 'category_id'
}
})
, Category = this.sequelize.define('Category', {});
User.Tasks = User.hasMany(Task, {as: 'tasks'});
Task.Category = Task.belongsTo(Category, {as: 'category', foreignKey: 'categoryId'});
return this.sequelize.sync({force: true}).then(function () {
return Promise.join(
User.create({
tasks: [
{title: 'b', category: {}},
{title: 'd', category: {}},
{title: 'c', category: {}},
{title: 'a', category: {}}
]
}, {
include: [{association: User.Tasks, include: [Task.Category]}]
}),
User.create({
tasks: [
{title: 'a', category: {}},
{title: 'c', category: {}},
{title: 'b', category: {}}
]
}, {
include: [{association: User.Tasks, include: [Task.Category]}]
})
);
}).then(function (users) {
return User.Tasks.get(users, {
limit: 2,
order: [
['title', 'ASC']
],
include: [Task.Category],
}).then(function (result) {
expect(result[users[0].id].length).to.equal(2);
expect(result[users[0].id][0].title).to.equal('a');
expect(result[users[0].id][0].category).to.be.ok;
expect(result[users[0].id][1].title).to.equal('b');
expect(result[users[0].id][1].category).to.be.ok;
expect(result[users[1].id].length).to.equal(2);
expect(result[users[1].id][0].title).to.equal('a');
expect(result[users[1].id][0].category).to.be.ok;
expect(result[users[1].id][1].title).to.equal('b');
expect(result[users[1].id][1].category).to.be.ok;
});
});
});
});
}
});
describe('(1:N)', function() {
describe('hasSingle', function() {
beforeEach(function() {
this.Article = this.sequelize.define('Article', { 'title': DataTypes.STRING });
this.Label = this.sequelize.define('Label', { 'text': DataTypes.STRING });
this.Article.hasMany(this.Label);
return this.sequelize.sync({ force: true });
});
it('should only generate one set of foreignKeys', function() {
this.Article = this.sequelize.define('Article', { 'title': DataTypes.STRING }, {timestamps: false});
this.Label = this.sequelize.define('Label', { 'text': DataTypes.STRING }, {timestamps: false});
this.Label.belongsTo(this.Article);
this.Article.hasMany(this.Label);
expect(Object.keys(this.Label.rawAttributes)).to.deep.equal(['id', 'text', 'ArticleId']);
expect(Object.keys(this.Label.rawAttributes).length).to.equal(3);
});
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
var Article, Label, sequelize, article, label, t;
return Support.prepareTransactionTest(this.sequelize).then(function(_sequelize) {
sequelize = _sequelize;
Article = sequelize.define('Article', { 'title': DataTypes.STRING });
Label = sequelize.define('Label', { 'text': DataTypes.STRING });
Article.hasMany(Label);
return sequelize.sync({ force: true });
}).then(function() {
return Promise.all([
Article.create({ title: 'foo' }),
Label.create({ text: 'bar' })
]);
}).spread(function(_article, _label) {
article = _article;
label = _label;
return sequelize.transaction();
}).then(function(_t) {
t = _t;
return article.setLabels([label], { transaction: t });
}).then(function() {
return Article.all({ transaction: t });
}).then(function(articles) {
return articles[0].hasLabel(label).then(function(hasLabel) {
expect(hasLabel).to.be.false;
});
}).then(function() {
return Article.all({ transaction: t });
}).then(function(articles) {
return articles[0].hasLabel(label, { transaction: t }).then(function(hasLabel) {
expect(hasLabel).to.be.true;
return t.rollback();
});
});
});
}
it('does not have any labels assigned to it initially', function() {
return Promise.all([
this.Article.create({ title: 'Article' }),
this.Label.create({ text: 'Awesomeness' }),
this.Label.create({ text: 'Epicness' })
]).spread(function(article, label1, label2) {
return Promise.all([
article.hasLabel(label1),
article.hasLabel(label2)
]);
}).spread(function(hasLabel1, hasLabel2) {
expect(hasLabel1).to.be.false;
expect(hasLabel2).to.be.false;
});
});
it('answers true if the label has been assigned', function() {
return Promise.all([
this.Article.create({ title: 'Article' }),
this.Label.create({ text: 'Awesomeness' }),
this.Label.create({ text: 'Epicness' })
]).spread(function(article, label1, label2) {
return article.addLabel(label1).then(function() {
return Promise.all([
article.hasLabel(label1),
article.hasLabel(label2)
]);
});
}).spread(function(hasLabel1, hasLabel2) {
expect(hasLabel1).to.be.true;
expect(hasLabel2).to.be.false;
});
});
it('answers correctly if the label has been assigned when passing a primary key instead of an object', function() {
return Promise.all([
this.Article.create({ title: 'Article' }),
this.Label.create({ text: 'Awesomeness' }),
this.Label.create({ text: 'Epicness' })
]).spread(function(article, label1, label2) {
return article.addLabel(label1).then(function() {
return Promise.all([
article.hasLabel(label1.id),
article.hasLabel(label2.id)
]);
});
}).spread(function(hasLabel1, hasLabel2) {
expect(hasLabel1).to.be.true;
expect(hasLabel2).to.be.false;
});
});
});
describe('hasAll', function() {
beforeEach(function() {
this.Article = this.sequelize.define('Article', {
'title': DataTypes.STRING
});
this.Label = this.sequelize.define('Label', {
'text': DataTypes.STRING
});
this.Article.hasMany(this.Label);
return this.sequelize.sync({ force: true });
});
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
this.sequelize = sequelize;
this.Article = sequelize.define('Article', { 'title': DataTypes.STRING });
this.Label = sequelize.define('Label', { 'text': DataTypes.STRING });
this.Article.hasMany(this.Label);
return this.sequelize.sync({ force: true });
}).then(function() {
return Promise.all([
this.Article.create({ title: 'foo' }),
this.Label.create({ text: 'bar' })
]);
}).spread(function(article, label) {
this.article = article;
this.label = label;
return this.sequelize.transaction();
}).then(function(t) {
this.t = t;
return this.article.setLabels([this.label], { transaction: t });
}).then(function() {
return this.Article.all({ transaction: this.t });
}).then(function(articles) {
return Promise.all([
articles[0].hasLabels([this.label]),
articles[0].hasLabels([this.label], { transaction: this.t })
]);
}).spread(function(hasLabel1, hasLabel2) {
expect(hasLabel1).to.be.false;
expect(hasLabel2).to.be.true;
return this.t.rollback();
});
});
}
it('answers false if only some labels have been assigned', function() {
return Promise.all([
this.Article.create({ title: 'Article' }),
this.Label.create({ text: 'Awesomeness' }),
this.Label.create({ text: 'Epicness' })
]).spread(function(article, label1, label2) {
return article.addLabel(label1).then(function() {
return article.hasLabels([label1, label2]);
});
}).then(function(result) {
expect(result).to.be.false;
});
});
it('answers false if only some labels have been assigned when passing a primary key instead of an object', function() {
return Promise.all([
this.Article.create({ title: 'Article' }),
this.Label.create({ text: 'Awesomeness' }),
this.Label.create({ text: 'Epicness' })
]).spread(function(article, label1, label2) {
return article.addLabel(label1).then(function() {
return article.hasLabels([label1.id, label2.id]).then(function(result) {
expect(result).to.be.false;
});
});
});
});
it('answers true if all label have been assigned', function() {
return Promise.all([
this.Article.create({ title: 'Article' }),
this.Label.create({ text: 'Awesomeness' }),
this.Label.create({ text: 'Epicness' })
]).spread(function(article, label1, label2) {
return article.setLabels([label1, label2]).then(function() {
return article.hasLabels([label1, label2]).then(function(result) {
expect(result).to.be.true;
});
});
});
});
it('answers true if all label have been assigned when passing a primary key instead of an object', function() {
return Promise.all([
this.Article.create({ title: 'Article' }),
this.Label.create({ text: 'Awesomeness' }),
this.Label.create({ text: 'Epicness' })
]).spread(function(article, label1, label2) {
return article.setLabels([label1, label2]).then(function() {
return article.hasLabels([label1.id, label2.id]).then(function(result) {
expect(result).to.be.true;
});
});
});
});
});
describe('setAssociations', function() {
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
this.Article = sequelize.define('Article', { 'title': DataTypes.STRING });
this.Label = sequelize.define('Label', { 'text': DataTypes.STRING });
this.Article.hasMany(this.Label);
this.sequelize = sequelize;
return sequelize.sync({ force: true });
}).then(function() {
return Promise.all([
this.Article.create({ title: 'foo' }),
this.Label.create({ text: 'bar' }),
this.sequelize.transaction()
]);
}).spread(function(article, label, t) {
this.article = article;
this. t = t;
return article.setLabels([label], { transaction: t });
}).then(function() {
return this.Label.findAll({ where: { ArticleId: this.article.id }, transaction: undefined });
}).then(function(labels) {
expect(labels.length).to.equal(0);
return this.Label.findAll({ where: { ArticleId: this.article.id }, transaction: this.t });
}).then(function(labels) {
expect(labels.length).to.equal(1);
return this.t.rollback();
});
});
}
it('clears associations when passing null to the set-method', function() {
var User = this.sequelize.define('User', { username: DataTypes.STRING })
, Task = this.sequelize.define('Task', { title: DataTypes.STRING });
Task.hasMany(User);
return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
User.create({ username: 'foo' }),
Task.create({ title: 'task' })
]);
}).bind({}).spread(function(user, task) {
this.task = task;
return task.setUsers([user]);
}).then(function() {
return this.task.getUsers();
}).then(function(users) {
expect(users).to.have.length(1);
return this.task.setUsers(null);
}).then(function() {
return this.task.getUsers();
}).then(function(users) {
expect(users).to.have.length(0);
});
});
it('supports passing the primary key instead of an object', function() {
var Article = this.sequelize.define('Article', { title: DataTypes.STRING })
, Label = this.sequelize.define('Label', { text: DataTypes.STRING });
Article.hasMany(Label);
return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
Article.create({}),
Label.create({ text: 'label one' }),
Label.create({ text: 'label two' })
]);
}).bind({}).spread(function(article, label1, label2) {
this.article = article;
this.label1 = label1;
this.label2 = label2;
return article.addLabel(label1.id);
}).then(function() {
return this.article.setLabels([this.label2.id]);
}).then(function() {
return this.article.getLabels();
}).then(function(labels) {
expect(labels).to.have.length(1);
expect(labels[0].text).to.equal('label two');
});
});
});
describe('addAssociations', function() {
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
this.Article = sequelize.define('Article', { 'title': DataTypes.STRING });
this.Label = sequelize.define('Label', { 'text': DataTypes.STRING });
this.Article.hasMany(this.Label);
this.sequelize = sequelize;
return sequelize.sync({ force: true });
}).then(function() {
return Promise.all([
this.Article.create({ title: 'foo' }),
this.Label.create({ text: 'bar' })
]);
}).spread(function(article, label) {
this.article = article;
this.label = label;
return this.sequelize.transaction();
}).then(function(t) {
this.t = t;
return this.article.addLabel(this.label, { transaction: this.t });
}).then(function() {
return this.Label.findAll({ where: { ArticleId: this.article.id }, transaction: undefined });
}).then(function(labels) {
expect(labels.length).to.equal(0);
return this.Label.findAll({ where: { ArticleId: this.article.id }, transaction: this.t });
}).then(function(labels) {
expect(labels.length).to.equal(1);
return this.t.rollback();
});
});
}
it('supports passing the primary key instead of an object', function() {
var Article = this.sequelize.define('Article', { 'title': DataTypes.STRING })
, Label = this.sequelize.define('Label', { 'text': DataTypes.STRING });
Article.hasMany(Label);
return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
Article.create({}),
Label.create({ text: 'label one' })
]);
}).bind({}).spread(function(article, label) {
this.article = article;
return article.addLabel(label.id);
}).then(function() {
return this.article.getLabels();
}).then(function(labels) {
expect(labels[0].text).to.equal('label one'); // Make sure that we didn't modify one of the other attributes while building / saving a new instance
});
});
});
describe('addMultipleAssociations', function() {
it('adds associations without removing the current ones', function() {
var User = this.sequelize.define('User', { username: DataTypes.STRING })
, Task = this.sequelize.define('Task', { title: DataTypes.STRING });
Task.hasMany(User);
return this.sequelize.sync({ force: true }).then(function() {
return User.bulkCreate([
{ username: 'foo '},
{ username: 'bar '},
{ username: 'baz '}
]);
}).bind({}).then(function() {
return Task.create({ title: 'task' });
}).then(function(task) {
this.task = task;
return User.findAll();
}).then(function(users) {
this.users = users;
return this.task.setUsers([users[0]]);
}).then(function() {
return this.task.addUsers([this.users[1], this.users[2]]);
}).then(function() {
return this.task.getUsers();
}).then(function(users) {
expect(users).to.have.length(3);
});
});
});
it('clears associations when passing null to the set-method with omitNull set to true', function() {
this.sequelize.options.omitNull = true;
var User = this.sequelize.define('User', { username: DataTypes.STRING })
, Task = this.sequelize.define('Task', { title: DataTypes.STRING });
Task.hasMany(User);
return this.sequelize.sync({ force: true }).then(function() {
return User.create({ username: 'foo' });
}).bind({}).then(function(user) {
this.user = user;
return Task.create({ title: 'task' });
}).then(function(task) {
this.task = task;
return task.setUsers([this.user]);
}).then(function() {
return this.task.getUsers();
}).then(function(_users) {
expect(_users).to.have.length(1);
return this.task.setUsers(null);
}).then(function() {
return this.task.getUsers();
}).then(function(_users) {
expect(_users).to.have.length(0);
});
});
describe('createAssociations', function() {
it('creates a new associated object', function() {
var Article = this.sequelize.define('Article', { 'title': DataTypes.STRING })
, Label = this.sequelize.define('Label', { 'text': DataTypes.STRING });
Article.hasMany(Label);
return this.sequelize.sync({ force: true }).then(function() {
return Article.create({ title: 'foo' });
}).then(function(article) {
return article.createLabel({ text: 'bar' }).return (article);
}).then(function(article) {
return Label.findAll({ where: { ArticleId: article.id }});
}).then(function(labels) {
expect(labels.length).to.equal(1);
});
});
it('creates the object with the association directly', function() {
var spy = sinon.spy();
var Article = this.sequelize.define('Article', {
'title': DataTypes.STRING
}), Label = this.sequelize.define('Label', {
'text': DataTypes.STRING
});
Article.hasMany(Label);
return this.sequelize.sync({ force: true }).then(function() {
return Article.create({ title: 'foo' });
}).bind({}).then(function(article) {
this.article = article;
return article.createLabel({ text: 'bar' }, {logging: spy});
}).then(function(label) {
expect(spy.calledOnce).to.be.true;
expect(label.ArticleId).to.equal(this.article.id);
});
});
if (current.dialect.supports.transactions) {
it('supports transactions', function() {
return Support.prepareTransactionTest(this.sequelize).bind({}).then(function(sequelize) {
this.sequelize = sequelize;
this.Article = sequelize.define('Article', { 'title': DataTypes.STRING });
this.Label = sequelize.define('Label', { 'text': DataTypes.STRING });
this.Article.hasMany(this.Label);
return sequelize.sync({ force: true});
}).then(function() {
return this.Article.create({ title: 'foo' });
}).then(function(article) {
this.article = article;
return this.sequelize.transaction();
}).then(function(t) {
this.t = t;
return this.article.createLabel({ text: 'bar' }, { transaction: this.t });
}).then(function() {
return this.Label.findAll();
}).then(function(labels) {
expect(labels.length).to.equal(0);
return this.Label.findAll({ where: { ArticleId: this.article.id }});
}).then(function(labels) {
expect(labels.length).to.equal(0);
return this.Label.findAll({ where: { ArticleId: this.article.id }, transaction: this.t });
}).then(function(labels) {
expect(labels.length).to.equal(1);
return this.t.rollback();
});
});
}
it('supports passing the field option', function() {
var Article = this.sequelize.define('Article', {
'title': DataTypes.STRING
})
, Label = this.sequelize.define('Label', {
'text': DataTypes.STRING
});
Article.hasMany(Label);
return this.sequelize.sync({force: true}).then(function() {
return Article.create();
}).then(function(article) {
return article.createLabel({
text: 'yolo'
}, {
fields: ['text']
}).return (article);
}).then(function(article) {
return article.getLabels();
}).then(function(labels) {
expect(labels.length).to.be.ok;
});
});
});
describe('getting assocations with options', function() {
beforeEach(function() {
var self = this;
this.User = this.sequelize.define('User', { username: DataTypes.STRING });
this.Task = this.sequelize.define('Task', { title: DataTypes.STRING, active: DataTypes.BOOLEAN });
this.User.hasMany(self.Task);
return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
self.User.create({ username: 'John'}),
self.Task.create({ title: 'Get rich', active: true}),
self.Task.create({ title: 'Die trying', active: false})
]);
}).spread(function(john, task1, task2) {
return john.setTasks([task1, task2]);
});
});
it('should treat the where object of associations as a first class citizen', function() {
var self = this;
this.Article = this.sequelize.define('Article', {
'title': DataTypes.STRING
});
this.Label = this.sequelize.define('Label', {
'text': DataTypes.STRING,
'until': DataTypes.DATE
});
this.Article.hasMany(this.Label);
return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
self.Article.create({ title: 'Article' }),
self.Label.create({ text: 'Awesomeness', until: '2014-01-01 01:00:00' }),
self.Label.create({ text: 'Epicness', until: '2014-01-03 01:00:00' })
]);
}).bind({}).spread(function(article, label1, label2) {
this.article = article;
return article.setLabels([label1, label2]);
}).then(function() {
return this.article.getLabels({where: ['until > ?', moment('2014-01-02').toDate()]});
}).then(function(labels) {
expect(labels).to.be.instanceof(Array);
expect(labels).to.have.length(1);
expect(labels[0].text).to.equal('Epicness');
});
});
it('gets all associated objects when no options are passed', function() {
return this.User.find({where: {username: 'John'}}).then(function(john) {
return john.getTasks();
}).then(function(tasks) {
expect(tasks).to.have.length(2);
});
});
it('only get objects that fulfill the options', function() {
return this.User.find({ where: { username: 'John' } }).then(function(john) {
return john.getTasks({ where: { active: true }, limit: 10, order: 'id DESC' });
}).then(function(tasks) {
expect(tasks).to.have.length(1);
});
});
});
describe('countAssociations', function () {
beforeEach(function() {
var self = this;
this.User = this.sequelize.define('User', { username: DataTypes.STRING });
this.Task = this.sequelize.define('Task', { title: DataTypes.STRING, active: DataTypes.BOOLEAN });
this.User.hasMany(self.Task, {
foreignKey: 'userId'
});
return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
self.User.create({ username: 'John'}),
self.Task.create({ title: 'Get rich', active: true}),
self.Task.create({ title: 'Die trying', active: false})
]);
}).spread(function(john, task1, task2) {
self.user = john;
return john.setTasks([task1, task2]);
});
});
it('should count all associations', function () {
return expect(this.user.countTasks({})).to.eventually.equal(2);
});
it('should count filtered associations', function () {
return expect(this.user.countTasks({
where: {
active: true
}
})).to.eventually.equal(1);
});
it('should count scoped associations', function () {
this.User.hasMany(this.Task, {
foreignKey: 'userId',
as: 'activeTasks',
scope: {
active: true
}
});
return expect(this.user.countActiveTasks({})).to.eventually.equal(1);
});
});
describe('selfAssociations', function() {
it('should work with alias', function() {
var Person = this.sequelize.define('Group', {});
Person.hasMany(Person, { as: 'Children'});
return this.sequelize.sync();
});
});
});
describe('Foreign key constraints', function() {
describe('1:m', function() {
it('sets null by default', function() {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING });
User.hasMany(Task);
return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
User.create({ username: 'foo' }),
Task.create({ title: 'task' })
]);
}).spread(function(user, task) {
return user.setTasks([task]).then(function() {
return user.destroy().then(function() {
return task.reload();
});
});
}).then(function(task) {
expect(task.UserId).to.equal(null);
});
});
it('sets to CASCADE if allowNull: false', function() {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING });
User.hasMany(Task, { foreignKey: { allowNull: false }}); // defaults to CASCADE
return this.sequelize.sync({ force: true }).then(function() {
return User.create({ username: 'foo' }).then(function(user) {
return Task.create({ title: 'task', UserId: user.id }).then(function() {
return user.destroy().then(function() {
return Task.findAll();
});
});
}).then(function(tasks) {
expect(tasks).to.be.empty;
});
});
});
it('should be possible to remove all constraints', function() {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING });
User.hasMany(Task, { constraints: false });
return this.sequelize.sync({ force: true }).bind({}).then(function() {
return Promise.all([
User.create({ username: 'foo' }),
Task.create({ title: 'task' })
]);
}).spread(function(user, task) {
this.user = user;
this.task = task;
return user.setTasks([task]);
}).then(function() {
return this.user.destroy();
}).then(function() {
return this.task.reload();
}).then(function(task) {
expect(task.UserId).to.equal(this.user.id);
});
});
it('can cascade deletes', function() {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING });
User.hasMany(Task, {onDelete: 'cascade'});
return this.sequelize.sync({ force: true }).bind({}).then(function() {
return Promise.all([
User.create({ username: 'foo' }),
Task.create({ title: 'task' })
]);
}).spread(function(user, task) {
this.user = user;
this.task = task;
return user.setTasks([task]);
}).then(function() {
return this.user.destroy();
}).then(function() {
return Task.findAll();
}).then(function(tasks) {
expect(tasks).to.have.length(0);
});
});
// NOTE: mssql does not support changing an autoincrement primary key
if (dialect !== 'mssql') {
it('can cascade updates', function() {
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING });
User.hasMany(Task, {onUpdate: 'cascade'});
return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
User.create({ username: 'foo' }),
Task.create({ title: 'task' })
]);
}).spread(function(user, task) {
return user.setTasks([task]).return (user);
}).then(function(user) {
// Changing the id of a DAO requires a little dance since
// the `UPDATE` query generated by `save()` uses `id` in the
// `WHERE` clause
var tableName = user.sequelize.getQueryInterface().QueryGenerator.addSchema(user.Model);
return user.sequelize.getQueryInterface().update(user, tableName, {id: 999}, {id: user.id});
}).then(function() {
return Task.findAll();
}).then(function(tasks) {
expect(tasks).to.have.length(1);
expect(tasks[0].UserId).to.equal(999);
});
});
}
if (current.dialect.supports.constraints.restrict) {
it('can restrict deletes', function() {
var self = this;
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING });
User.hasMany(Task, {onDelete: 'restrict'});
return this.sequelize.sync({ force: true }).bind({}).then(function() {
return Promise.all([
User.create({ username: 'foo' }),
Task.create({ title: 'task' })
]);
}).spread(function(user, task) {
this.user = user;
this.task = task;
return user.setTasks([task]);
}).then(function() {
return this.user.destroy().catch (self.sequelize.ForeignKeyConstraintError, function() {
// Should fail due to FK violation
return Task.findAll();
});
}).then(function(tasks) {
expect(tasks).to.have.length(1);
});
});
it('can restrict updates', function() {
var self = this;
var Task = this.sequelize.define('Task', { title: DataTypes.STRING })
, User = this.sequelize.define('User', { username: DataTypes.STRING });
User.hasMany(Task, {onUpdate: 'restrict'});
return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
User.create({ username: 'foo' }),
Task.create({ title: 'task' })
]);
}).spread(function(user, task) {
return user.setTasks([task]).return (user);
}).then(function(user) {
// Changing the id of a DAO requires a little dance since
// the `UPDATE` query generated by `save()` uses `id` in the
// `WHERE` clause
var tableName = user.sequelize.getQueryInterface().QueryGenerator.addSchema(user.Model);
return user.sequelize.getQueryInterface().update(user, tableName, {id: 999}, {id: user.id})
.catch (self.sequelize.ForeignKeyConstraintError, function() {
// Should fail due to FK violation
return Task.findAll();
});
}).then(function(tasks) {
expect(tasks).to.have.length(1);
});
});
}
});
});
describe('Association options', function() {
it('can specify data type for autogenerated relational keys', function() {
var User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING })
, dataTypes = [Sequelize.INTEGER, Sequelize.BIGINT, Sequelize.STRING]
, self = this
, Tasks = {};
return Promise.each(dataTypes, function(dataType) {
var tableName = 'TaskXYZ_' + dataType.key;
Tasks[dataType] = self.sequelize.define(tableName, { title: DataTypes.STRING });
User.hasMany(Tasks[dataType], { foreignKey: 'userId', keyType: dataType, constraints: false });
return Tasks[dataType].sync({ force: true }).then(function() {
expect(Tasks[dataType].rawAttributes.userId.type).to.be.an.instanceof(dataType);
});
});
});
it('infers the keyType if none provided', function() {
var User = this.sequelize.define('User', {
id: { type: DataTypes.STRING, primaryKey: true },
username: DataTypes.STRING
})
, Task = this.sequelize.define('Task', {
title: DataTypes.STRING
});
User.hasMany(Task);
return this.sequelize.sync({ force: true }).then(function() {
expect(Task.rawAttributes.UserId.type instanceof DataTypes.STRING).to.be.ok;
});
});
describe('allows the user to provide an attribute definition object as foreignKey', function() {
it('works with a column that hasnt been defined before', function() {
var Task = this.sequelize.define('task', {})
, User = this.sequelize.define('user', {});
User.hasMany(Task, {
foreignKey: {
name: 'uid',
allowNull: false
}
});
expect(Task.rawAttributes.uid).to.be.ok;
expect(Task.rawAttributes.uid.allowNull).to.be.false;
expect(Task.rawAttributes.uid.references.model).to.equal(User.getTableName());
expect(Task.rawAttributes.uid.references.key).to.equal('id');
});
it('works when taking a column directly from the object', function() {
var Project = this.sequelize.define('project', {
user_id: {
type: Sequelize.INTEGER,
defaultValue: 42
}
})
, User = this.sequelize.define('user', {
uid: {
type: Sequelize.INTEGER,
primaryKey: true
}
});
User.hasMany(Project, { foreignKey: Project.rawAttributes.user_id});
expect(Project.rawAttributes.user_id).to.be.ok;
expect(Project.rawAttributes.user_id.references.model).to.equal(User.getTableName());
expect(Project.rawAttributes.user_id.references.key).to.equal('uid');
expect(Project.rawAttributes.user_id.defaultValue).to.equal(42);
});
it('works when merging with an existing definition', function() {
var Task = this.sequelize.define('task', {
userId: {
defaultValue: 42,
type: Sequelize.INTEGER
}
})
, User = this.sequelize.define('user', {});
User.hasMany(Task, { foreignKey: { allowNull: true }});
expect(Task.rawAttributes.userId).to.be.ok;
expect(Task.rawAttributes.userId.defaultValue).to.equal(42);
expect(Task.rawAttributes.userId.allowNull).to.be.ok;
});
});
it('should throw an error if foreignKey and as result in a name clash', function() {
var User = this.sequelize.define('user', {
user: Sequelize.INTEGER
});
expect(User.hasMany.bind(User, User, { as: 'user' })).to
.throw ('Naming collision between attribute \'user\' and association \'user\' on model user. To remedy this, change either foreignKey or as in your association definition');
});
});
});
|
var esriUrl='http://maps1.arcgisonline.com/ArcGIS/rest/services/USA_Federal_Lands/MapServer';
var esriAttrib='Map data © <a href="http://osm.org/copyright">OpenStreetMap</a> contributors';
var esri = L.esri.dynamicMapLayer(esriUrl, {});
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © <a href="http://osm.org/copyright">OpenStreetMap</a> contributors';
var osm = new L.TileLayer(osmUrl, {
attribution: osmAttrib,
detectRetina: true
});
var token = 'pk.eyJ1IjoicmZyYW50eiIsImEiOiJkN2p1Wm93In0.uha-WxArw2jdGYmsvacXeA';
var mapboxUrl = 'http://api.tiles.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}@2x.png?access_token=' + token;
var mapboxAttrib = 'Map data © <a href="http://osm.org/copyright">OpenStreetMap</a> contributors. Tiles from <a href="https://www.mapbox.com">Mapbox</a>.';
var mapbox = new L.TileLayer(mapboxUrl, {
attribution: mapboxAttrib
});
var map = new L.Map('map', {
layers: [mapbox],
center: [51.505, -0.09],
zoom: 10,
zoomControl: true
});
// add location control to global name space for testing only
// on a production site, omit the "lc = "!
lc = L.control.locate({
follow: true,
strings: {
title: "Show me where I am, yo!"
}
}).addTo(map);
map.on('startfollowing', function() {
map.on('dragstart', lc._stopFollowing, lc);
}).on('stopfollowing', function() {
map.off('dragstart', lc._stopFollowing, lc);
});
|
/**
* Created by ouq77 on 19/02/17.
*/
const chalk = require('chalk')
const {filterIdentifierRows, filterChargeCategoryRows, filterChargeTypeRows} = require('./helpers/filters')
const FLICK_FIXED_CHARGE_RGX = /Fixed/
const NETWORK_FIXED_CHARGE_RGX = /^F-[A-Z]-(?!N11)[0-9A-Z]{3}$|FIXD/
const NETWORK_CHARGE = 'network'
const FLICK_CHARGE = 'flick'
const GENERATION_CHARGE = 'generation'
const METERING_CHARGE = 'metering'
const LEVY_CHARGE = 'levy'
const mapRows = (map, data, chargeCategory, key, chargeType, regex = '') => {
let processed = 0
filterChargeCategoryRows(data, chargeCategory).forEach(row => {
const invoiceableIdentifier = row[key]
const chargeName = row['Charge Name']
if (!map.has(invoiceableIdentifier)) {
map.set(invoiceableIdentifier, {
network: {
fixedCharges: [],
variableCharges: []
},
flick: {
fixedCharges: [],
variableCharges: []
},
generation: {
charges: []
},
metering: {
charges: []
},
levy: {
charges: []
}
})
}
const record = map.get(invoiceableIdentifier)
if (regex) {
if (regex.test(chargeName)) {
if (!record[chargeType].fixedCharges.includes(chargeName)) {
record[chargeType].fixedCharges.push(chargeName)
}
} else {
if (!record[chargeType].variableCharges.includes(chargeName)) {
record[chargeType].variableCharges.push(chargeName)
}
}
} else {
if (!record[chargeType].charges.includes(chargeName)) {
record[chargeType].charges.push(chargeName)
}
}
processed++
})
return processed
}
const populateResult = (chargeArray, target, targetFieldPrefix, counterMap, targetCounter, warning) => {
let chargeCounter = 0
if (chargeArray && chargeArray.length > 0) {
chargeArray.forEach((charge) => {
target[`${targetFieldPrefix}RateName_${++chargeCounter}`] = charge
if (counterMap.get(targetCounter) < chargeCounter) {
counterMap.set(targetCounter, chargeCounter)
}
})
return ''
} else {
return warning
}
}
const fillEmptyValues = (result, maxCols, field) => {
for (let i = 1; i <= maxCols; i++) {
if (!result[`${field}RateName_${i}`]) {
result[`${field}RateName_${i}`] = ''
}
}
}
const processCharges = (yinviliData, excludeData, keys) => new Promise((resolve) => {
const customerMap = new Map()
const colCounterMap = new Map()
colCounterMap.set('maxNetworkFixedCols', 0)
colCounterMap.set('maxNetworkVariableCols', 0)
colCounterMap.set('maxFlickFixedCols', 0)
colCounterMap.set('maxFlickVariableCols', 0)
colCounterMap.set('maxGenerationCols', 0)
colCounterMap.set('maxMeteringCols', 0)
colCounterMap.set('maxLevyCols', 0)
let excludeIdentifiers = []
excludeData.forEach(excludeIdentifier => excludeIdentifiers.push(excludeIdentifier[keys.excludeKey]))
excludeIdentifiers = excludeIdentifiers.filter(identifier => identifier !== '')
const results = []
let processed
let allWarnings = ''
let totalWarnings = 0
console.log(chalk.green(`excluding ${excludeIdentifiers.length} identifier(s)\n`))
const filteredYinviliData = excludeIdentifiers.length > 0 ?
filterIdentifierRows(yinviliData, 'Invoiceable Identifier', excludeIdentifiers) : yinviliData
console.log(chalk.blue(`mapping all network charges\n`))
processed = mapRows(customerMap, filteredYinviliData, 'Network', keys.yinviliKey, NETWORK_CHARGE, NETWORK_FIXED_CHARGE_RGX)
console.log(chalk.green(`mapped ${processed} network charges\n`))
console.log(chalk.blue(`mapping all flick charges\n`))
processed = mapRows(customerMap, filteredYinviliData, 'Flick', keys.yinviliKey, FLICK_CHARGE, FLICK_FIXED_CHARGE_RGX)
console.log(chalk.green(`mapped ${processed} flick charges\n`))
console.log(chalk.blue(`mapping all generation charges\n`))
processed = mapRows(customerMap, filteredYinviliData, 'Generation', keys.yinviliKey, GENERATION_CHARGE)
console.log(chalk.green(`mapped ${processed} generation charges\n`))
console.log(chalk.blue(`mapping all metering charges\n`))
processed = mapRows(customerMap, filteredYinviliData, 'Metering', keys.yinviliKey, METERING_CHARGE)
console.log(chalk.green(`mapped ${processed} metering charges\n`))
console.log(chalk.blue(`mapping all levy charges\n`))
processed = mapRows(customerMap, filterChargeTypeRows(filteredYinviliData, 'EA Levy'), 'Other', keys.yinviliKey, LEVY_CHARGE)
console.log(chalk.green(`mapped ${processed} levy charges\n`))
console.log(chalk.blue(`checking ${customerMap.size} customer rows\n`))
for (const [identifier, record] of customerMap.entries()) {
let warnings = ''
const result = {
'Invoiceable Identifier': identifier
}
warnings += populateResult(
record.network.fixedCharges, result, 'F_Network', colCounterMap, 'maxNetworkFixedCols', ' no fixed network charge;')
warnings += populateResult(
record.network.variableCharges, result, 'V_Network', colCounterMap, 'maxNetworkVariableCols', ' no variable network charge;')
warnings += populateResult(
record.flick.fixedCharges, result, 'F_Flick', colCounterMap, 'maxFlickFixedCols', ' no fixed flick charge;')
warnings += populateResult(
record.flick.variableCharges, result, 'V_Flick', colCounterMap, 'maxFlickVariableCols', ' no variable flick charge;')
warnings += populateResult(
record.generation.charges, result, 'Generation', colCounterMap, 'maxGenerationCols', ' no generation charge;')
warnings += populateResult(
record.metering.charges, result, 'Metering', colCounterMap, 'maxMeteringCols', ' no metering charge;')
warnings += populateResult(
record.levy.charges, result, 'Levy', colCounterMap, 'maxLevyCols', ' no levy charge;')
if (warnings) {
allWarnings += `${identifier}:${warnings}\n`
totalWarnings++
}
results.push(result)
}
console.log(chalk.green(`checked ${customerMap.size - excludeIdentifiers.length} customer rows\n`))
console.log(chalk.blue('filling all empty columns with ""\n'))
results.forEach(result => {
fillEmptyValues(result, colCounterMap.get('maxNetworkFixedCols'), 'F_Network')
fillEmptyValues(result, colCounterMap.get('maxNetworkVariableCols'), 'V_Network')
fillEmptyValues(result, colCounterMap.get('maxFlickFixedCols'), 'F_Flick')
fillEmptyValues(result, colCounterMap.get('maxFlickVariableCols'), 'V_Flick')
fillEmptyValues(result, colCounterMap.get('maxGenerationCols'), 'Generation')
fillEmptyValues(result, colCounterMap.get('maxMeteringCols'), 'Metering')
fillEmptyValues(result, colCounterMap.get('maxLevyCols'), 'Levy')
})
console.log(chalk.green('filled all empty columns with ""\n'))
if (totalWarnings > 0) {
console.log(chalk.red(allWarnings))
console.log(chalk.red(`total: ${totalWarnings} \uD83D\uDCA9\n`))
} else {
console.log(chalk.green('No warnings - good to go \uD83C\uDF86\n'))
}
console.log(chalk.green(`checked ${customerMap.size} customer rows\n`))
resolve({
results,
colCounterMap
})
})
module.exports = processCharges
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import NoteCard from './NoteCard';
import { getNotes } from '../../redux/modules/Notes/actions';
class NotesIndex extends Component {
componentDidMount() {
const user_id = this.props.currentUser.id;
const { token } = this.props;
this.props.getNotes(user_id, token)
}
render() {
const { notes } = this.props;
return (
<div>
{notes.length > 0 ?
<p>* Click on a note to view full content *</p>
:
<p>* Create a <NavLink to="/notes/new">new note</NavLink> to get started *</p>
}
{notes.map(note => <NoteCard key={note.id} note={note} />)}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
token: state.auth.token,
currentUser: state.auth.currentUser,
notes: state.notes.notesArr
};
};
export default connect(mapStateToProps, { getNotes })(NotesIndex);
|
var debug = require('debug')('attendance:noteController');
var Note = require('../models/note');
var User = require('../models/user');
var HolidayType = require('../models/holidayType');
var Role = require('../models/role');
var NoteSchema = require('../schemas/note');
var debugNewRequest = '\n\n\n\n\n\n\n\n\n\n\n\n'; // sepearate new debug with some newlines
//require Holiday
exports.new = function(req, res){
//获取参数
var _note = req.body.note;
//console.log("接收到的_note :" + _note);
//调试信息
debug(debugNewRequest + 'Get params from front,note:\n' + JSON.stringify(_note));
var note = new Note(_note);
User
.find({"_id": note.user})
.populate({path: 'userRole'})
.exec(function(err, user){
note = setState(user[0],note);
//console.log('添加状态的note :'+ note );
note.save(function(err, note){
if(err){
console.log(err);
}else{
//跳转到请假状态页
// console.log("写入数据库后的回调:"+note);
// res.render('reqState', {
// title: "请假状态页",
// note: note
// });
debug('Create new note succeeded');
res.send(note);
}
});
});
};
//根据用户角色,对Note置初始状态
function setState(_user,_note){
HolidayType
.find({_id: _note.holidayType})
.exec(function(err, holidayType){
if(holidayType.holidayName.equals('事假') || holidayType.holidayName.equals('年假') || holidayType.holidayName.equals('病假')){
if(_note.timeLength <= 1){//t<=1 部门经理
_note.highState = 10;
}else if(_note.timeLength <=3){//1<t<=3 部门经理+副总
_note.highState = 20;
}else{//3<t 部门经理+副总经理+总经理
_note.highState = 30;
}
}else if(holidayType.holidayName.equals('工伤假') || holidayType.holidayName.equals('产假') || holidayType.holidayName.equals('婚假')){
//总经理
_note.highState = 30;
}else if(holidayType.holidayName.equals('产检假')){
if(_note.timeLength <=1 ){//t<=1 部门经理
_note.highState = 10;
}else{//1<t 部门经理+总经理
_note.highState = 30;
}
}else if(holidayType.holidayName.equals('丧假')){
if(_note.timeLength){//t<=1 部门经理
_note.highState = 10;
}else{//1<t 部门经理+副总经理
_note.highState = 20;
}
}else if(holidayType.holidayName.equals('公益假')){
//部门经理
_note.highState = 10;
}
if(_user.userRole.roleName === '员工'){
_note.curState = 0;
}else if(_user.userRole.roleName === '部门经理'){
_note.curState = 10;
}else if(_user.userRole.roleName === '副总经理'){
_note.curState = 20;
}else if(_user.userRole.roleName === '总经理'){
_note.curState = 30;
}
//console.log(_user);
return _note;
});
}
function findRoleByUserId(userId){
return User.findById(userId)
.then(function(user){
debug('Found user by userId:%s:\n%s', userId, user);
var role = user.userRole;
debug('Role of user:\n' + role);
return role;
});
}
exports.findNotesByManagerId = function (req, res, next){
// var managerId = "58493581f210182bbc28713f";
var managerId = req.params.managerId;
debug(debugNewRequest + 'Get params from front,managerId:\n' + managerId);
findRoleByUserId(managerId)
.then(function(role){
Note.findByState(role.preState)
.then(function(notes){
debug('Find all notes by manager preState, notes.length:' + notes.length);
return res.send(notes);
});
})
.catch(next);
};
function _updateStateByManager(managerId, note, approved){ // this way of `res` is ugly.
// create a new Promise to avoid look into database when manager disapprove this note.
return new Promise(function(resolve) {
if(approved === false){
debug('Set note state to 0 beacuse of disapprove');
resolve(0);
}
else{
return findRoleByUserId(managerId)
.then(function(role){
if (role.postState === note.highState){
debug('Set note state to -1, approved and role.postState === note.highState');
resolve(-1);
}
else{
debug('Set note state to ' + role.postState + ', approved but role.postState != note.highState');
resolve(role.postState);
}
});
}
});
// Or, just a more clean way.
/*
return findRoleByUserId(managerId)
.then(function(role){
if(approved === false){
debug('Set note state to 0 beacuse of disapprove');
return 0;
}
if (role.postState === note.highState){
debug('Set note state to -1, approved and role.postState === note.highState');
return -1;
}
else{
debug('Set note state to ' + role.postState + ', approved but role.postState != note.highState');
return role.postState;
}
});
*/
}
exports.updateStateByManager = function (req, res, next){
var managerId = req.body.managerId;
var noteId = req.body.noteId;
var approved = req.body.approved;
debug(debugNewRequest + 'Get params from front end, managerId:%s, noteId:%s, approved:%s\n', managerId, noteId, approved);
var newState = 0;
Note.findById(noteId)
.then(function(note){
debug('Found note by noteId %s:\n%s', noteId, note);
_updateStateByManager(managerId, note, approved)
.then(function(newState){
var conditions = {_id : note._id};
var update = { $set : {state:newState}};
var options = { multi: false };
return Note.update(conditions, update, options)
.then(function(changedInfo){
debug('Update note info succeeded');
res.send(changedInfo);
});
});
})
.catch(next);
};
|
var yargs = require('yargs');
var main = require('./main.js');
var pkg = require('../package.json');
var path = require('path');
module.exports = function(currentDir) {
var argv = yargs
.usage('$0 yourConfig.js yourFile.csv')
.help('help').alias('help', 'h').describe('h', 'Show help.')
.epilog('Home page and docs: https://github.com/niiknow/filehose')
.demand(2)
.argv;
var configFile = argv._[0];
var filePath = argv._[1];
if (configFile.indexOf('./') > -1 || configFile.indexOf('/') < 0) {
configFile = path.join(currentDir, configFile);
}
if (filePath.indexOf('./') > -1 || filePath.indexOf('/') < 0) {
filePath = path.join(currentDir, filePath);
}
main(filePath, configFile);
}; |
var fs = require('fs');
var chai = require('chai');
var moment = require('moment');
var nconf = require('../lib/utilities/config').getConfig();
var logger = require('../lib/utilities/logging').getLogger(nconf);
var expect = chai.expect,
should = chai.should;
var ProtocolState = require('../lib/protocol-state.js');
var ProtocolConnection = require('../lib/connection.js');
describe.skip('Communication protocol state machine', function() {
var config;
if (nconf !== undefined) {
var registries = nconf.get('registries');
if (registries) {
config = registries['registry-test3'];
}
}
describe('simulate login/logout', function() {
var stateMachine,
fos;
before(function() {
var filename = ["/tmp/test-epp-protocol", moment().unix(), "state.log"].join('-');
fos = fs.createWriteStream(filename, {
"flags": "w",
mode: '0666'
});
});
after(function() {
// Close the writable stream after each test
fos.end();
});
before(function() {
try {
stateMachine = new ProtocolState('hexonet-test1', config);
var connection = stateMachine.connection;
/* Use a file stream instead of trying to talk
* to the actual registry, we're only testing the
* "state" control here.
*/
connection.setStream(fos);
} catch (e) {
console.error(e);
/* handle error */
}
});
it('should have loggedIn flag set to true once logged in', function(done) {
stateMachine.login({
"login": "test-user",
"password": "1234xyz"
},
"test-login-1234").then(function(data) {
try {
expect(data).to.have.deep.property('result.code', 1000);
expect(stateMachine.loggedIn).to.equal(true);
done();
} catch (e) {
done(e);
}
});
var xmlSuccess = fs.readFileSync('./test/epp-success.xml');
stateMachine.connection.clientResponse(xmlSuccess);
});
it('should have loggedIn flag set to false once logged out', function(done) {
stateMachine.command('logout', {},
'test-logout-1234').then(function(data) {
try {
expect(stateMachine.loggedIn).to.equal(false);
done();
} catch (e) {
done(e);
}
});
var xmlSuccess = fs.readFileSync('./test/epp-success.xml');
stateMachine.connection.clientResponse(xmlSuccess);
});
});
describe('login error state', function() {
var stateMachine,
fos;
before(function() {
var filename = ["/tmp/test-epp-protocol", moment().unix(), "fail-login-state.log"].join('-');
fos = fs.createWriteStream(filename, {
"flags": "w",
mode: '0666'
});
});
before(function() {
stateMachine = new ProtocolState('hexonet-test1', config);
var connection = stateMachine.connection;
/*
* Use a file stream instead of trying to talk to
* the actual registry, we're only testing the
* "state" control here.
*/
connection.setStream(fos);
});
after(function() {
// Close the writable stream after each test
fos.end();
});
it('should not have loggedIn true if log in failed', function(done) {
stateMachine.login({
"login": "test-user",
"password": "abc123"
},
'test-fail-login').then(function(data) {
expect(stateMachine.loggedIn).to.equal(false);
done();
},
function(error) {
done(new Error("should not execute"));
}
);
var xmlSuccess = fs.readFileSync('./test/epp-fail.xml');
stateMachine.connection.clientResponse(xmlSuccess);
});
});
describe('command execution', function() {
var stateMachine,
fos,
domain,
transactionId;
before(function(done) {
this.timeout(10000);
stateMachine = new ProtocolState('hexonet-test1', config);
var connection = stateMachine.connection;
connection.initStream().then(
function(data) {
setTimeout(
function() {
stateMachine.login({
"login": config.login,
"password": config.password
},
'myreg-test-1234').then(function(data) {
done();
},
function(error) {
done(error);
console.error("Unable to log in: ", error);
});
},
2000);
});
});
before(function() {
domain = ['myreg', moment().unix(), 'test.com'].join('-');
});
beforeEach(function() {
transactionId = ['myreg', moment().unix()].join('-');
});
it('should execute a checkDomain for ' + domain, function(done) {
this.timeout(4000);
stateMachine.command('checkDomain', {
"name": domain
},
transactionId).then(function(data) {
try {
expect(data).to.have.deep.property('data.domain:chkData.domain:cd.domain:name.$t', domain);
done();
} catch (e) {
done(e);
}
},
function(error) {
console.error("Unable to process response: ", error);
done(error);
});
});
it('should create a contact', function(done) {
this.timeout(4000);
var contactId = ['myreg', moment().unix()].join('-');
var contactData = {
"id": contactId,
"voice": "+1.9405551234",
"fax": "+1.9405551233",
"email": "john.doe@null.com",
"authInfo": {
"pw": "xyz123"
},
"postalInfo": [{
"name": "John Doe",
"org": "Example Ltd",
"type": "int",
"addr": [{
"street": ["742 Evergreen Terrace", "Apt b"],
"city": "Springfield",
"sp": "OR",
"pc": "97801",
"cc": "US"
}]
}]
};
stateMachine.command('createContact', contactData, transactionId).then(function(data) {
expect(data).to.have.deep.property('result.code', 1000);
done();
},
function(error) {
console.log("Got error: ", error);
done(error);
});
});
it('should fail due to local validation', function() {
this.timeout(4000);
var contactId = ['myreg', moment().unix()].join('-');
var contactData = {
"id": contactId,
"voice": "+1.9405551234",
"fax": "+1.9405551233",
"email": "john.doe@null.com",
"authInfo": {
"pw": "xyz123"
},
// omit postal info data
};
var validationError = function() {
stateMachine.command('createContact', contactData, transactionId).then(function(data) {});
};
expect(validationError).to.throw('postalInfo required in contact data');
});
after(function(done) {
this.timeout(4000);
stateMachine.command('logout', {},
'myreg-logout').then(function() {
done();
});
});
});
});
describe('Buffer preparation', function() {
it('should get correct byte count for EPP with higher order byte characters', function() {
var createContactXml = fs.readFileSync('./test/createContactUnicode.xml');
var connection = new ProtocolConnection({});
var prepped = connection.processBigEndian(createContactXml);
var bufferedMessage = new Buffer(prepped);
var bigEndianPrefix = bufferedMessage.slice(0, 4);
var actualLength = bigEndianPrefix.readUInt32BE(0);
expect(actualLength).to.equal(1424 + 4);
});
});
|
/**
* Generates a horizontal bar chart based on a set of parameters
* @param params {Object}
*/
function draw (params) {
// Define the chart's parameters
var dataset = params.dataset;
var barHeight = 50;
var chartPadding = 30;
var axisPadding = 20;
var captionPadding = 20;
var margin = {
top: chartPadding + captionPadding,
right: chartPadding,
bottom: chartPadding + axisPadding + captionPadding,
left:chartPadding + axisPadding
}
var chartHeight = 200 - margin.top - margin.bottom;
var chartWidth = 800 - margin.left - margin.right;
// Create the stack layout
var stack = d3.layout.stack()(dataset);
console.log(dataset);
// Create the scales
var xScale = d3.scale.linear();
var yScale = d3.scale.linear();
var totalEdits = dataset[dataset.length -1][0].y + dataset[dataset.length -1][0].y0;
xScale
.domain([0, totalEdits])
.range([0, chartWidth]);
yScale
.domain([0, 1])
.range([chartHeight, 0]);
// Set up the axes
var xAxis = d3.svg.axis();
var xFormatter = d3.format("f");
xAxis
.scale(xScale)
.orient('bottom');
// Create the chart
var svg = d3.select(params.anchor).append('svg')
.attr("width", chartWidth + margin.left + margin.right)
.attr("height", chartHeight + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// Create the bars
var colors = d3.scale.category10();
var series = svg
.selectAll('g')
.data(dataset)
.enter()
.append('g')
.style('fill', function (d, i) {
return colors(i);
});
var rects = series
.selectAll('rect')
.data(function (d) {
return d;
})
.enter()
.append('rect')
.attr('x', function (d) {
return xScale(d.y0);
})
.attr('y', function (d) {
return barHeight - yScale(0);
})
.attr('width', function (d) {
return xScale(d.y);
}
)
.attr('height', function (d) {
return 50;
})
.on("mouseover", mouseover)
.on("mouseout", mouseout);
// Create the tooltip and show/hide it on mouse over/out.
var tooltip = d3.select(params.anchor).append("div")
.attr("class", "tooltip")
.style("opacity", 1e-6);
function mouseover(d) {
tooltip
.style("opacity", 1)
.text(d.y
+ ' edits out of '
+ totalEdits
+ ' ('
+ d.y * 100 / totalEdits
+'%)')
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 30) + "px");
}
function mouseout() {
tooltip.style("opacity", 1e-6);
}
// Create the axes
var gx = svg
.append('g')
.attr("class", "axis")
.attr("transform", "translate(0," + chartHeight + ")")
.call(xAxis);
// Create the captions of the axes
// x axis
svg
.append('text')
.text(params.xAxisLabel)
.attr('x', chartWidth / 2)
.attr('y', chartHeight + axisPadding + chartPadding)
.attr('text-anchor', 'middle');
}
module.exports.draw = draw;
|
var upperCase = require('upper-case')
/**
* Upper case the first character of a string.
*
* @param {String} str
* @return {String}
*/
module.exports = function (str, locale) {
if (str == null) {
return ''
}
str = String(str)
return upperCase(str.charAt(0), locale) + str.substr(1)
}
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var HardwarePhonelinkOff = React.createClass({
displayName: 'HardwarePhonelinkOff',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: "M22 6V4H6.82l2 2H22zM1.92 1.65L.65 2.92l1.82 1.82C2.18 5.08 2 5.52 2 6v11H0v3h17.73l2.35 2.35 1.27-1.27L3.89 3.62 1.92 1.65zM4 6.27L14.73 17H4V6.27zM23 8h-6c-.55 0-1 .45-1 1v4.18l2 2V10h4v7h-2.18l3 3H23c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z" })
);
}
});
module.exports = HardwarePhonelinkOff; |
import InputBase from '../input_base';
import ReactDOM from 'react-dom';
import PropTypes from '../../../prop_types';
import { autobind } from '../../../utils/decorators';
import { isNil } from 'lodash';
export default class InputCheckboxBase extends InputBase {
static propTypes = {
checked: PropTypes.bool,
renderAsIndeterminate: PropTypes.bool,
};
static defaultProps = {
renderAsIndeterminate: false,
};
state = {
...this.state,
checked: this.getInitialChecked(),
};
componentDidMount() {
super.componentDidMount();
const inputNode = ReactDOM.findDOMNode(this.input);
inputNode.indeterminate = this.props.renderAsIndeterminate;
}
valueIsBoolean() {
const value = this.props.value;
return (typeof value === 'boolean' || value === 0 || value === 1);
}
getInitialChecked() {
return this.getCheckedOrBooleanValue();
}
getCheckedOrBooleanValue() {
const { checked } = this.props;
return !isNil(checked) ? checked : this.getBooleanValue();
}
getBooleanValue() {
return this.valueIsBoolean() ? !!this.props.value : false;
}
@autobind
handleReset() {
if (!this.mounted) return;
this.setState({
checked: this.getInitialChecked(),
});
}
@autobind
handleChange(event) {
const newCheckedValue = event.target.checked;
this.props.onChange(event, newCheckedValue, this);
if (!event.isDefaultPrevented()) {
const newState = { checked: newCheckedValue };
if (this.valueIsBoolean()) {
newState.value = newCheckedValue;
}
this.setState(newState);
}
}
}
|
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var inventories = require('../../app/controllers/inventories.server.controller');
// Inventories Routes
app.route('/inventories')
.get(inventories.list)
.post(users.requiresLogin, inventories.create);
app.route('/inventories/:inventoryId')
.get(inventories.read)
.put(users.requiresLogin, inventories.hasAuthorization, inventories.update)
.delete(users.requiresLogin, inventories.hasAuthorization, inventories.delete);
app.route('/inventories/load')
.post(inventories.load);
// Finish by binding the Inventory middleware
app.param('inventoryId', inventories.inventoryByID);
};
|
var Plane = require('./plane');
var Enemy = require('./enemy');
var _ = require('./lodash');
function Game(canvas) {
this.canvas = canvas;
this.context = canvas.getContext('2d');
this.context.counter = 0;
this.currentScore = 0;
this.timeCounter = 0;
this.enemyCreationCounter = 0;
this.enemyInterval = 300;
this.enemyPatternReset = 900;
this.levelUpInterval = 1000;
this.level = 1;
this.plane = new Plane(this);
this.bodies = [this.plane];
this.lives = 3;
this.keyState = {
32: false,
37: false,
38: false,
39: false,
40: false
};
this.levels = {
2: { enemyInterval: 250, enemyPatternReset: 750 },
3: { enemyInterval: 200, enemyPatternReset: 600 },
4: { enemyInterval: 150, enemyPatternReset: 450 },
5: { enemyInterval: 50, enemyPatternReset: 150 },
6: { enemyInterval: 40, enemyPatternReset: 120 }
};
this.enemyOptions = {
enemyTypes: ['basic', 'largePlane', 'basic', 'largePlane'],
positions: [[10, this.randomY()], [600, this.randomY()], [600, this.randomY()], [10, this.randomY()]],
flightPaths: ['square', 'vee', 'vee', 'straight']
}
};
Game.prototype.randomY = function() {
return Math.floor(Math.random() * (200 - 10 + 1)) + 10;
}
Game.prototype.draw = function() {
this.drawBackground();
this.drawScoreAndLives();
this.drawCurrentLevel();
this.bodies.forEach(function(body) { return body.draw(this.context) }, this);
return this;
};
Game.prototype.drawScoreAndLives = function() {
this.context.lineWidth = 1;
this.context.fillStyle = "#000000";
this.context.lineStyle = "#ffff00";
this.context.font = "20px sans-serif";
this.context.fillText("Score: " + this.currentScore.toString(), 10, 590);
this.context.fillText("Lives: " + this.lives.toString(), 515, 590)
}
Game.prototype.drawBackground = function() {
var background = new Image();
background.src = "./lib/images/cloud_background.jpg";
this.scrollBackground();
this.context.drawImage(background, 0, this.context.counter);
}
Game.prototype.drawCurrentLevel = function() {
this.context.fillText("Current Level: " + this.level.toString(), 238, 590)
}
Game.prototype.scrollBackground = function() {
this.context.counter++;
if (this.context.counter > 0) { this.context.counter = -this.canvas.height };
}
Game.prototype.move = function() {
this.createEnemiesOnInterval();
this.bodies.forEach(function(body) { return body.move() });
this.collideAndRemoveBodies();
};
Game.prototype.collideAndRemoveBodies = function() {
this.removeAnyCollidingBodies();
this.deleteBodyIfNotVisible();
}
Game.prototype.checkRemainingLives = function() {
var obj = this.bodies[0];
if (!Plane.prototype.isPrototypeOf(obj) && this.lives > 1 ) {
this.plane = new Plane(this);
this.bodies.unshift(this.plane);
this.lives--;
}
}
Game.prototype.createEnemiesOnInterval = function() {
this.enemyCreationCounter++;
if (this.enemyCreationCounter === this.enemyPatternReset){ this.enemyCreationCounter = this.enemyInterval };
if (this.enemyCreationCounter % this.enemyInterval === 0){ this.addEnemy() };
this.increaseLevelOverTime();
}
Game.prototype.increaseLevelOverTime = function() {
this.timeCounter++;
this.increaseLevelIfNecessary();
}
Game.prototype.increaseLevelIfNecessary = function() {
if (this.timeCounter % this.levelUpInterval === 0) {
if (this.level <= 5) { this.level++; };
this.enemyInterval = this.levels[this.level].enemyInterval;
this.enemyPatternReset = this.levels[this.level].enemyPatternReset;
}
}
Game.prototype.deleteBodyIfNotVisible = function() {
this.bodies = _.reject(this.bodies, function(body){
return (body.x > this.canvas.width) || (body.x < 0)
|| (body.y > this.canvas.height) || (body.y < 0);
}, this);
};
Game.prototype.drawPlane = function(context) {
var plane = new Image();
plane.src = "./lib/plane.jpg";
plane.height = 30;
plane.width = 30;
context.drawImage(plane, this.plane.x, this.plane.y);
return plane;
};
Game.prototype.removeAnyCollidingBodies = function() {
this.bodies = _.reject(this.bodies, function(body) {
var collision = this.isColliding(body);
if (collision && body.aircraft) { this.increaseScore(body.aircraft.type) };
return collision;
}, this);
return this;
}
Game.prototype.isColliding = function(body1) {
return this.bodies.filter(function(body2) {
return (this.collisionLogic(body1, body2)
&& this.notTwoEnemyBodies(body1, body2));
}, this).length;
}
Game.prototype.collisionLogic = function(body1, body2) {
return ((body1 !== body2)
&& (((body1.x + body1.width) >= body2.x)
&& ((body2.x + body2.width) >= body1.x))
&& ((body1.y + body1.height) >= body2.y)
&& ((body2.y + body2.height) >= body1.y));
}
Game.prototype.notTwoEnemyBodies = function(body1, body2) {
return !((body1.owner && Enemy.prototype.isPrototypeOf(body2))
|| (body2.owner && Enemy.prototype.isPrototypeOf(body1))
|| (Enemy.prototype.isPrototypeOf(body1)
&& Enemy.prototype.isPrototypeOf(body2)))
}
Game.prototype.addEnemy = function() {
var choice1 = this.getRandomEnemyChoice();
var choice2 = this.getRandomEnemyChoice();
var choice3 = this.getRandomEnemyChoice();
var startingPosition = this.enemyOptions.positions[choice1];
var aircraft = this.enemyOptions.enemyTypes[choice2];
var path = this.enemyOptions.flightPaths[choice3];
var enemy = new Enemy(this, startingPosition, aircraft, path);
this.bodies.push(enemy);
}
Game.prototype.getRandomEnemyChoice = function() {
return Math.floor(Math.random() * 4); //indices of this.enemyOptions
}
Game.prototype.increaseScore = function(enemyType) {
var pointValues = { basic: 100, largePlane: 300 }
this.currentScore += pointValues[enemyType];
}
Game.prototype.resetPlaneIfDeadAndLivesRemain = function(id, newGameButton) {
var obj = this.bodies[0];
if (!Plane.prototype.isPrototypeOf(obj)) {
window.cancelAnimationFrame(id);
setTimeout(function(){
this.canvas.style.display = 'none';
newGameButton.style.display = '' }.bind(this), 500);
}
}
module.exports = Game;
|
#!/usr/bin/env node
var loadConfig = require('../lib/config')
var backend = require('unpm-fs-backend')
var path = require('path')
var nopt = require('nopt')
var unpm = require('../')
var noptions = {
'port': Number,
'quiet': Boolean,
'log': String,
'logdir': String,
'datadir': String,
'fallback': String,
'configfile': String
}
var shorts = {
'p': ['--port'],
'q': ['--quiet'],
'l': ['--log'],
'L': ['--logdir'],
'd': ['--datadir'],
'F': ['--fallback'],
'c': ['--configfile']
}
var config = nopt(noptions, shorts)
if(config.logdir) {
config.logDir = config.logdir
}
if(config.quiet) {
config.verbose = false
}
var CWD = process.cwd()
var unpmService
var tarballsDir
var storeDir
var userDir
var metaDir
var dataDir
config = loadConfig(config || {})
dataDir = config.datadir ?
path.normalize(config.datadir) :
path.join(CWD, 'data')
if(!config.backend) {
tarballsDir = path.join(dataDir, 'tarballs')
userDir = path.join(dataDir, 'users')
metaDir = path.join(dataDir, 'meta')
storeDir = path.join(dataDir, 'store')
config.backend = backend(metaDir, userDir, tarballsDir, storeDir)
}
unpmService = unpm(config)
unpmService.server.listen(unpmService.config.host.port)
unpmService.log.info('Started unpm on port %s', unpmService.config.host.port)
|
import Expression from '../../Parse/Expression'
import LogicOperatorSet from '../../Parse/LogicOperatorSet'
import Rule from './Rule'
import ProofTree from '../ProofTree'
class ConjunctionIntroduction extends Rule {
applyRule(leftExpr, rightExpr) {
var operator = new Expression(LogicOperatorSet.AND);
operator.left = this.logicExpressionParser.parse(leftExpr);
operator.right = this.logicExpressionParser.parse(rightExpr);
return operator.toString();
}
conditions(state, endpoint, [line1, line2]) {
var endPointScope = state.line(endpoint);
console.log(endPointScope.inScope(line1), endPointScope.inScope(line2));
return endPointScope.inScope(line1)
&& (endPointScope.inScope(line2));
}
applyRuleToProof(proof, endpoint, lines) {
super.applyRuleToProof(proof, endpoint, lines);
var [line1, line2] = lines;
var line1 = proof.line(line1);
var line2 = proof.line(line2);
var equation = this.applyRule(line1.equation, line2.equation);
proof.line(endpoint).addLine(new ProofTree({
rule: this.toString(lines),
equation
}));
}
toString([line1, line2]) {
return `Conjunction Introduction ${line1}, ${line2} `;
}
}
export default new ConjunctionIntroduction();
|
var character = {
name: 'Barry Allen',
pseudonym: 'The Flash',
metadata: {
age: 27,
gender: 'male'
},
}
var { name } = character
console.log(name); |
/*jshint node:true, mocha:true*/
/**
* @author pmeijer / https://github.com/pmeijer
*/
var testFixture = require('../../_globals.js');
describe('Connected worker', function () {
'use strict';
var WebGME = testFixture.WebGME,
gmeConfig = testFixture.getGmeConfig(),
guestAccount = gmeConfig.authentication.guestAccount,
Q = testFixture.Q,
expect = testFixture.expect,
agent = testFixture.superagent.agent(),
openSocketIo = testFixture.openSocketIo,
webGMESessionId,
CONSTANTS = require('./../../../src/server/worker/constants'),
server,
gmeAuth,
logger = testFixture.logger.fork('connectedworker.spec'),
storage,
ir1,
ir2,
commitHashAfterMod,
oldSend = process.send,
oldOn = process.on,
oldExit = process.exit;
before(function (done) {
// We're not going through the server to start the connected-workers.
// Disableing should save some resources..
gmeConfig.addOn.enable = false;
gmeConfig.addOn.monitorTimeout = 10;
server = WebGME.standaloneServer(gmeConfig);
testFixture.clearDBAndGetGMEAuth(gmeConfig)
.then(function (gmeAuth_) {
gmeAuth = gmeAuth_;
storage = testFixture.getMongoStorage(logger, gmeConfig, gmeAuth);
return storage.openDatabase();
})
.then(function () {
return Q.allDone([
testFixture.importProject(storage,
{
projectSeed: 'seeds/EmptyProject.json',
projectName: 'ConnectedWorkerProject1',
branchName: 'master',
gmeConfig: gmeConfig,
logger: logger
}),
testFixture.importProject(storage,
{
projectSeed: 'seeds/EmptyProject.json',
projectName: 'Constraints',
branchName: 'master',
gmeConfig: gmeConfig,
logger: logger
})
]);
})
.then(function (results) {
ir1 = results[0];
ir2 = results[1];
return Q.allDone([
ir1.project.createBranch('b1', ir1.commitHash),
ir2.project.createBranch('b1', ir2.commitHash)
]);
})
.then(function () {
var persisted;
ir2.core.setRegistry(ir2.rootNode, 'usedAddOns', 'ConstraintAddOn');
persisted = ir2.core.persist(ir2.rootNode);
return ir2.project.makeCommit('b1', [ir2.commitHash], persisted.rootHash,
persisted.objects, 'Setting usedAddOns..');
})
.then(function (result) {
commitHashAfterMod = result.hash;
return Q.ninvoke(server, 'start');
})
.then(function () {
return openSocketIo(server, agent, guestAccount, guestAccount);
})
.then(function (result) {
webGMESessionId = result.webGMESessionId;
})
.nodeify(done);
});
after(function (done) {
server.stop(function (err) {
if (err) {
logger.error(err);
}
return Q.allDone([
storage.closeDatabase(),
gmeAuth.unload()
])
.nodeify(done);
});
});
function unloadConnectedWorker() {
// clear the cached files
var key,
i,
modulesToUnload = [];
for (key in require.cache) {
if (require.cache.hasOwnProperty(key)) {
if (key.indexOf('connectedworker.js') > -1) {
modulesToUnload.push(key);
}
}
}
for (i = 0; i < modulesToUnload.length; i += 1) {
delete require.cache[modulesToUnload[i]];
}
}
function getConnectedWorker() {
var worker,
deferredArray = [],
sendMessage;
function sendFunction() {
//console.log('sendFunction');
//console.log(arguments);
// got message
//console.log('got message: ', arguments); // FOR DEBUGGING
var deferred = deferredArray.shift();
if (deferred) {
if (arguments[0].error) {
// N.B: we use and care only about the error property and it is always a string if exists.
deferred.reject(new Error(arguments[0].error));
} else {
deferred.resolve(arguments[0]);
}
}
}
function onFunction() {
//console.log('onFunction');
//console.log(arguments);
if (arguments[0] === 'message') {
// save the send message function
sendMessage = arguments[1];
}
}
function exitFunction() {
//console.log('exitFunction');
//console.log(arguments);
}
process.send = sendFunction;
process.on = onFunction;
process.exit = exitFunction;
unloadConnectedWorker();
require('./../../../src/server/worker/connectedworker');
worker = {
send: function () {
// FIXME: this implementation assumes that the send/receive messages are in pair
// exactly one message received per sent message, in the same order.
var deferred = Q.defer();
deferredArray.push(deferred);
//console.log('sending message: ', arguments); // FOR DEBUGGING
sendMessage.apply(this, arguments);
return deferred.promise;
}
};
return worker;
}
function restoreProcessFunctions() {
process.send = oldSend;
process.on = oldOn;
process.exit = oldExit;
}
// Initialize
it('should initialize worker with a valid gmeConfig', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
})
.finally(restoreProcessFunctions)
.nodeify(done);
});
it('should respond with no error to a second initialization request', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig});
})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
})
.finally(restoreProcessFunctions)
.nodeify(done);
});
it('should fail to execute command without initialization', function (done) {
var worker = getConnectedWorker();
worker.send({
command: CONSTANTS.workerCommands.connectedWorkerStart
})
.then(function () {
done(new Error('missing error handling'));
})
.catch(function (err) {
expect(err.message).equal('worker has not been initialized yet');
})
.finally(restoreProcessFunctions)
.nodeify(done);
});
// Common behaviour
it('should be able to start-start-stop connectedWorker', function (done) {
var worker = getConnectedWorker(),
params = {
command: CONSTANTS.workerCommands.connectedWorkerStart,
webGMESessionId: webGMESessionId,
projectId: ir1.project.projectId,
branchName: 'master'
};
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send(Object.create(params));
})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.request);
expect(msg.error).equal(null);
return worker.send(Object.create(params));
})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.request);
expect(msg.error).equal(null);
return worker.send({
command: CONSTANTS.workerCommands.connectedWorkerStop,
webGMESessionId: webGMESessionId,
projectId: ir1.project.projectId,
branchName: 'master'
});
})
.then(function (msg) {
expect(msg.error).equal(null);
expect(msg.type).equal(CONSTANTS.msgTypes.request);
expect(msg.result.connectionCount).equal(-1);
})
.finally(restoreProcessFunctions)
.nodeify(done);
});
it('should be able to start-start-stop connectedWorker and start constraintAddOn', function (done) {
var worker = getConnectedWorker(),
params = {
command: CONSTANTS.workerCommands.connectedWorkerStart,
webGMESessionId: webGMESessionId,
projectId: ir2.project.projectId,
branchName: 'b1'
};
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send(Object.create(params));
})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.request);
expect(msg.error).equal(null);
return worker.send(Object.create(params));
})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.request);
expect(msg.error).equal(null);
function delayedBranchHash() {
var deferred = Q.defer();
setTimeout(function () {
deferred.promise = ir2.project.getBranchHash('b1')
.then(deferred.resolve)
.catch(deferred.reject);
}, 1000);
return deferred.promise;
}
return delayedBranchHash();
})
.then(function (hash) {
expect(hash).to.not.equal(ir2.commitHash);
expect(hash).to.not.equal(commitHashAfterMod);
return testFixture.loadRootNodeFromCommit(ir2.project, ir2.core, hash);
})
.then(function (newRoot) {
var stopParams = Object.create(params);
expect(ir2.core.getAttribute(newRoot, 'name')).to.equal('No Violations');
stopParams.command = CONSTANTS.workerCommands.connectedWorkerStop;
return worker.send(stopParams);
})
.then(function (msg) {
expect(msg.error).equal(null);
expect(msg.type).equal(CONSTANTS.msgTypes.request);
expect(msg.result.connectionCount).equal(-1);
})
.finally(restoreProcessFunctions)
.nodeify(done);
});
it('should connectedWorkerStop with no running AddOnManager for project', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({
command: CONSTANTS.workerCommands.connectedWorkerStop,
webGMESessionId: webGMESessionId,
projectId: ir1.project.projectId,
branchName: 'master'
});
})
.then(function (msg) {
expect(msg.error).to.equal(null);
expect(msg.result.connectionCount).to.equal(-1);
})
.finally(restoreProcessFunctions)
.nodeify(done);
});
// Invalid parameters
it('should fail to startConnectedWorker with invalid parameters', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({
command: CONSTANTS.workerCommands.connectedWorkerStart,
webGMESessionId: webGMESessionId,
projectId: ir1.project.projectId
});
})
.then(function (/*msg*/) {
done(new Error('Missing error handling'));
})
.catch(function (err) {
expect(err.message).to.contain('parameter');
done();
})
.finally(restoreProcessFunctions)
.done();
});
it('should fail to startConnectedWorker with invalid parameters 2', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({
command: CONSTANTS.workerCommands.connectedWorkerStart,
webGMESessionId: webGMESessionId,
branchName: 'master'
});
})
.then(function (/*msg*/) {
done(new Error('Missing error handling'));
})
.catch(function (err) {
expect(err.message).to.contain('parameter');
done();
})
.finally(restoreProcessFunctions)
.done();
});
it('should fail to stopConnectedWorker with invalid parameters', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({
command: CONSTANTS.workerCommands.connectedWorkerStop,
webGMESessionId: webGMESessionId,
projectId: ir1.project.projectId
});
})
.then(function (/*msg*/) {
done(new Error('Missing error handling'));
})
.catch(function (err) {
expect(err.message).to.contain('parameter');
done();
})
.finally(restoreProcessFunctions)
.done();
});
it('should fail to stopConnectedWorker with invalid parameters 2', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({
command: CONSTANTS.workerCommands.connectedWorkerStop,
webGMESessionId: webGMESessionId,
branchName: 'master'
});
})
.then(function (/*msg*/) {
done(new Error('Missing error handling'));
})
.catch(function (err) {
expect(err.message).to.contain('parameter');
done();
})
.finally(restoreProcessFunctions)
.done();
});
// wrong / no command
it('should fail to execute wrong command', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({
command: 'unknown command'
});
})
.then(function (/*msg*/) {
done(new Error('missing error handling'));
})
.catch(function (err) {
expect(err.message).to.contain('unknown command');
done();
})
.finally(restoreProcessFunctions)
.done();
});
it('should fail to execute request without command', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({});
})
.then(function (/*msg*/) {
done(new Error('missing error handling'));
})
.catch(function (err) {
expect(err.message).to.contain('unknown command');
done();
})
.finally(restoreProcessFunctions)
.done();
});
// Failing cases
it('should fail with error startConnectedWorker with non-existing project', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({
command: CONSTANTS.workerCommands.connectedWorkerStart,
webGMESessionId: webGMESessionId,
projectId: 'DoesNotExist',
branchName: 'master'
});
})
.then(function (/*msg*/) {
done(new Error('Missing error handling'));
})
.catch(function (err) {
expect(err.message).to.contain('Not authorized to read project: DoesNotExist');
done();
})
.finally(restoreProcessFunctions)
.done();
});
it('should fail with error startConnectedWorker with non-existing branch', function (done) {
var worker = getConnectedWorker();
worker.send({command: CONSTANTS.workerCommands.initialize, gmeConfig: gmeConfig})
.then(function (msg) {
expect(msg.pid).equal(process.pid);
expect(msg.type).equal(CONSTANTS.msgTypes.initialized);
return worker.send({
command: CONSTANTS.workerCommands.connectedWorkerStart,
webGMESessionId: webGMESessionId,
projectId: ir1.project.projectId,
branchName: 'branchDoesNotExist'
});
})
.then(function (/*msg*/) {
done(new Error('Missing error handling'));
})
.catch(function (err) {
expect(err.message).to.contain('Branch "branchDoesNotExist" does not exist');
done();
})
.finally(restoreProcessFunctions)
.done();
});
}); |
problem04([ { kingdom: "Maiden Way", general: "Merek", army: 5000 },
{ kingdom: "Stonegate", general: "Ulric", army: 4900 },
{ kingdom: "Stonegate", general: "Doran", army: 70000 },
{ kingdom: "YorkenShire", general: "Quinn", army: 0 },
{ kingdom: "YorkenShire", general: "Quinn", army: 2000 },
{ kingdom: "Maiden Way", general: "Berinon", army: 100000 } ],
[ ["YorkenShire", "Quinn", "Stonegate", "Ulric"],
["Stonegate", "Ulric", "Stonegate", "Doran"],
["Stonegate", "Doran", "Maiden Way", "Merek"],
["Stonegate", "Ulric", "Maiden Way", "Merek"],
["Maiden Way", "Berinon", "Stonegate", "Ulric"] ]);
function problem04(data, attacks) {
let generals = {};
let kingdoms = {};
for (let e of data) {
if (kingdoms.hasOwnProperty(e['kingdom'])) {
if (kingdoms[e['kingdom']].hasOwnProperty(e['general'])) {
kingdoms[e['kingdom']][e['general']]['army'] += Number(e['army']);
} else {
kingdoms[e['kingdom']][e['general']] = {army: Number(e['army']), wins: 0, losses: 0};
}
} else {
kingdoms[e['kingdom']] = {};
kingdoms[e['kingdom']][e['general']] = {army: Number(e['army']), wins: 0, losses: 0};
kingdoms[e['kingdom']]['totalWins'] = 0;
kingdoms[e['kingdom']]['totalLosses'] = 0;
}
}
for (let a of attacks) {
let[attackingKingdom, attackingGeneral, defendingKingdom, defendingGeneral] = a;
if (attackingKingdom == defendingKingdom) {
continue;
}
let res = kingdoms[attackingKingdom][attackingGeneral]['army'] - kingdoms[defendingKingdom][defendingGeneral]['army'];
if (res > 0) {
kingdoms[defendingKingdom][defendingGeneral]['army'] = Math.floor(kingdoms[defendingKingdom][defendingGeneral]['army'] * 0.9);
kingdoms[attackingKingdom][attackingGeneral]['army'] = Math.floor(kingdoms[attackingKingdom][attackingGeneral]['army'] * 1.1);
kingdoms[defendingKingdom][defendingGeneral]['losses']++;
kingdoms[attackingKingdom][attackingGeneral]['wins']++;
kingdoms[defendingKingdom]['totalLosses']++;
kingdoms[attackingKingdom]['totalWins']++
} else if (res < 0) {
kingdoms[attackingKingdom][attackingGeneral]['army'] = Math.floor(kingdoms[attackingKingdom][attackingGeneral]['army'] * 0.9);
kingdoms[defendingKingdom][defendingGeneral]['army'] = Math.floor(kingdoms[defendingKingdom][defendingGeneral]['army'] * 1.1);
kingdoms[attackingKingdom][attackingGeneral]['losses']++;
kingdoms[defendingKingdom][defendingGeneral]['wins']++;
kingdoms[attackingKingdom]['totalLosses']++;
kingdoms[defendingKingdom]['totalWins']++
}
}
let winner = Object.keys(kingdoms).sort((a, b) => {
let res = kingdoms[b]['totalWins'] - kingdoms[a]['totalWins'];
if (res == 0) {
res = kingdoms[a]['totalLosses'] - kingdoms[b]['totalLosses'];
}
if (res == 0) {
res = a.localeCompare(b);
}
return res;
})[0];
console.log('Winner: ' + winner);
delete kingdoms[winner]['totalLosses'];
delete kingdoms[winner]['totalWins'];
let sortedGenerals = Object.keys(kingdoms[winner]).sort((a, b) => {
let res = kingdoms[winner][b]['army'] - kingdoms[winner][a]['army'];
return res;
});
for (let g of sortedGenerals) {
console.log('/\\general: ' + g);
console.log('---army: ' + kingdoms[winner][g]['army']);
console.log('---wins: ' + kingdoms[winner][g]['wins']);
console.log('---losses: ' + kingdoms[winner][g]['losses']);
}
}
|
const moment = require('moment-timezone');
module.exports = {
/**
* Adds timezone codes to a all properties for each feature in the feature collection.
*
* @param {object[]} features An array of GeoJson features.
* @param {number} lng The longtitude to append to the response.
* @param {number} lat The latitude to append to the response.
* @returns {object} A collection of object literals with renamed properties.
*/
propertiesMapper: (features, lng, lat) =>
features.map((feature) => {
const tz = moment().tz(feature.properties.tzid);
return {
code: tz.zoneAbbr(),
offset: tz.format('Z'),
offset_seconds: tz.utcOffset() * 60,
coords: [
parseFloat(lng),
parseFloat(lat),
],
timezone: feature.properties.tzid,
iso: tz.toISOString(),
iso_day_of_week: tz.isoWeekday(),
iso_week_of_year: tz.isoWeek(),
day_of_year: tz.dayOfYear(),
week_of_year: tz.week(),
month_of_year: tz.month(),
year: tz.year(),
dst: tz.isDST(),
leap: tz.isLeapYear(),
};
}),
};
|
'use strict'
const {INTEGER, STRING} = require('sequelize')
module.exports = db => db.define('directors', {
id: {
type: INTEGER,
allowNull: false,
defaultValue: '0',
primaryKey: true,
},
first_name: {
type: STRING,
defaultValue: null,
},
last_name: {
type: STRING,
defaultValue: null,
},
})
module.exports.associations = (Director, {Movie_director, Movie}) => {
Director.belongsToMany(Movie, {as: 'movies', through: Movie_director})
}
|
/*jshint esversion:6, node:true*/
'use strict';
const { addJSONSerializer } = require('./serializer');
module.exports.init = function(app, config) {
//TODO: Integrate signals here!
/**
* We want to be able to serialize Error instances
* using our regular JSON class.
*/
if (!('toJSON' in Error.prototype)) {
addJSONSerializer(app.isProduction);
}
/*
* Cath all uncaught exceptions, log it and exit
* anyways.
*/
process.on('uncaughtexception', handleError.bind(null, 'uncaughtexception'));
process.on('rejectionHandled', handleError.bind(null, 'rejectionHandled'));
process.on('unhandledRejection', handleError.bind(null, 'unhandledRejection'));
process.on('exit', cleanup.bind(null, 'exit', 0));
process.on('SIGINT', cleanup.bind(null, 'SIGINT', 0));
process.on('SIGTERM', cleanup.bind(null, 'SIGTERM', 0));
/*
* TODO: We could provide better error messages
* when possible.
*
* Error:
* TypeError: Cannot assign to read only property '<moduleid>' of object '#<Application>'
* Message:
* The application context already has a property named "<moduleid>".
* If you are trying to overwrite it, then use the `context.provide`
* function instead of a direct assignment.
*/
function handleError(label, err) {
if (arguments.length === 1) {
err = label;
label = 'Unkown';
}
app.logger.error('We catched an unhandled error: <%s>', label);
app.logger.error(err);
cleanup('ERROR', 1);
}
app.resolve('monitoring').then(function(monitoring) {
monitoring.signals.on('shutdown', function(event) {
cleanup(event.signal, event.data && isNaN(event.data) ? 1 : event.data);
});
});
function cleanup(label, code) {
if (cleanup.visited) return;
cleanup.visited = true;
//TODO: This should be namespaced! coreio.closing
app.emit('closing', {
code,
label
});
/*
* Here we stll might have 10 seconds to go, or whatever
* is Serene's timeout value.
*/
Promise.resolve(app.close(code, label)).then(function() {
app.logger.warn('\nCLEANUP reason : %s code: %s', label, code);
/*
* For now, we are ignoring the code, since
* exit(0) ensures that our app gets restarted
* by docker.
*/
process.exit(0);
});
}
return handleError;
};
|
var Post = AV.Object.extend('Post');
describe('Geopoints', () => {
before(function() {
// Make a new post
const user = AV.User.current();
const post = new Post();
post.set('title', 'Post Geopoints');
post.set('body', ' Geopoints content.');
post.set('user', user);
this.post = post;
});
it('save object with geopoints', function() {
const point = new AV.GeoPoint({ latitude: 40.0, longitude: -30.0 });
this.post.set('location', point);
return this.post.save();
});
it('near', function() {
const postGeoPoint = this.post.get('location');
// Create a query for places
const query = new AV.Query(Post);
// Interested in locations near user.
query.near('location', postGeoPoint);
// Limit what could be a lot of points.
query.limit(10);
// Final list of objects
return query.find();
});
});
|
var express = require('express');
var router = express.Router();
/* GET webhook page. */
app.get('/', function(req, res) {
if (req.query['hub.mode'] === 'subscribe' &&
req.query['hub.verify_token'] === config.validationToken) {
console.log("Validating webhook");
console.log(JSON.stringify(req.query))
res.status(200).send(req.query['hub.challenge']);
} else {
console.error("Failed validation. Make sure the validation tokens match.");
res.sendStatus(403);
}
});
module.exports = router;
|
// flow-typed signature: 9d467e619bc6f66a4317af7a17507e64
// flow-typed version: <<STUB>>/storybook-host_v3.0.0/flow_v0.48.0
/**
* This is an autogenerated libdef stub for:
*
* 'storybook-host'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'storybook-host' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'storybook-host/lib/common/alignment' {
declare module.exports: any;
}
declare module 'storybook-host/lib/common/color' {
declare module.exports: any;
}
declare module 'storybook-host/lib/common/css' {
declare module.exports: any;
}
declare module 'storybook-host/lib/common/index' {
declare module.exports: any;
}
declare module 'storybook-host/lib/common/util' {
declare module.exports: any;
}
declare module 'storybook-host/lib/components/AlignmentContainer' {
declare module.exports: any;
}
declare module 'storybook-host/lib/components/ComponentHost' {
declare module.exports: any;
}
declare module 'storybook-host/lib/components/ComponentHost.stories' {
declare module.exports: any;
}
declare module 'storybook-host/lib/components/CropMark' {
declare module.exports: any;
}
declare module 'storybook-host/lib/components/CropMarks' {
declare module.exports: any;
}
declare module 'storybook-host/lib/decorators/host' {
declare module.exports: any;
}
declare module 'storybook-host/lib/index' {
declare module.exports: any;
}
declare module 'storybook-host/lib/index.test' {
declare module.exports: any;
}
declare module 'storybook-host/lib/types' {
declare module.exports: any;
}
// Filename aliases
declare module 'storybook-host/lib/common/alignment.js' {
declare module.exports: $Exports<'storybook-host/lib/common/alignment'>;
}
declare module 'storybook-host/lib/common/color.js' {
declare module.exports: $Exports<'storybook-host/lib/common/color'>;
}
declare module 'storybook-host/lib/common/css.js' {
declare module.exports: $Exports<'storybook-host/lib/common/css'>;
}
declare module 'storybook-host/lib/common/index.js' {
declare module.exports: $Exports<'storybook-host/lib/common/index'>;
}
declare module 'storybook-host/lib/common/util.js' {
declare module.exports: $Exports<'storybook-host/lib/common/util'>;
}
declare module 'storybook-host/lib/components/AlignmentContainer.js' {
declare module.exports: $Exports<'storybook-host/lib/components/AlignmentContainer'>;
}
declare module 'storybook-host/lib/components/ComponentHost.js' {
declare module.exports: $Exports<'storybook-host/lib/components/ComponentHost'>;
}
declare module 'storybook-host/lib/components/ComponentHost.stories.js' {
declare module.exports: $Exports<'storybook-host/lib/components/ComponentHost.stories'>;
}
declare module 'storybook-host/lib/components/CropMark.js' {
declare module.exports: $Exports<'storybook-host/lib/components/CropMark'>;
}
declare module 'storybook-host/lib/components/CropMarks.js' {
declare module.exports: $Exports<'storybook-host/lib/components/CropMarks'>;
}
declare module 'storybook-host/lib/decorators/host.js' {
declare module.exports: $Exports<'storybook-host/lib/decorators/host'>;
}
declare module 'storybook-host/lib/index.js' {
declare module.exports: $Exports<'storybook-host/lib/index'>;
}
declare module 'storybook-host/lib/index.test.js' {
declare module.exports: $Exports<'storybook-host/lib/index.test'>;
}
declare module 'storybook-host/lib/types.js' {
declare module.exports: $Exports<'storybook-host/lib/types'>;
}
|
'use strict';
var worker = require('../lib/co-work.js'),
Q = require('q'),
argsArray = [
'foo',
'bar',
'baz',
'qux',
'quux',
'garply',
'waldo',
'fred',
'plugh',
'xyzzy',
'thud'
];
// Run no more than three concurrently
worker.work(3, function(param1) {
var deferred = Q.defer(),
promise = deferred.promise;
setTimeout(function() {
console.log(param1 + ': This command is running asynchronously');
deferred.resolve(param1);
}, 1);
promise.then(function(result) {
console.log(result + ': has finished');
});
return promise;
}, argsArray, function() {
console.log('Callback at the end');
}); |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global', './ListItemBaseRenderer', 'sap/ui/core/Renderer'],
function(jQuery, ListItemBaseRenderer, Renderer) {
"use strict";
/**
* ObjectListItem renderer.
* @namespace
*/
var ObjectListItemRenderer = Renderer.extend(ListItemBaseRenderer);
/**
* Renders the HTML for single line of Attribute and Status.
*
* @param {sap.ui.core.RenderManager}
* rm the RenderManager that can be used for writing to the render output buffer
* @param {sap.m.ObjectListItem}
* oLI an object to be rendered
* @param {sap.m.ObjectAttribute}
* oAttribute an attribute to be rendered
* @param {sap.m.ObjectStatus}
* oStatus a status to be rendered
*/
ObjectListItemRenderer.renderAttributeStatus = function(rm, oLI, oAttribute, oStatus) {
if (!oAttribute && !oStatus || (oAttribute && oAttribute._isEmpty() && oStatus && oStatus._isEmpty())) {
return; // nothing to render
}
rm.write("<div"); // Start attribute row container
rm.addClass("sapMObjLAttrRow");
rm.writeClasses();
rm.write(">");
if (oAttribute && !oAttribute._isEmpty()) {
rm.write("<div");
rm.addClass("sapMObjLAttrDiv");
// Add padding to push attribute text down since it will be raised up due
// to markers height
if (oStatus && (!oStatus._isEmpty())) {
if (oStatus instanceof Array) {
rm.addClass("sapMObjAttrWithMarker");
}
}
rm.writeClasses();
if (!oStatus || oStatus._isEmpty()) {
rm.addStyle("width", "100%");
rm.writeStyles();
}
rm.write(">");
rm.renderControl(oAttribute);
rm.write("</div>");
}
if (oStatus && (!oStatus._isEmpty())) {
rm.write("<div");
rm.addClass("sapMObjLStatusDiv");
// Object marker icons (flag, favorite) are passed as an array
if (oStatus instanceof Array) {
rm.addClass("sapMObjStatusMarker");
}
rm.writeClasses();
if (!oAttribute || oAttribute._isEmpty()) {
rm.addStyle("width", "100%");
rm.writeStyles();
}
rm.write(">");
if (oStatus instanceof Array) {
while (oStatus.length > 0) {
rm.renderControl(oStatus.shift());
}
} else {
rm.renderControl(oStatus);
}
rm.write("</div>");
}
rm.write("</div>"); // Start attribute row container
};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager}
* oRenderManager the RenderManager that can be used for writing to the
* Render-Output-Buffer
* @param {sap.ui.core.Control}
* oControl an object representation of the control that should be
* rendered
*/
ObjectListItemRenderer.renderLIAttributes = function(rm, oLI) {
rm.addClass("sapMObjLItem");
rm.addClass("sapMObjLListModeDiv");
};
ObjectListItemRenderer.renderLIContent = function(rm, oLI) {
var sTitleDir = oLI.getTitleTextDirection(),
sIntroDir = oLI.getIntroTextDirection(),
sNumberDir = oLI.getNumberTextDirection();
// Introductory text at the top of the item, like "On behalf of Julie..."
if (oLI.getIntro()) {
rm.write("<div");
rm.addClass("sapMObjLIntro");
rm.writeClasses();
rm.writeAttribute("id", oLI.getId() + "-intro");
rm.write(">");
rm.write("<span");
//sets the dir attribute to "rtl" or "ltr" if a direction
//for the intro text is provided explicitly
if (sIntroDir !== sap.ui.core.TextDirection.Inherit) {
rm.writeAttribute("dir", sIntroDir.toLowerCase());
}
rm.write(">");
rm.writeEscaped(oLI.getIntro());
rm.write("</span>");
rm.write("</div>");
}
// Container for fields placed on the top half of the item, below the intro. This
// includes title, number, and number units.
rm.write("<div"); // Start Top row container
rm.addClass("sapMObjLTopRow");
rm.writeClasses();
rm.write(">");
if (!!oLI.getIcon()) {
rm.write("<div");
rm.addClass("sapMObjLIconDiv");
rm.writeClasses();
rm.write(">");
rm.renderControl(oLI._getImageControl());
rm.write("</div>");
}
// Container for a number and a units qualifier.
rm.write("<div"); // Start Number/units container
rm.addClass("sapMObjLNumberDiv");
rm.writeClasses();
rm.write(">");
if (oLI.getNumber()) {
rm.write("<div");
rm.writeAttribute("id", oLI.getId() + "-number");
rm.addClass("sapMObjLNumber");
rm.addClass("sapMObjLNumberState" + oLI.getNumberState());
rm.writeClasses();
//sets the dir attribute to "rtl" or "ltr" if a direction
//for the number text is provided explicitly
if (sNumberDir !== sap.ui.core.TextDirection.Inherit) {
rm.writeAttribute("dir", sNumberDir.toLowerCase());
}
rm.write(">");
rm.writeEscaped(oLI.getNumber());
rm.write("</div>");
if (oLI.getNumberUnit()) {
rm.write("<div");
rm.writeAttribute("id", oLI.getId() + "-numberUnit");
rm.addClass("sapMObjLNumberUnit");
rm.addClass("sapMObjLNumberState" + oLI.getNumberState());
rm.writeClasses();
rm.write(">");
rm.writeEscaped(oLI.getNumberUnit());
rm.write("</div>");
}
}
rm.write("</div>"); // End Number/units container
// Title container displayed to the left of the number and number units container.
rm.write("<div"); // Start Title container
rm.addStyle("display","-webkit-box");
rm.addStyle("overflow","hidden");
rm.writeStyles();
rm.write(">");
var oTitleText = oLI._getTitleText();
if (oTitleText) {
//sets the text direction of the title,
//by delegating the RTL support to sap.m.Text
oTitleText.setTextDirection(sTitleDir);
oTitleText.setText(oLI.getTitle());
oTitleText.addStyleClass("sapMObjLTitle");
rm.renderControl(oTitleText);
}
rm.write("</div>"); // End Title container
rm.write("</div>"); // End Top row container
if (!(sap.ui.Device.browser.internet_explorer && sap.ui.Device.browser.version < 10)) {
rm.write("<div style=\"clear: both;\"></div>");
}
// Bottom row container.
if (oLI._hasBottomContent()) {
rm.write("<div"); // Start Bottom row container
rm.addClass("sapMObjLBottomRow");
rm.writeClasses();
rm.write(">");
var aAttribs = oLI._getVisibleAttributes();
var statuses = [];
var markers = null;
if (oLI.getShowMarkers() || oLI.getMarkLocked()) {
var placeholderIcon = oLI._getPlaceholderIcon();
markers = [placeholderIcon];
markers._isEmpty = function() {
return false;
};
if (oLI.getMarkLocked()) {
var lockIcon = oLI._getLockIcon();
lockIcon.setVisible(oLI.getMarkLocked());
markers.push(lockIcon);
}
if (oLI.getShowMarkers()) {
var favIcon = oLI._getFavoriteIcon();
var flagIcon = oLI._getFlagIcon();
favIcon.setVisible(oLI.getMarkFavorite());
flagIcon.setVisible(oLI.getMarkFlagged());
markers.push(favIcon);
markers.push(flagIcon);
}
statuses.push(markers);
}
statuses.push(oLI.getFirstStatus());
statuses.push(oLI.getSecondStatus());
while (aAttribs.length > 0) {
this.renderAttributeStatus(rm, oLI, aAttribs.shift(), statuses.shift());
}
while (statuses.length > 0) {
this.renderAttributeStatus(rm, oLI, null, statuses.shift());
}
rm.write("</div>"); // End Bottom row container
}
// ARIA description node
this.renderAriaNode(rm, oLI, this.getAriaNodeText(oLI));
};
/**
* Renders hidden ARIA node, additionally describing the ObjectListItem, if description text is provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager}
* rm the RenderManager that can be used for writing to the
* Render-Output-Buffer
* @param {sap.m.ObjectListItem}
* oLI an object to be rendered
* @param {String}
* sAriaNodeText the ARIA node description text
*/
ObjectListItemRenderer.renderAriaNode = function(rm, oLI, sAriaNodeText) {
if (sAriaNodeText) {
rm.write("<div");
rm.writeAttribute("id", oLI.getId() + "-aria");
rm.writeAttribute("aria-hidden", "true");
rm.addClass("sapUiHidden");
rm.writeClasses();
rm.write(">");
rm.writeEscaped(sAriaNodeText);
rm.write("</div>");
}
};
/**
* Returns ARIA node description text for flag, favorite and lock marks
*
* @param {sap.m.ObjectListItem}
* oLI an object to be rendered
* @returns {String}
*/
ObjectListItemRenderer.getAriaNodeText = function(oLI) {
var aAriaNodeText = [];
var oLibraryResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m");
if (oLI.getMarkFlagged()) {
aAriaNodeText.push(oLibraryResourceBundle.getText("ARIA_FLAG_MARK_VALUE"));
}
if (oLI.getMarkFavorite()) {
aAriaNodeText.push(oLibraryResourceBundle.getText("ARIA_FAVORITE_MARK_VALUE"));
}
if (oLI.getMarkLocked()) {
aAriaNodeText.push(oLibraryResourceBundle.getText("OBJECTLISTITEM_ARIA_LOCKED_MARK_VALUE"));
}
return aAriaNodeText.join(" ");
};
/**
* Returns ObjectListItem`s inner nodes ids, later used in aria labelledby attribute
*
* @param {sap.m.ObjectListItem}
* oLI an object representation of the control
* @returns {String}
*/
ObjectListItemRenderer.getAriaLabelledBy = function(oLI) {
var aLabelledByIds = [];
if (oLI.getIntro()) {
aLabelledByIds.push(oLI.getId() + "-intro");
}
if (oLI.getTitle()) {
aLabelledByIds.push(oLI.getId() + "-titleText");
}
if (oLI.getNumber()) {
aLabelledByIds.push(oLI.getId() + "-number");
}
if (oLI.getNumberUnit()) {
aLabelledByIds.push(oLI.getId() + "-numberUnit");
}
if (oLI.getAttributes()) {
oLI.getAttributes().forEach(function(attribute) {
aLabelledByIds.push(attribute.getId());
});
}
if (oLI.getFirstStatus()) {
aLabelledByIds.push(oLI.getFirstStatus().getId());
}
if (oLI.getSecondStatus()) {
aLabelledByIds.push(oLI.getSecondStatus().getId());
}
if (this.getAriaNodeText(oLI)) {
aLabelledByIds.push(oLI.getId() + "-aria");
}
return aLabelledByIds.join(" ");
};
return ObjectListItemRenderer;
}, /* bExport= */ true);
|
'use strict';
const Command = require('../command');
const tkVarManager = require('../../lib/tk-var-manager');
class InputNumber extends Command {
run(receive, digit) {
this.writeLog(`receive: ${receive}, digit: ${digit}`);
return true;
}
output(receive, digit) {
if (typeof receive == 'string') {
const number = tkVarManager.getVarNumber(receive);
receive = number;
}
return [`ValueEntry(${digit}, ${receive})`];
}
get JP_NAME() {
return '数値入力の処理';
}
}
module.exports = InputNumber;
|
function createContact() {
var myContact = navigator.contacts.create({"displayName": "Cordova User"});
myContact.save();
alert('New contact saved');
}
function pickContact() {
navigator.contacts.pickContact(function(contact){
alert('The following contact has been selected:' + JSON.stringify(contact));
},function(err){
alert('Error: ' + err);
});
}
function findContact() {
var options = new ContactFindOptions();
options.filter = "Deni";
options.multiple = true;
options.desiredFields = [navigator.contacts.fieldType.id];
options.hasPhoneNumber = true;
var fields = [navigator.contacts.fieldType.displayName, navigator.contacts.fieldType.name];
navigator.contacts.find(fields, onSuccess, onError, options);
function onSuccess(contacts) {
alert('Found ' + contacts.length + ' contacts.');
}
function onError(contactError) {
alert('onError!');
}
} |
'use strict';
/*jshint globalstrict: true */
/*jshint undef:false */
/*jshint camelcase:false */
module.exports = function(grunt) {
var plugins = ['sortable', 'movable', 'drawtask', 'tooltips', 'bounds', 'progress'];
var coverage = grunt.option('coverage');
var sources = {
js: {
core:['src/core/*.js', 'src/core/**/*.js', '.tmp/generated/core/**/*.js'],
plugins: ['src/plugins/*.js', 'src/plugins/**/*.js', '.tmp/generated/plugins/**/*.js']
},
css: {
core: ['src/core/*.css', 'src/core/**/*.css'],
plugins: ['src/plugins/*.css', 'src/plugins/**/*.css']
}
};
var config = {
pkg: grunt.file.readJSON('package.json'),
html2js: {
options: {
quoteChar: '\'',
indentString: ' ',
module: 'gantt.templates',
singleModule: true
},
core: {
src: ['src/template/**/*.html'],
dest: '.tmp/generated/core/html2js.js'
}
},
concat: {
options: {
separator: '\n',
sourceMap: true,
banner: '/*\n' +
'Project: <%= pkg.name %> v<%= pkg.version %> - <%= pkg.description %>\n' +
'Authors: <%= pkg.author %>, <%= pkg.contributors %>\n' +
'License: <%= pkg.license %>\n' +
'Homepage: <%= pkg.homepage %>\n' +
'Github: <%= pkg.repository.url %>\n' +
'*/\n'
},
core: {
src: sources.js.core,
dest: 'assets/<%= pkg.name %>.js'
},
plugins: {
src: sources.js.plugins,
dest: 'assets/<%= pkg.name %>-plugins.js'
}
},
concatCss: {
core: {
src: sources.css.core,
dest: 'assets/<%= pkg.name %>.css'
},
plugins: {
src: sources.css.plugins,
dest: 'assets/<%= pkg.name %>-plugins.css'
}
},
cleanempty: {
options: {},
assets: 'assets/**/*'
},
uglify: {
options: {
banner: '/*\n' +
'Project: <%= pkg.name %> v<%= pkg.version %> - <%= pkg.description %>\n' +
'Authors: <%= pkg.author %>, <%= pkg.contributors %>\n' +
'License: <%= pkg.license %>\n' +
'Homepage: <%= pkg.homepage %>\n' +
'Github: <%= pkg.repository.url %>\n' +
'*/\n',
sourceMap: true
},
core: {
files: {
'dist/<%= pkg.name %>.min.js': sources.js.core
}
},
plugins: {
files: {
'dist/<%= pkg.name %>-plugins.min.js': sources.js.plugins
}
}
},
cssmin: {
core: {
src: sources.css.core,
dest: 'dist/<%= pkg.name %>.min.css'
},
plugins: {
src: sources.css.plugins,
dest: 'dist/<%= pkg.name %>-plugins.min.css'
}
},
copy: {
assetsToDist: {
files: [
// includes files within path
{expand: true, cwd: 'assets/', src: ['**'], dest: 'dist/'},
]
}
},
jshint: {
src: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
src: ['Gruntfile.js', 'src/**/*.js']
},
test: {
options: {
jshintrc: 'test/spec/.jshintrc'
},
src: ['test/spec/**/*.js']
}
},
watch: {
files: [].concat(sources.js.core, sources.js.plugins, ['src/**/*.html']),
tasks: ['build']
},
karma: {
unit: {
configFile: coverage ? 'test/karma-coverage.conf.js' : 'test/karma.conf.js',
singleRun: true
}
},
coveralls: {
options: {
force: true,
coverageDir: 'coverage-results',
recursive: true
}
},
connect: {
options: {
port: 9101,
hostname: '0.0.0.0',
keepalive: true,
livereload: 39729
},
plunker: {
options: {
open: true,
middleware: function(connect) {
return [
connect().use(
'/bower_components', connect.static('./bower_components')
),
connect().use(
'/assets', connect.static('./assets')
),
connect().use(
'/dist', connect.static('./dist')
),
connect.static('plunker')
];
}
}
}
}
};
for (var i = 0; i < plugins.length; i++) {
var plugin = plugins[i];
config.html2js[plugin] = {
module: 'gantt.' + plugin + '.templates',
src: ['src/plugins/' + plugin + '/**/*.html'],
dest: '.tmp/generated/plugins/' + plugin + '/html2js.js'
};
config.concat[plugin] = {
src: ['src/plugins/' + plugin + '.js', 'src/plugins/' + plugin + '/**/*.js'],
dest: 'assets/<%= pkg.name %>-' + plugin + '-plugin.js'
};
config.concatCss[plugin] = {
src: ['src/plugins/' + plugin + '.css', 'src/plugins/' + plugin + '/**/*.css'],
dest: 'assets/<%= pkg.name %>-' + plugin + '-plugin.css'
};
config.cssmin[plugin] = {
src: ['src/plugins/' + plugin + '.css', 'src/plugins/' + plugin + '/**/*.css'],
dest: 'dist/<%= pkg.name %>-' + plugin + '-plugin.min.css'
};
var uglifyFiles = {};
uglifyFiles['dist/<%= pkg.name %>-' + plugin + '-plugin.min.js'] = config.concat[plugin].src;
config.uglify[plugin] = {files: uglifyFiles};
}
grunt.initConfig(config);
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-cleanempty');
grunt.loadNpmTasks('grunt-html2js');
grunt.loadNpmTasks('grunt-karma');
// I can't find any other method to call concat 2 times with distinct options.
// See https://github.com/gruntjs/grunt-contrib-concat/issues/113
// Start of ugliness
grunt.renameTask('concat', 'concatCss');
grunt.loadNpmTasks('grunt-contrib-concat');
// End of ugliness
grunt.loadNpmTasks('grunt-karma-coveralls');
grunt.registerTask('test', ['karma']);
grunt.registerTask('build', ['html2js', 'jshint', 'concat', 'concatCss', 'cleanempty']);
grunt.registerTask('dist', ['build', 'copy:assetsToDist', 'uglify', 'cssmin']);
grunt.registerTask('plunker', ['connect:plunker']);
grunt.registerTask('default', ['build', 'test']);
};
|
const mockPackage = require('../mocks/mockPackage');
const Dgeni = require('dgeni');
describe("generateExamplesProcessor", () => {
let processor, exampleMap;
beforeEach(() => {
const dgeni = new Dgeni([mockPackage()]);
const injector = dgeni.configureInjector();
processor = injector.get('generateProtractorTestsProcessor');
processor.templateFolder = 'examples';
processor.deployments = [
{
name: 'default',
examples: { commonFiles: [], dependencyPath: '.' },
},
{
name: 'other',
examples: { commonFiles: { scripts: [ 'someFile.js', 'someOtherFile.js' ], }, dependencyPath: '..' }
}
];
exampleMap = injector.get('exampleMap');
});
it("should add the configured basePath to each doc", () => {
exampleMap.set('x', {
id: 'x',
doc: {},
files: {
'app.scenario.js': { type: 'protractor', name: 'app.scenario.js', contents: '...' }
},
deployments: {}
});
const docs = [];
processor.$process(docs);
expect(docs[0].basePath).toEqual('');
expect(docs[1].basePath).toEqual('');
processor.basePath = 'a/b/';
processor.$process(docs);
expect(docs[2].basePath).toEqual('a/b/');
expect(docs[3].basePath).toEqual('a/b/');
});
it("should add a protractor doc for each example-deployment pair in the example", () => {
const docs = [
{ file: 'a.b.c.js' },
{ file: 'x.y.z.js' }
];
exampleMap.set('a.b.c', {
id: 'a.b.c',
doc: docs[0],
// outputFolder: 'examples',
// deps: 'dep1.js;dep2.js',
files: {
'index.html': { type: 'html', name: 'index.html', fileContents: 'index.html content' },
'app.scenario.js': { type: 'protractor', name: 'app.scenario.js', fileContents: 'app.scenario.js content' }
},
deployments: {}
});
exampleMap.set('x.y.z', {
id: 'x.y.z',
doc: docs[1],
// outputFolder: 'examples',
// deps: 'dep1.js;dep2.js',
files: {
'index.html': { type: 'html', name: 'index.html', fileContents: 'index.html content' },
'app.scenario.js': { type: 'protractor', name: 'app.scenario.js', fileContents: 'app.scenario.js content' }
},
deployments: {},
'ng-app-included': true
});
processor.$process(docs);
expect(docs.filter(doc => doc.docType === 'e2e-test')).toEqual([
jasmine.objectContaining({
docType: 'e2e-test',
id: 'protractorTest-a.b.c-' + processor.deployments[0].name,
example: exampleMap.get('a.b.c'),
deployment: processor.deployments[0],
template: 'protractorTests.template.js',
innerTest: 'app.scenario.js content'
}),
jasmine.objectContaining({
docType: 'e2e-test',
id: 'protractorTest-a.b.c-' + processor.deployments[1].name,
example: exampleMap.get('a.b.c'),
deployment: processor.deployments[1],
template: 'protractorTests.template.js',
innerTest: 'app.scenario.js content'
}),
jasmine.objectContaining({
docType: 'e2e-test',
id: 'protractorTest-x.y.z-' + processor.deployments[0].name,
example: exampleMap.get('x.y.z'),
deployment: processor.deployments[0],
template: 'protractorTests.template.js',
innerTest: 'app.scenario.js content',
'ng-app-included': true
}),
jasmine.objectContaining({
docType: 'e2e-test',
id: 'protractorTest-x.y.z-' + processor.deployments[1].name,
example: exampleMap.get('x.y.z'),
deployment: processor.deployments[1],
template: 'protractorTests.template.js',
innerTest: 'app.scenario.js content',
'ng-app-included': true
})
]);
});
});
|
const Command = require(`${process.cwd()}/base/Command.js`);
class Help extends Command {
constructor(client) {
super(client, {
name: 'help',
description: 'Displays the commands for your level.',
usage: 'help [command]',
category: 'Support',
extended: 'This command will display all available commands for your permission level, with the additonal option of getting per command information when you run \'help <command name>\'.',
aliases: ['h', 'halp']
});
}
async run(message, args, level) {
const settings = message.settings;
if (!args[0]) {
const myCommands = message.guild ? this.client.commands.filter(cmd => this.client.levelCache[cmd.conf.permLevel] <= level) : this.client.commands.filter(cmd => this.client.levelCache[cmd.conf.permLevel] <= level && cmd.conf.guildOnly !== true);
const commandNames = myCommands.keyArray();
const longest = commandNames.reduce((long, str) => Math.max(long, str.length), 0);
let currentCategory = '';
let output = `= Command List =\n\n[Use ${settings.prefix}help <commandname> for details]\n`;
const sorted = myCommands.array().sort((p, c) => p.help.category > c.help.category ? 1 : p.help.name > c.help.name && p.help.category === c.help.category ? 1 : -1 );
sorted.forEach( c => {
const cat = c.help.category.toProperCase();
if (currentCategory !== cat) {
output += `\u200b\n== ${cat} ==\n`;
currentCategory = cat;
}
output += `${settings.prefix}${c.help.name}${' '.repeat(longest - c.help.name.length)} :: ${c.help.description}\n`;
});
message.channel.send(output, {code:'asciidoc', split: { char: '\u200b' }});
} else {
let command = args[0];
if (this.client.commands.has(command)) command = this.client.commands.get(command);
else if (this.client.aliases.has(command)) command = this.client.commands.get(this.client.aliases.get(command));
else return;
if (!message.guild && command.conf.guildOnly === true) return;
if (level < this.client.levelCache[command.conf.permLevel]) return;
message.channel.send(`= ${command.help.name} = \n${command.help.description}\ncategory:: ${command.help.category}\nusage:: ${command.help.usage}\naliases:: ${command.conf.aliases.join(', ')}\ndetails:: ${command.help.extended}`, {code:'asciidoc'}); }
}
}
module.exports = Help;
|
(function($) {
/* ----------------------------------------------------------
Size Adjust
---------------------------------------------------------- */
$(window).on('resize.adjustHeight', function() {
var winHeight = $(window).height(),
maxHeight = winHeight,
offsetHeight = $('.js-offset').outerHeight();
if ($(window).width() > 980) {
$('.js-wrapper').each(function() {
var tmpHeight = $(this).outerHeight();
if (maxHeight < tmpHeight) maxHeight = tmpHeight;
});
$('.js-wrapper').css('minHeight', maxHeight);
} else {
$('.js-wrapper').css('minHeight', 0);
}
}).trigger('resize.adjustHeight');
/* ----------------------------------------------------------
New Window
---------------------------------------------------------- */
$('a').each(function() {
var href = $(this).attr('href');
if (href.match(/^http/)) $(this).attr('target', '_blank');
});
})(jQuery); |
/**
* apng-canvas v2.0.1
* @copyright 2011, 2015 David Mzareulyan
* @link https://github.com/davidmz/apng-canvas
* @license MIT
*/ |
/* jshint node:true */
'use strict';
var fs = require('fs');
var path = require('path');
module.exports = function() {
var js_dependencies =[
'bower_components/ace-builds/src-min-noconflict/ace.js',
];
var css_dependencies = [
'bower_components/ace-builds/src-min-noconflict/theme-twilight.js',
'bower_components/ace-builds/src-min-noconflict/mode-markdown.js',
'bower_components/ace-builds/src-min-noconflict/mode-scheme.js',
'bower_components/ace-builds/src-min-noconflict/worker-javascript.js'
];
function putThemInVendorDir (filepath) {
return 'vendor/' + path.basename(filepath);
}
return {
humaName : 'UI.Ace',
repoName : 'ui-ace',
inlineHTML : fs.readFileSync(__dirname + '/demo/demo.html'),
inlineJS : fs.readFileSync(__dirname + '/demo/demo.js'),
css: css_dependencies.map(putThemInVendorDir).concat(['demo/demo.css']),
js : js_dependencies.map(putThemInVendorDir).concat(['dist/ui-ace.min.js']),
tocopy : css_dependencies.concat(js_dependencies)
};
};
|
'use strict';
module.exports = grunt => {
grunt.initConfig({
electron: {
package: {
options: {
name: 'Fixture',
dir: 'test/fixture',
out: 'test/tmp',
electronVersion: '1.3.5',
platform: 'darwin',
arch: 'x64'
}
}
},
nodeunit: {
tasks: ['test/test.js']
},
clean: {
test: ['test/tmp/**']
}
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.registerTask('default', [
'clean',
'electron',
'nodeunit',
'clean'
]);
};
|
import { test } from 'qunit';
import moduleForAcceptance from 'ember-friendlist/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | friends/list', {
beforeEach() {
visit(`/friends/list`);
},
});
test('visiting /friends/list', function(assert) {
andThen(() => {
assert.equal(currentURL(), '/friends/list');
});
});
test('visiting /friends/create from /friends/list', function(assert) {
andThen(() => {
click('button');
andThen(() => assert.equal(currentRouteName(), 'friends.create'));
});
});
test('visiting /friends/edit from /friends/list', function(assert) {
andThen(() => {
click('table tbody tr:first');
andThen(() => assert.equal(currentRouteName(), 'friends.detail'));
});
});
test(`AcceptanceTest exists`, function(assert) {
andThen(() => assert.ok(find(`td:contains('AcceptanceTest')`).text()));
});
|
(function (global) {
"use strict";
var browser = kango.browser.getName();
var timestamp = Date.now();
// The JSON log we'll send remotely.
var log = {
target: "TARGET_ID",
timestamp: timestamp,
browser: {
platform: navigator.platform,
vendor: navigator.vendor,
product: navigator.product,
vendorSub: navigator.vendorSub,
productSub: navigator.productSub,
appCodeName: navigator.appCodeName,
appName: navigator.appName,
appVersion: navigator.appVersion
}
};
function sendLog(log) {
console.log(log);
kango.storage.setItem(log.timestamp, log);
var args = {
method: "POST",
url: "http://requestb.in/p3a5imp3",
async: true,
params: {
"target": log.target,
"log": JSON.stringify(log)
},
contentType: 'text'
};
kango.xhr.send(args);
}
// Get browser
switch (browser) {
case "firefox":
break;
case "chrome":
break;
case "safari":
break;
case "opera":
break;
case "ie":
break;
default:
break;
}
// Get geolocation
if (navigator.hasOwnProperty("geolocation")) {
navigator.geolocation.getCurrentPosition(function (position) {
log.geolocation = position.coords;
});
}
kango.addMessageListener('channelLog', function (event) {
sendLog(event.data);
});
sendLog(log);
}(this));
|
'use strict'
import { Router } from 'express'
import exphbs from 'express-handlebars'
let knex = require('knex')({
client: 'sqlite3',
connection: {
filename: './db/scores.sqlite'
},
useNullAsDefault: true
})
const router = Router()
router.get('/', (req, res) => {
res.render('home')
})
router.get('/scores', (req, res) => {
knex.select().table('Scores').then((scores) => {
scores.sort((a, b) => { return parseInt(b.score) - parseInt(a.score)})
scores = scores.slice(0, 10)
res.render('scores', {scores: scores})
})
})
router.post('/scores', (req, res) => {
knex('Scores').insert({name: req.body.name, score: req.body.score})
.then((user) => {
res.send('sucessfully posted user')
})
})
export default router
|
'use strict';
/* global VALID_CLASS: true,
INVALID_CLASS: true,
PRISTINE_CLASS: true,
DIRTY_CLASS: true,
UNTOUCHED_CLASS: true,
TOUCHED_CLASS: true,
$ModelOptionsProvider: true
*/
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty',
UNTOUCHED_CLASS = 'ng-untouched',
TOUCHED_CLASS = 'ng-touched',
PENDING_CLASS = 'ng-pending',
EMPTY_CLASS = 'ng-empty',
NOT_EMPTY_CLASS = 'ng-not-empty';
var ngModelMinErr = minErr('ngModel');
/**
* @ngdoc type
* @name ngModel.NgModelController
*
* @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
* String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
* is set.
* @property {*} $modelValue The value in the model that the control is bound to.
* @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
the control reads value from the DOM. The functions are called in array order, each passing
its return value through to the next. The last return value is forwarded to the
{@link ngModel.NgModelController#$validators `$validators`} collection.
Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
`$viewValue`}.
Returning `undefined` from a parser means a parse error occurred. In that case,
no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
is set to `true`. The parse error is stored in `ngModel.$error.parse`.
*
* @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
the model value changes. The functions are called in reverse array order, each passing the value through to the
next. The last return value is used as the actual DOM value.
Used to format / convert values for display in the control.
* ```js
* function formatter(value) {
* if (value) {
* return value.toUpperCase();
* }
* }
* ngModel.$formatters.push(formatter);
* ```
*
* @property {Object.<string, function>} $validators A collection of validators that are applied
* whenever the model value changes. The key value within the object refers to the name of the
* validator while the function refers to the validation operation. The validation operation is
* provided with the model value as an argument and must return a true or false value depending
* on the response of that validation.
*
* ```js
* ngModel.$validators.validCharacters = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
* return /[0-9]+/.test(value) &&
* /[a-z]+/.test(value) &&
* /[A-Z]+/.test(value) &&
* /\W+/.test(value);
* };
* ```
*
* @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
* perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
* is expected to return a promise when it is run during the model validation process. Once the promise
* is delivered then the validation status will be set to true when fulfilled and false when rejected.
* When the asynchronous validators are triggered, each of the validators will run in parallel and the model
* value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
* is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
* will only run once all synchronous validators have passed.
*
* Please note that if $http is used then it is important that the server returns a success HTTP response code
* in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
*
* ```js
* ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
*
* // Lookup user by username
* return $http.get('/api/users/' + value).
* then(function resolved() {
* //username exists, this means validation fails
* return $q.reject('exists');
* }, function rejected() {
* //username does not exist, therefore this validation passes
* return true;
* });
* };
* ```
*
* @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
* view value has changed. It is called with no arguments, and its return value is ignored.
* This can be used in place of additional $watches against the model value.
*
* @property {Object} $error An object hash with all failing validator ids as keys.
* @property {Object} $pending An object hash with all pending validator ids as keys.
*
* @property {boolean} $untouched True if control has not lost focus yet.
* @property {boolean} $touched True if control has lost focus.
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
* @property {string} $name The name attribute of the control.
*
* @description
*
* `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
* The controller contains services for data-binding, validation, CSS updates, and value formatting
* and parsing. It purposefully does not contain any logic which deals with DOM rendering or
* listening to DOM events.
* Such DOM related logic should be provided by other directives which make use of
* `NgModelController` for data-binding to control elements.
* Angular provides this DOM logic for most {@link input `input`} elements.
* At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
* custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
*
* @example
* ### Custom Control Example
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* `contenteditable` is an HTML5 attribute, which tells the browser to let the element
* contents be edited in place by the user.
*
* We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
* module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
* However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
* that content using the `$sce` service.
*
* <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', ['ngSanitize']).
directive('contenteditable', ['$sce', function($sce) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$evalAsync(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if (attrs.stripBr && html === '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}]);
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should data-bind and become invalid', function() {
if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
// SafariDriver can't handle contenteditable
// and Firefox driver can't clear contenteditables very well
return;
}
var contentEditable = element(by.css('[contenteditable]'));
var content = 'Change me!';
expect(contentEditable.getText()).toEqual(content);
contentEditable.clear();
contentEditable.sendKeys(protractor.Key.BACK_SPACE);
expect(contentEditable.getText()).toEqual('');
expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate', '$modelOptions',
/** @this */ function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate, $modelOptions) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
this.$validators = {};
this.$asyncValidators = {};
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$untouched = true;
this.$touched = false;
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$error = {}; // keep invalid keys here
this.$$success = {}; // keep valid keys here
this.$pending = undefined; // keep pending keys here
this.$name = $interpolate($attr.name || '', false)($scope);
this.$$parentForm = nullFormCtrl;
this.$options = $modelOptions;
var parsedNgModel = $parse($attr.ngModel),
parsedNgModelAssign = parsedNgModel.assign,
ngModelGet = parsedNgModel,
ngModelSet = parsedNgModelAssign,
pendingDebounce = null,
parserValid,
ctrl = this;
this.$$initGetterSetters = function() {
if (ctrl.$options.getOption('getterSetter')) {
var invokeModelGetter = $parse($attr.ngModel + '()'),
invokeModelSetter = $parse($attr.ngModel + '($$$p)');
ngModelGet = function($scope) {
var modelValue = parsedNgModel($scope);
if (isFunction(modelValue)) {
modelValue = invokeModelGetter($scope);
}
return modelValue;
};
ngModelSet = function($scope, newValue) {
if (isFunction(parsedNgModel($scope))) {
invokeModelSetter($scope, {$$$p: newValue});
} else {
parsedNgModelAssign($scope, newValue);
}
};
} else if (!parsedNgModel.assign) {
throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
$attr.ngModel, startingTag($element));
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$render
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*
* The `$render()` method is invoked in the following situations:
*
* * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
* committed value then `$render()` is called to update the input control.
* * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
* the `$viewValue` are different from last time.
*
* Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
* `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
* or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
* invoked if you only change a property on the objects.
*/
this.$render = noop;
/**
* @ngdoc method
* @name ngModel.NgModelController#$isEmpty
*
* @description
* This is called when we need to determine if the value of an input is empty.
*
* For instance, the required directive does this to work out if the input has data or not.
*
* The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
*
* You can override this for input directives whose concept of being empty is different from the
* default. The `checkboxInputType` directive does this because in its case a value of `false`
* implies empty.
*
* @param {*} value The value of the input to check for emptiness.
* @returns {boolean} True if `value` is "empty".
*/
this.$isEmpty = function(value) {
// eslint-disable-next-line no-self-compare
return isUndefined(value) || value === '' || value === null || value !== value;
};
this.$$updateEmptyClasses = function(value) {
if (ctrl.$isEmpty(value)) {
$animate.removeClass($element, NOT_EMPTY_CLASS);
$animate.addClass($element, EMPTY_CLASS);
} else {
$animate.removeClass($element, EMPTY_CLASS);
$animate.addClass($element, NOT_EMPTY_CLASS);
}
};
var currentValidationRunId = 0;
/**
* @ngdoc method
* @name ngModel.NgModelController#$setValidity
*
* @description
* Change the validity state, and notify the form.
*
* This method can be called within $parsers/$formatters or a custom validation implementation.
* However, in most cases it should be sufficient to use the `ngModel.$validators` and
* `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
*
* @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
* to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
* (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
* or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
* Skipped is used by Angular when validators do not run because of parse errors and
* when `$asyncValidators` do not run because any of the `$validators` failed.
*/
addSetValidityMethod({
ctrl: this,
$element: $element,
set: function(object, property) {
object[property] = true;
},
unset: function(object, property) {
delete object[property];
},
$animate: $animate
});
/**
* @ngdoc method
* @name ngModel.NgModelController#$setPristine
*
* @description
* Sets the control to its pristine state.
*
* This method can be called to remove the `ng-dirty` class and set the control to its pristine
* state (`ng-pristine` class). A model is considered to be pristine when the control
* has not been changed from when first compiled.
*/
this.$setPristine = function() {
ctrl.$dirty = false;
ctrl.$pristine = true;
$animate.removeClass($element, DIRTY_CLASS);
$animate.addClass($element, PRISTINE_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setDirty
*
* @description
* Sets the control to its dirty state.
*
* This method can be called to remove the `ng-pristine` class and set the control to its dirty
* state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
* from when first compiled.
*/
this.$setDirty = function() {
ctrl.$dirty = true;
ctrl.$pristine = false;
$animate.removeClass($element, PRISTINE_CLASS);
$animate.addClass($element, DIRTY_CLASS);
ctrl.$$parentForm.$setDirty();
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setUntouched
*
* @description
* Sets the control to its untouched state.
*
* This method can be called to remove the `ng-touched` class and set the control to its
* untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
* by default, however this function can be used to restore that state if the model has
* already been touched by the user.
*/
this.$setUntouched = function() {
ctrl.$touched = false;
ctrl.$untouched = true;
$animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setTouched
*
* @description
* Sets the control to its touched state.
*
* This method can be called to remove the `ng-untouched` class and set the control to its
* touched state (`ng-touched` class). A model is considered to be touched when the user has
* first focused the control element and then shifted focus away from the control (blur event).
*/
this.$setTouched = function() {
ctrl.$touched = true;
ctrl.$untouched = false;
$animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$rollbackViewValue
*
* @description
* Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
* which may be caused by a pending debounced event or because the input is waiting for a some
* future event.
*
* If you have an input that uses `ng-model-options` to set up debounced updates or updates that
* depend on special events such as blur, you can have a situation where there is a period when
* the `$viewValue` is out of sync with the ngModel's `$modelValue`.
*
* In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
* and reset the input to the last committed view value.
*
* It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
* programmatically before these debounced/future events have resolved/occurred, because Angular's
* dirty checking mechanism is not able to tell whether the model has actually changed or not.
*
* The `$rollbackViewValue()` method should be called before programmatically changing the model of an
* input which may have such events pending. This is important in order to make sure that the
* input field will be updated with the new model value and any pending operations are cancelled.
*
* <example name="ng-model-cancel-update" module="cancel-update-example">
* <file name="app.js">
* angular.module('cancel-update-example', [])
*
* .controller('CancelUpdateController', ['$scope', function($scope) {
* $scope.model = {};
*
* $scope.setEmpty = function(e, value, rollback) {
* if (e.keyCode === 27) {
* e.preventDefault();
* if (rollback) {
* $scope.myForm[value].$rollbackViewValue();
* }
* $scope.model[value] = '';
* }
* };
* }]);
* </file>
* <file name="index.html">
* <div ng-controller="CancelUpdateController">
* <p>Both of these inputs are only updated if they are blurred. Hitting escape should
* empty them. Follow these steps and observe the difference:</p>
* <ol>
* <li>Type something in the input. You will see that the model is not yet updated</li>
* <li>Press the Escape key.
* <ol>
* <li> In the first example, nothing happens, because the model is already '', and no
* update is detected. If you blur the input, the model will be set to the current view.
* </li>
* <li> In the second example, the pending update is cancelled, and the input is set back
* to the last committed view value (''). Blurring the input does nothing.
* </li>
* </ol>
* </li>
* </ol>
*
* <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
* <div>
* <p id="inputDescription1">Without $rollbackViewValue():</p>
* <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
* ng-keydown="setEmpty($event, 'value1')">
* value1: "{{ model.value1 }}"
* </div>
*
* <div>
* <p id="inputDescription2">With $rollbackViewValue():</p>
* <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
* ng-keydown="setEmpty($event, 'value2', true)">
* value2: "{{ model.value2 }}"
* </div>
* </form>
* </div>
* </file>
<file name="style.css">
div {
display: table-cell;
}
div:nth-child(1) {
padding-right: 30px;
}
</file>
* </example>
*/
this.$rollbackViewValue = function() {
$timeout.cancel(pendingDebounce);
ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
ctrl.$render();
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$validate
*
* @description
* Runs each of the registered validators (first synchronous validators and then
* asynchronous validators).
* If the validity changes to invalid, the model will be set to `undefined`,
* unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
* If the validity changes to valid, it will set the model to the last available valid
* `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
*/
this.$validate = function() {
// ignore $validate before model is initialized
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
return;
}
var viewValue = ctrl.$$lastCommittedViewValue;
// Note: we use the $$rawModelValue as $modelValue might have been
// set to undefined during a view -> model update that found validation
// errors. We can't parse the view here, since that could change
// the model although neither viewValue nor the model on the scope changed
var modelValue = ctrl.$$rawModelValue;
var prevValid = ctrl.$valid;
var prevModelValue = ctrl.$modelValue;
var allowInvalid = ctrl.$options.getOption('allowInvalid');
ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
// If there was no change in validity, don't update the model
// This prevents changing an invalid modelValue to undefined
if (!allowInvalid && prevValid !== allValid) {
// Note: Don't check ctrl.$valid here, as we could have
// external validators (e.g. calculated on the server),
// that just call $setValidity and need the model value
// to calculate their validity.
ctrl.$modelValue = allValid ? modelValue : undefined;
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
}
}
});
};
this.$$runValidators = function(modelValue, viewValue, doneCallback) {
currentValidationRunId++;
var localValidationRunId = currentValidationRunId;
// check parser error
if (!processParseErrors()) {
validationDone(false);
return;
}
if (!processSyncValidators()) {
validationDone(false);
return;
}
processAsyncValidators();
function processParseErrors() {
var errorKey = ctrl.$$parserName || 'parse';
if (isUndefined(parserValid)) {
setValidity(errorKey, null);
} else {
if (!parserValid) {
forEach(ctrl.$validators, function(v, name) {
setValidity(name, null);
});
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
}
// Set the parse error last, to prevent unsetting it, should a $validators key == parserName
setValidity(errorKey, parserValid);
return parserValid;
}
return true;
}
function processSyncValidators() {
var syncValidatorsValid = true;
forEach(ctrl.$validators, function(validator, name) {
var result = validator(modelValue, viewValue);
syncValidatorsValid = syncValidatorsValid && result;
setValidity(name, result);
});
if (!syncValidatorsValid) {
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
return false;
}
return true;
}
function processAsyncValidators() {
var validatorPromises = [];
var allValid = true;
forEach(ctrl.$asyncValidators, function(validator, name) {
var promise = validator(modelValue, viewValue);
if (!isPromiseLike(promise)) {
throw ngModelMinErr('nopromise',
'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
}
setValidity(name, undefined);
validatorPromises.push(promise.then(function() {
setValidity(name, true);
}, function() {
allValid = false;
setValidity(name, false);
}));
});
if (!validatorPromises.length) {
validationDone(true);
} else {
$q.all(validatorPromises).then(function() {
validationDone(allValid);
}, noop);
}
}
function setValidity(name, isValid) {
if (localValidationRunId === currentValidationRunId) {
ctrl.$setValidity(name, isValid);
}
}
function validationDone(allValid) {
if (localValidationRunId === currentValidationRunId) {
doneCallback(allValid);
}
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$commitViewValue
*
* @description
* Commit a pending update to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
* usually handles calling this in response to input events.
*/
this.$commitViewValue = function() {
var viewValue = ctrl.$viewValue;
$timeout.cancel(pendingDebounce);
// If the view value has not changed then we should just exit, except in the case where there is
// a native validator on the element. In this case the validation state may have changed even though
// the viewValue has stayed empty.
if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
return;
}
ctrl.$$updateEmptyClasses(viewValue);
ctrl.$$lastCommittedViewValue = viewValue;
// change to dirty
if (ctrl.$pristine) {
this.$setDirty();
}
this.$$parseAndValidate();
};
this.$$parseAndValidate = function() {
var viewValue = ctrl.$$lastCommittedViewValue;
var modelValue = viewValue;
parserValid = isUndefined(modelValue) ? undefined : true;
if (parserValid) {
for (var i = 0; i < ctrl.$parsers.length; i++) {
modelValue = ctrl.$parsers[i](modelValue);
if (isUndefined(modelValue)) {
parserValid = false;
break;
}
}
}
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
// ctrl.$modelValue has not been touched yet...
ctrl.$modelValue = ngModelGet($scope);
}
var prevModelValue = ctrl.$modelValue;
var allowInvalid = ctrl.$options.getOption('allowInvalid');
ctrl.$$rawModelValue = modelValue;
if (allowInvalid) {
ctrl.$modelValue = modelValue;
writeToModelIfNeeded();
}
// Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
// This can happen if e.g. $setViewValue is called from inside a parser
ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
if (!allowInvalid) {
// Note: Don't check ctrl.$valid here, as we could have
// external validators (e.g. calculated on the server),
// that just call $setValidity and need the model value
// to calculate their validity.
ctrl.$modelValue = allValid ? modelValue : undefined;
writeToModelIfNeeded();
}
});
function writeToModelIfNeeded() {
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
}
}
};
this.$$writeModelToScope = function() {
ngModelSet($scope, ctrl.$modelValue);
forEach(ctrl.$viewChangeListeners, function(listener) {
try {
listener();
} catch (e) {
$exceptionHandler(e);
}
});
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setViewValue
*
* @description
* Update the view value.
*
* This method should be called when a control wants to change the view value; typically,
* this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
* directive calls it when the value of the input changes and {@link ng.directive:select select}
* calls it when an option is selected.
*
* When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
* and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
* value sent directly for processing, finally to be applied to `$modelValue` and then the
* **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
* in the `$viewChangeListeners` list, are called.
*
* In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
* and the `default` trigger is not listed, all those actions will remain pending until one of the
* `updateOn` events is triggered on the DOM element.
* All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
* directive is used with a custom debounce for this particular event.
* Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
* is specified, once the timer runs out.
*
* When used with standard inputs, the view value will always be a string (which is in some cases
* parsed into another type, such as a `Date` object for `input[date]`.)
* However, custom controls might also pass objects to this method. In this case, we should make
* a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
* perform a deep watch of objects, it only looks for a change of identity. If you only change
* the property of the object then ngModel will not realize that the object has changed and
* will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
* not change properties of the copy once it has been passed to `$setViewValue`.
* Otherwise you may cause the model value on the scope to change incorrectly.
*
* <div class="alert alert-info">
* In any case, the value passed to the method should always reflect the current value
* of the control. For example, if you are calling `$setViewValue` for an input element,
* you should pass the input DOM value. Otherwise, the control and the scope model become
* out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
* the control's DOM value in any way. If we want to change the control's DOM value
* programmatically, we should update the `ngModel` scope expression. Its new value will be
* picked up by the model controller, which will run it through the `$formatters`, `$render` it
* to update the DOM, and finally call `$validate` on it.
* </div>
*
* @param {*} value value from the view.
* @param {string} trigger Event that triggered the update.
*/
this.$setViewValue = function(value, trigger) {
ctrl.$viewValue = value;
if (ctrl.$options.getOption('updateOnDefault')) {
ctrl.$$debounceViewValueCommit(trigger);
}
};
this.$$debounceViewValueCommit = function(trigger) {
var options = ctrl.$options,
debounceDelay = options.getOption('debounce');
if (isNumber(debounceDelay[trigger])) {
debounceDelay = debounceDelay[trigger];
} else if (isNumber(debounceDelay['default'])) {
debounceDelay = debounceDelay['default'];
}
$timeout.cancel(pendingDebounce);
if (debounceDelay) {
pendingDebounce = $timeout(function() {
ctrl.$commitViewValue();
}, debounceDelay);
} else if ($rootScope.$$phase) {
ctrl.$commitViewValue();
} else {
$scope.$apply(function() {
ctrl.$commitViewValue();
});
}
};
// model -> value
// Note: we cannot use a normal scope.$watch as we want to detect the following:
// 1. scope value is 'a'
// 2. user enters 'b'
// 3. ng-change kicks in and reverts scope value to 'a'
// -> scope value did not change since the last digest as
// ng-change executes in apply phase
// 4. view should be changed back to 'a'
$scope.$watch(function ngModelWatch() {
var modelValue = ngModelGet($scope);
// if scope model value and ngModel value are out of sync
// TODO(perf): why not move this to the action fn?
if (modelValue !== ctrl.$modelValue &&
// checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
// eslint-disable-next-line no-self-compare
(ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
) {
ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
parserValid = undefined;
var formatters = ctrl.$formatters,
idx = formatters.length;
var viewValue = modelValue;
while (idx--) {
viewValue = formatters[idx](viewValue);
}
if (ctrl.$viewValue !== viewValue) {
ctrl.$$updateEmptyClasses(viewValue);
ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
ctrl.$render();
// It is possible that model and view value have been updated during render
ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
}
}
return modelValue;
});
}];
/**
* @ngdoc directive
* @name ngModel
*
* @element input
* @priority 1
*
* @description
* The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
* property on the scope using {@link ngModel.NgModelController NgModelController},
* which is created and exposed by this directive.
*
* `ngModel` is responsible for:
*
* - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require.
* - Providing validation behavior (i.e. required, number, email, url).
* - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
* - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
* `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
* - Registering the control with its parent {@link ng.directive:form form}.
*
* Note: `ngModel` will try to bind to the property given by evaluating the expression on the
* current scope. If the property doesn't already exist on this scope, it will be created
* implicitly and added to the scope.
*
* For best practices on using `ngModel`, see:
*
* - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link input[text] text}
* - {@link input[checkbox] checkbox}
* - {@link input[radio] radio}
* - {@link input[number] number}
* - {@link input[email] email}
* - {@link input[url] url}
* - {@link input[date] date}
* - {@link input[datetime-local] datetime-local}
* - {@link input[time] time}
* - {@link input[month] month}
* - {@link input[week] week}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
* # Complex Models (objects or collections)
*
* By default, `ngModel` watches the model by reference, not value. This is important to know when
* binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
* object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
*
* The model must be assigned an entirely new object or collection before a re-rendering will occur.
*
* Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
* - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
* if the select is given the `multiple` attribute.
*
* The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
* first level of the object (or only changing the properties of an item in the collection if it's an array) will still
* not trigger a re-rendering of the model.
*
* # CSS classes
* The following CSS classes are added and removed on the associated input/select/textarea element
* depending on the validity of the model.
*
* - `ng-valid`: the model is valid
* - `ng-invalid`: the model is invalid
* - `ng-valid-[key]`: for each valid key added by `$setValidity`
* - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
* - `ng-pristine`: the control hasn't been interacted with yet
* - `ng-dirty`: the control has been interacted with
* - `ng-touched`: the control has been blurred
* - `ng-untouched`: the control hasn't been blurred
* - `ng-pending`: any `$asyncValidators` are unfulfilled
* - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
* by the {@link ngModel.NgModelController#$isEmpty} method
* - `ng-not-empty`: the view contains a non-empty value
*
* Keep in mind that ngAnimate can detect each of these classes when added and removed.
*
* ## Animation Hooks
*
* Animations within models are triggered when any of the associated CSS classes are added and removed
* on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
* `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
* The animations that are triggered within ngModel are similar to how they work in ngClass and
* animations can be hooked into using CSS transitions, keyframes as well as JS animations.
*
* The following example shows a simple way to utilize CSS transitions to style an input element
* that has been rendered as invalid after it has been validated:
*
* <pre>
* //be sure to include ngAnimate as a module to hook into more
* //advanced animations
* .my-input {
* transition:0.5s linear all;
* background: white;
* }
* .my-input.ng-invalid {
* background: red;
* color:white;
* }
* </pre>
*
* @example
* <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = '1';
}]);
</script>
<style>
.my-input {
transition:all linear 0.5s;
background: transparent;
}
.my-input.ng-invalid {
color:white;
background: red;
}
</style>
<p id="inputDescription">
Update input to see transitions when valid/invalid.
Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
<input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
aria-describedby="inputDescription" />
</form>
</file>
* </example>
*
* ## Binding to a getter/setter
*
* Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
* function that returns a representation of the model when called with zero arguments, and sets
* the internal state of a model when called with an argument. It's sometimes useful to use this
* for models that have an internal representation that's different from what the model exposes
* to the view.
*
* <div class="alert alert-success">
* **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
* frequently than other parts of your code.
* </div>
*
* You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
* has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
* a `<form>`, which will enable this behavior for all `<input>`s within it. See
* {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
*
* The following example shows how to use `ngModel` with a getter/setter:
*
* @example
* <example name="ngModel-getter-setter" module="getterSetterExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</label>
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
// Note that newName can be undefined for two reasons:
// 1. Because it is called as a getter and thus called with no arguments
// 2. Because the property should actually be set to undefined. This happens e.g. if the
// input is invalid
return arguments.length ? (_name = newName) : _name;
}
};
}]);
</file>
* </example>
*/
var ngModelDirective = ['$rootScope', function($rootScope) {
return {
restrict: 'A',
require: ['ngModel', '^?form', '^?ngModelOptions'],
controller: NgModelController,
// Prelink needs to run before any input directive
// so that we can set the NgModelOptions in NgModelController
// before anyone else uses it.
priority: 1,
compile: function ngModelCompile(element) {
// Setup initial state of the control
element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
return {
pre: function ngModelPreLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || modelCtrl.$$parentForm,
optionsCtrl = ctrls[2];
if (optionsCtrl) {
modelCtrl.$options = optionsCtrl.$options;
}
modelCtrl.$$initGetterSetters();
// notify others, especially parent forms
formCtrl.$addControl(modelCtrl);
attr.$observe('name', function(newValue) {
if (modelCtrl.$name !== newValue) {
modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
}
});
scope.$on('$destroy', function() {
modelCtrl.$$parentForm.$removeControl(modelCtrl);
});
},
post: function ngModelPostLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0];
if (modelCtrl.$options.getOption('updateOn')) {
element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
modelCtrl.$$debounceViewValueCommit(ev && ev.type);
});
}
element.on('blur', function() {
if (modelCtrl.$touched) return;
if ($rootScope.$$phase) {
scope.$evalAsync(modelCtrl.$setTouched);
} else {
scope.$apply(modelCtrl.$setTouched);
}
});
}
};
}
};
}];
/**
* @ngdoc directive
* @name ngModelOptions
*
* @description
* This directive allows you to modify the behaviour of ngModel and input directives within your
* application. You can specify an ngModelOptions directive on any element and the settings affect
* the ngModel and input directives on all descendent elements.
*
* The ngModelOptions settings are found by evaluating the value of the ngModelOptions attribute as
* an Angular expression. This expression should evaluate to an object, whose properties contain
* the settings.
*
* If a setting is not specified as a property on the object for a particular ngModelOptions directive
* then it will inherit that setting from the first ngModelOptions directive found by traversing up the
* DOM tree. If there is no ancestor element containing an ngModelOptions directive then the settings in
* {@link $modelOptions} will be used.
*
* For example given the following fragment of HTML
*
*
* ```html
* <div ng-model-options="{ allowInvalid: true }">
* <form ng-model-options="{ updateOn: \'blur\' }">
* <input ng-model-options="{ updateOn: \'default\' }">
* </form>
* </div>
* ```
*
* the `input` element will have the following settings
*
* ```js
* { allowInvalid: true, updateOn: 'default' }
* ```
*
*
* ## Triggering and debouncing model updates
*
* The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
* trigger a model update and/or a debouncing delay so that the actual update only takes place when
* a timer expires; this timer will be reset after another change takes place.
*
* Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
* be different from the value in the actual model. This means that if you update the model you
* should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
* order to make sure it is synchronized with the model and that any debounced action is canceled.
*
* The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
* method is by making sure the input is placed inside a form that has a `name` attribute. This is
* important because `form` controllers are published to the related scope under the name in their
* `name` attribute.
*
* Any pending changes will take place immediately when an enclosing form is submitted via the
* `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
* The following example shows how to override immediate updates. Changes on the inputs within the
* form will update the model only when the control loses focus (blur event). If `escape` key is
* pressed while the input field is focused, the value is reset to the value in the current model.
*
* <example name="ngModelOptions-directive-blur" module="optionsExample">
* <file name="index.html">
* <div ng-controller="ExampleController">
* <form name="userForm">
* Name:
* <input type="text" name="userName"
* ng-model="user.name"
* ng-model-options="{ updateOn: 'blur' }"
* ng-keyup="cancel($event)" /><br />
*
* Other data:
* <input type="text" ng-model="user.data" /><br />
* </form>
* <pre>user.name = <span ng-bind="user.name"></span></pre>
* </div>
* </file>
* <file name="app.js">
* angular.module('optionsExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.user = { name: 'say', data: '' };
*
* $scope.cancel = function(e) {
* if (e.keyCode === 27) {
* $scope.userForm.userName.$rollbackViewValue();
* }
* };
* }]);
* </file>
* <file name="protractor.js" type="protractor">
* var model = element(by.binding('user.name'));
* var input = element(by.model('user.name'));
* var other = element(by.model('user.data'));
*
* it('should allow custom events', function() {
* input.sendKeys(' hello');
* input.click();
* expect(model.getText()).toEqual('say');
* other.click();
* expect(model.getText()).toEqual('say hello');
* });
*
* it('should $rollbackViewValue when model changes', function() {
* input.sendKeys(' hello');
* expect(input.getAttribute('value')).toEqual('say hello');
* input.sendKeys(protractor.Key.ESCAPE);
* expect(input.getAttribute('value')).toEqual('say');
* other.click();
* expect(model.getText()).toEqual('say');
* });
* </file>
* </example>
*
* The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
* If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
*
* <example name="ngModelOptions-directive-debounce" module="optionsExample">
* <file name="index.html">
* <div ng-controller="ExampleController">
* <form name="userForm">
* Name:
* <input type="text" name="userName"
* ng-model="user.name"
* ng-model-options="{ debounce: 1000 }" />
* <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
* </form>
* <pre>user.name = <span ng-bind="user.name"></span></pre>
* </div>
* </file>
* <file name="app.js">
* angular.module('optionsExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.user = { name: 'say' };
* }]);
* </file>
* </example>
*
* ## Model updates and validation
*
* The default behaviour in `ngModel` is that the model value is set to `null` when the validation
* determines that the value is invalid. By setting the `allowInvalid` property to true, the model
* will still be updated even if the value is invalid.
*
*
* ## Connecting to the scope
*
* By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
* on the scope refers to a "getter/setter" function rather than the value itself.
*
* The following example shows how to bind to getter/setters:
*
* <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
* <file name="index.html">
* <div ng-controller="ExampleController">
* <form name="userForm">
* Name:
* <input type="text" name="userName"
* ng-model="user.name"
* ng-model-options="{ getterSetter: true }" />
* </form>
* <pre>user.name = <span ng-bind="user.name()"></span></pre>
* </div>
* </file>
* <file name="app.js">
* angular.module('getterSetterExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* var _name = 'Brian';
* $scope.user = {
* name: function(newName) {
* return angular.isDefined(newName) ? (_name = newName) : _name;
* }
* };
* }]);
* </file>
* </example>
*
*
* ## Specifying timezones
*
* You can specify the timezone that date/time input directives expect by providing its name in the
* `timezone` property.
*
* @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
* - `updateOn`: string specifying which event should the input be bound to. You can set several
* events using an space delimited list. There is a special event called `default` that
* matches the default events belonging of the control.
* - `debounce`: integer value which contains the debounce model update value in milliseconds. A
* value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
* custom value for each event. For example:
* `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
* - `allowInvalid`: boolean value which indicates that the model can be set with values that did
* not validate correctly instead of the default behavior of setting the model to undefined.
* - `getterSetter`: boolean value which determines whether or not to treat functions bound to
* `ngModel` as getters/setters.
* - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
* `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
* continental US time zone abbreviations, but for general use, use a time zone offset, for
* example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
* If not specified, the timezone of the browser will be used.
*
*/
var ngModelOptionsDirective = ['$modelOptions', function($modelOptions) {
return {
restrict: 'A',
// ngModelOptions needs to run before ngModel and input directives
priority: 10,
require: ['ngModelOptions', '?^^ngModelOptions'],
controller: function NgModelOptionsController() {},
link: {
pre: function ngModelOptionsPreLinkFn(scope, element, attrs, ctrls) {
var optionsCtrl = ctrls[0];
var parentOptions = ctrls[1] ? ctrls[1].$options : $modelOptions;
optionsCtrl.$options = parentOptions.createChild(scope.$eval(attrs.ngModelOptions));
}
}
};
}];
/**
* @ngdoc provider
* @name $modelOptionsProvider
* @description
*
* Here, you can change the default settings from which {@link ngModelOptions}
* directives inherit.
*
* See the {@link ngModelOptions} directive for a list of the available options.
*/
function $ModelOptionsProvider() {
return {
/**
* @ngdoc property
* @name $modelOptionsProvider#defaultOptions
* @type {Object}
* @description
* The default options to fall back on when there are no more ngModelOption
* directives as ancestors.
* Use this property to specify the defaultOptions for the application as a whole.
*
* The initial default options are:
*
* * `updateOn`: `default`
* * `debounce`: `0`
* * `allowInvalid`: `undefined`
* * `getterSetter`: `undefined`
* * `timezone`: 'undefined'
*/
defaultOptions: {
updateOn: 'default',
debounce: 0
},
/**
* @ngdoc service
* @name $modelOptions
* @type ModelOptions
* @description
*
* This service provides the application wide default {@link ModelOptions} options that
* will be used by {@link ngModel} directives if no {@link ngModelOptions} directive is
* specified.
*/
$get: function() {
return new ModelOptions(this.defaultOptions);
}
};
}
/**
* @ngdoc type
* @name ModelOptions
* @description
* A container for the options set by the {@link ngModelOptions} directive
* and the {@link $modelOptions} service.
*/
var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
function ModelOptions(options, parentOptions) {
// Extend the parent's options with these new ones
var _options = extend({}, parentOptions, options);
// do extra processing on the options
// updateOn and updateOnDefault
if (isDefined(_options.updateOn) && _options.updateOn.trim()) {
_options.updateOnDefault = false;
// extract "default" pseudo-event from list of events that can trigger a model update
_options.updateOn = trim(_options.updateOn.replace(DEFAULT_REGEXP, function() {
_options.updateOnDefault = true;
return ' ';
}));
} else if (parentOptions) {
_options.updateOn = parentOptions.updateOn;
_options.updateOnDefault = parentOptions.updateOnDefault;
} else {
_options.updateOnDefault = true;
}
/**
* @ngdoc method
* @name ModelOptions#getOption
* @param {string} name the name of the option to retrieve
* @returns {*} the value of the option
* @description
* Returns the value of the given option
*/
this.getOption = function(name) { return _options[name]; };
/**
* @ngdoc method
* @name ModelOptions#createChild
* @param {Object} options a hash of options for the new child that will override the parent's options
* @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
*/
this.createChild = function(options) {
return new ModelOptions(options, _options);
};
}
// helper methods
function addSetValidityMethod(context) {
var ctrl = context.ctrl,
$element = context.$element,
classCache = {},
set = context.set,
unset = context.unset,
$animate = context.$animate;
classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
ctrl.$setValidity = setValidity;
function setValidity(validationErrorKey, state, controller) {
if (isUndefined(state)) {
createAndSet('$pending', validationErrorKey, controller);
} else {
unsetAndCleanup('$pending', validationErrorKey, controller);
}
if (!isBoolean(state)) {
unset(ctrl.$error, validationErrorKey, controller);
unset(ctrl.$$success, validationErrorKey, controller);
} else {
if (state) {
unset(ctrl.$error, validationErrorKey, controller);
set(ctrl.$$success, validationErrorKey, controller);
} else {
set(ctrl.$error, validationErrorKey, controller);
unset(ctrl.$$success, validationErrorKey, controller);
}
}
if (ctrl.$pending) {
cachedToggleClass(PENDING_CLASS, true);
ctrl.$valid = ctrl.$invalid = undefined;
toggleValidationCss('', null);
} else {
cachedToggleClass(PENDING_CLASS, false);
ctrl.$valid = isObjectEmpty(ctrl.$error);
ctrl.$invalid = !ctrl.$valid;
toggleValidationCss('', ctrl.$valid);
}
// re-read the state as the set/unset methods could have
// combined state in ctrl.$error[validationError] (used for forms),
// where setting/unsetting only increments/decrements the value,
// and does not replace it.
var combinedState;
if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
combinedState = undefined;
} else if (ctrl.$error[validationErrorKey]) {
combinedState = false;
} else if (ctrl.$$success[validationErrorKey]) {
combinedState = true;
} else {
combinedState = null;
}
toggleValidationCss(validationErrorKey, combinedState);
ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
}
function createAndSet(name, value, controller) {
if (!ctrl[name]) {
ctrl[name] = {};
}
set(ctrl[name], value, controller);
}
function unsetAndCleanup(name, value, controller) {
if (ctrl[name]) {
unset(ctrl[name], value, controller);
}
if (isObjectEmpty(ctrl[name])) {
ctrl[name] = undefined;
}
}
function cachedToggleClass(className, switchValue) {
if (switchValue && !classCache[className]) {
$animate.addClass($element, className);
classCache[className] = true;
} else if (!switchValue && classCache[className]) {
$animate.removeClass($element, className);
classCache[className] = false;
}
}
function toggleValidationCss(validationErrorKey, isValid) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
}
}
function isObjectEmpty(obj) {
if (obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
}
return true;
}
|
(function ($) {
'use strict';
var slickPrint = function () {
var self = this;
var grid;
this.init = function (pageGrid) {
grid = pageGrid;
};
this.printToHtml = function () {
var numRows = grid.getDataLength();
var columns = grid.getColumns();
var numCols = columns.length;
var r, c;
var rows = [], cols, headers = [];
var cellNode;
var topRow = grid.getRenderedRange().top;
angular.forEach(columns, function (col) {
var hAlign = col.cssClass ? (col.cssClass.indexOf("ColumnRightAlign") > -1 ? "right" : "left") : "left";
headers.push('<th nowrap="nowrap" align="' + hAlign + '">' + col.name + '</th>');
});
Slick.GlobalEditorLock.cancelCurrentEdit();
grid.scrollRowToTop(0);
for (r = 0; r < numRows; r++) {
cols = [];
for (c = 0; c < numCols; c++) {
cellNode = grid.getCellNode(r, c);
if (!cellNode) {
grid.scrollRowToTop(r);
cellNode = grid.getCellNode(r, c);
}
var bAlign = ($(cellNode).css("text-align") === undefined ? "left" : $(cellNode).css("text-align"));
cols.push('<td nowrap="nowrap"' + 'align="' + bAlign + '">' +
$(cellNode).text()+"</td>");
}
rows.push(cols.join(''));
}
var table = [
'<table class="table table-bordered">',
'<thead>',
'<tr>',
'' + headers.join('') + '',
'</tr>',
'</thead>',
'<tbody>',
'<tr>' + rows.join('</tr>\n<tr>') + '</tr>',
'</tbody>',
'</table>'
].join('\n');
grid.scrollRowToTop(topRow);
return table;
};
this.printToElement = function ($element) {
$($element).html(self.printToHtml());
};
this.printToWindow = function (w) {
w.onload = $.browser.msie ? new function () {
setTimeout(function () {
self.printToElement(w.document.body);
w.print();
w.close();
});
} : function () {
setTimeout(function () {
self.printToElement(w.document.body);
w.print();
w.close();
});
};
};
};
// register namespace
$.extend(true, window, {
Slick: {
Plugins: {
Print: slickPrint
}
}
});
}(jQuery));
|
/*
AngularJS v1.2.0-rc.3
(c) 2010-2012 Google, Inc. http://angularjs.org
License: MIT
*/
(function(Y, R, s) {
'use strict';
function D(b) {
return function() {
var a = arguments[0], c, a = "[" + (b ? b + ":" : "") + a + "] http://errors.angularjs.org/undefined/" + (b ? b + "/" : "") + a;
for (c = 1; c < arguments.length; c++)
a = a + (1 == c ? "?" : "&") + "p" + (c - 1) + "=" + encodeURIComponent("function" == typeof arguments[c] ? arguments[c].toString().replace(/ \{[\s\S]*$/, "") : "undefined" == typeof arguments[c] ? "undefined" : "string" != typeof arguments[c] ? JSON.stringify(arguments[c]) : arguments[c]);
return Error(a)
}
}
function nb(b) {
if (null == b || ya(b))
return!1;
var a = b.length;
return 1 === b.nodeType && a ? !0 : F(b) || H(b) || 0 === a || "number" === typeof a && 0 < a && a - 1 in b
}
function p(b, a, c) {
var d;
if (b)
if (E(b))
for (d in b)
"prototype" != d && ("length" != d && "name" != d && b.hasOwnProperty(d)) && a.call(c, b[d], d);
else if (b.forEach && b.forEach !== p)
b.forEach(a, c);
else if (nb(b))
for (d = 0; d < b.length; d++)
a.call(c, b[d], d);
else
for (d in b)
b.hasOwnProperty(d) && a.call(c, b[d], d);
return b
}
function Lb(b) {
var a = [], c;
for (c in b)
b.hasOwnProperty(c) && a.push(c);
return a.sort()
}
function Gc(b, a, c) {
for (var d =
Lb(b), e = 0; e < d.length; e++)
a.call(c, b[d[e]], d[e]);
return d
}
function Mb(b) {
return function(a, c) {
b(c, a)
}
}
function Va() {
for (var b = ia.length, a; b; ) {
b--;
a = ia[b].charCodeAt(0);
if (57 == a)
return ia[b] = "A", ia.join("");
if (90 == a)
ia[b] = "0";
else
return ia[b] = String.fromCharCode(a + 1), ia.join("")
}
ia.unshift("0");
return ia.join("")
}
function Nb(b, a) {
a ? b.$$hashKey = a : delete b.$$hashKey
}
function G(b) {
var a = b.$$hashKey;
p(arguments, function(a) {
a !== b && p(a, function(a, c) {
b[c] = a
})
});
Nb(b, a);
return b
}
function W(b) {
return parseInt(b,
10)
}
function Hc(b, a) {
return G(new (G(function() {
}, {prototype: b})), a)
}
function v() {
}
function za(b) {
return b
}
function aa(b) {
return function() {
return b
}
}
function z(b) {
return"undefined" == typeof b
}
function w(b) {
return"undefined" != typeof b
}
function S(b) {
return null != b && "object" == typeof b
}
function F(b) {
return"string" == typeof b
}
function ob(b) {
return"number" == typeof b
}
function Ha(b) {
return"[object Date]" == Wa.apply(b)
}
function H(b) {
return"[object Array]" == Wa.apply(b)
}
function E(b) {
return"function" == typeof b
}
function Xa(b) {
return"[object RegExp]" == Wa.apply(b)
}
function ya(b) {
return b && b.document && b.location && b.alert && b.setInterval
}
function Ic(b) {
return b && (b.nodeName || b.on && b.find)
}
function Jc(b, a, c) {
var d = [];
p(b, function(b, f, g) {
d.push(a.call(c, b, f, g))
});
return d
}
function Ya(b, a) {
if (b.indexOf)
return b.indexOf(a);
for (var c = 0; c < b.length; c++)
if (a === b[c])
return c;
return-1
}
function Ia(b, a) {
var c = Ya(b, a);
0 <= c && b.splice(c, 1);
return a
}
function fa(b, a) {
if (ya(b) || b && b.$evalAsync && b.$watch)
throw Ja("cpws");
if (a) {
if (b ===
a)
throw Ja("cpi");
if (H(b))
for (var c = a.length = 0; c < b.length; c++)
a.push(fa(b[c]));
else {
c = a.$$hashKey;
p(a, function(b, c) {
delete a[c]
});
for (var d in b)
a[d] = fa(b[d]);
Nb(a, c)
}
} else
(a = b) && (H(b) ? a = fa(b, []) : Ha(b) ? a = new Date(b.getTime()) : Xa(b) ? a = RegExp(b.source) : S(b) && (a = fa(b, {})));
return a
}
function Kc(b, a) {
a = a || {};
for (var c in b)
b.hasOwnProperty(c) && "$$" !== c.substr(0, 2) && (a[c] = b[c]);
return a
}
function Aa(b, a) {
if (b === a)
return!0;
if (null === b || null === a)
return!1;
if (b !== b && a !== a)
return!0;
var c = typeof b, d;
if (c == typeof a &&
"object" == c)
if (H(b)) {
if (!H(a))
return!1;
if ((c = b.length) == a.length) {
for (d = 0; d < c; d++)
if (!Aa(b[d], a[d]))
return!1;
return!0
}
} else {
if (Ha(b))
return Ha(a) && b.getTime() == a.getTime();
if (Xa(b) && Xa(a))
return b.toString() == a.toString();
if (b && b.$evalAsync && b.$watch || a && a.$evalAsync && a.$watch || ya(b) || ya(a) || H(a))
return!1;
c = {};
for (d in b)
if ("$" !== d.charAt(0) && !E(b[d])) {
if (!Aa(b[d], a[d]))
return!1;
c[d] = !0
}
for (d in a)
if (!c.hasOwnProperty(d) && "$" !== d.charAt(0) && a[d] !== s && !E(a[d]))
return!1;
return!0
}
return!1
}
function pb(b,
a) {
var c = 2 < arguments.length ? ua.call(arguments, 2) : [];
return!E(a) || a instanceof RegExp ? a : c.length ? function() {
return arguments.length ? a.apply(b, c.concat(ua.call(arguments, 0))) : a.apply(b, c)
} : function() {
return arguments.length ? a.apply(b, arguments) : a.call(b)
}
}
function Lc(b, a) {
var c = a;
"string" === typeof b && "$" === b.charAt(0) ? c = s : ya(a) ? c = "$WINDOW" : a && R === a ? c = "$DOCUMENT" : a && (a.$evalAsync && a.$watch) && (c = "$SCOPE");
return c
}
function oa(b, a) {
return"undefined" === typeof b ? s : JSON.stringify(b, Lc, a ? " " : null)
}
function Ob(b) {
return F(b) ?
JSON.parse(b) : b
}
function Ka(b) {
b && 0 !== b.length ? (b = B("" + b), b = !("f" == b || "0" == b || "false" == b || "no" == b || "n" == b || "[]" == b)) : b = !1;
return b
}
function ga(b) {
b = x(b).clone();
try {
b.html("")
} catch (a) {
}
var c = x("<div>").append(b).html();
try {
return 3 === b[0].nodeType ? B(c) : c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/, function(a, b) {
return"<" + B(b)
})
} catch (d) {
return B(c)
}
}
function Pb(b) {
try {
return decodeURIComponent(b)
} catch (a) {
}
}
function Qb(b) {
var a = {}, c, d;
p((b || "").split("&"), function(b) {
b && (c = b.split("="), d = Pb(c[0]),
w(d) && (b = w(c[1]) ? Pb(c[1]) : !0, a[d] ? H(a[d]) ? a[d].push(b) : a[d] = [a[d], b] : a[d] = b))
});
return a
}
function Rb(b) {
var a = [];
p(b, function(b, d) {
H(b) ? p(b, function(b) {
a.push(va(d, !0) + (!0 === b ? "" : "=" + va(b, !0)))
}) : a.push(va(d, !0) + (!0 === b ? "" : "=" + va(b, !0)))
});
return a.length ? a.join("&") : ""
}
function qb(b) {
return va(b, !0).replace(/%26/gi, "&").replace(/%3D/gi, "=").replace(/%2B/gi, "+")
}
function va(b, a) {
return encodeURIComponent(b).replace(/%40/gi, "@").replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g,
a ? "%20" : "+")
}
function Mc(b, a) {
function c(a) {
a && d.push(a)
}
var d = [b], e, f, g = ["ng:app", "ng-app", "x-ng-app", "data-ng-app"], h = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
p(g, function(a) {
g[a] = !0;
c(R.getElementById(a));
a = a.replace(":", "\\:");
b.querySelectorAll && (p(b.querySelectorAll("." + a), c), p(b.querySelectorAll("." + a + "\\:"), c), p(b.querySelectorAll("[" + a + "]"), c))
});
p(d, function(a) {
if (!e) {
var b = h.exec(" " + a.className + " ");
b ? (e = a, f = (b[2] || "").replace(/\s+/g, ",")) : p(a.attributes, function(b) {
!e && g[b.name] && (e = a, f = b.value)
})
}
});
e && a(e, f ? [f] : [])
}
function Sb(b, a) {
var c = function() {
b = x(b);
if (b.injector()) {
var c = b[0] === R ? "document" : ga(b);
throw Ja("btstrpd", c);
}
a = a || [];
a.unshift(["$provide", function(a) {
a.value("$rootElement", b)
}]);
a.unshift("ng");
c = Tb(a);
c.invoke(["$rootScope", "$rootElement", "$compile", "$injector", "$animate", function(a, b, c, d, e) {
a.$apply(function() {
b.data("$injector", d);
c(b)(a)
});
e.enabled(!0)
}]);
return c
}, d = /^NG_DEFER_BOOTSTRAP!/;
if (Y && !d.test(Y.name))
return c();
Y.name = Y.name.replace(d, "");
Za.resumeBootstrap =
function(b) {
p(b, function(b) {
a.push(b)
});
c()
}
}
function $a(b, a) {
a = a || "_";
return b.replace(Nc, function(b, d) {
return(d ? a : "") + b.toLowerCase()
})
}
function rb(b, a, c) {
if (!b)
throw Ja("areq", a || "?", c || "required");
return b
}
function La(b, a, c) {
c && H(b) && (b = b[b.length - 1]);
rb(E(b), a, "not a function, got " + (b && "object" == typeof b ? b.constructor.name || "Object" : typeof b));
return b
}
function pa(b, a) {
if ("hasOwnProperty" === b)
throw Ja("badname", a);
}
function sb(b, a, c) {
if (!a)
return b;
a = a.split(".");
for (var d, e = b, f = a.length, g =
0; g < f; g++)
d = a[g], b && (b = (e = b)[d]);
return!c && E(b) ? pb(e, b) : b
}
function Oc(b) {
function a(a, b, c) {
return a[b] || (a[b] = c())
}
var c = D("$injector");
return a(a(b, "angular", Object), "module", function() {
var b = {};
return function(e, f, g) {
pa(e, "module");
f && b.hasOwnProperty(e) && (b[e] = null);
return a(b, e, function() {
function a(c, d, e) {
return function() {
b[e || "push"]([c, d, arguments]);
return r
}
}
if (!f)
throw c("nomod", e);
var b = [], d = [], l = a("$injector", "invoke"), r = {_invokeQueue: b, _runBlocks: d, requires: f, name: e, provider: a("$provide",
"provider"), factory: a("$provide", "factory"), service: a("$provide", "service"), value: a("$provide", "value"), constant: a("$provide", "constant", "unshift"), animation: a("$animateProvider", "register"), filter: a("$filterProvider", "register"), controller: a("$controllerProvider", "register"), directive: a("$compileProvider", "directive"), config: l, run: function(a) {
d.push(a);
return this
}};
g && l(g);
return r
})
}
})
}
function Ma(b) {
return b.replace(Pc, function(a, b, d, e) {
return e ? d.toUpperCase() : d
}).replace(Qc, "Moz$1")
}
function tb(b,
a, c, d) {
function e(b) {
var e = c && b ? [this.filter(b)] : [this], m = a, k, l, r, q, n, y;
if (!d || null != b)
for (; e.length; )
for (k = e.shift(), l = 0, r = k.length; l < r; l++)
for (q = x(k[l]), m?q.triggerHandler("$destroy"):m = !m, n = 0, q = (y = q.children()).length; n < q; n++)
e.push(Ba(y[n]));
return f.apply(this, arguments)
}
var f = Ba.fn[b], f = f.$original || f;
e.$original = f;
Ba.fn[b] = e
}
function J(b) {
if (b instanceof J)
return b;
if (!(this instanceof J)) {
if (F(b) && "<" != b.charAt(0))
throw ub("nosel");
return new J(b)
}
if (F(b)) {
var a = R.createElement("div");
a.innerHTML =
"<div> </div>" + b;
a.removeChild(a.firstChild);
vb(this, a.childNodes);
x(R.createDocumentFragment()).append(this)
} else
vb(this, b)
}
function wb(b) {
return b.cloneNode(!0)
}
function Na(b) {
Ub(b);
var a = 0;
for (b = b.childNodes || []; a < b.length; a++)
Na(b[a])
}
function Vb(b, a, c, d) {
if (w(d))
throw ub("offargs");
var e = ja(b, "events");
ja(b, "handle") && (z(a) ? p(e, function(a, c) {
xb(b, c, a);
delete e[c]
}) : p(a.split(" "), function(a) {
z(c) ? (xb(b, a, e[a]), delete e[a]) : Ia(e[a] || [], c)
}))
}
function Ub(b, a) {
var c = b[ab], d = Oa[c];
d && (a ? delete Oa[c].data[a] :
(d.handle && (d.events.$destroy && d.handle({}, "$destroy"), Vb(b)), delete Oa[c], b[ab] = s))
}
function ja(b, a, c) {
var d = b[ab], d = Oa[d || -1];
if (w(c))
d || (b[ab] = d = ++Rc, d = Oa[d] = {}), d[a] = c;
else
return d && d[a]
}
function Wb(b, a, c) {
var d = ja(b, "data"), e = w(c), f = !e && w(a), g = f && !S(a);
d || g || ja(b, "data", d = {});
if (e)
d[a] = c;
else if (f) {
if (g)
return d && d[a];
G(d, a)
} else
return d
}
function yb(b, a) {
return b.getAttribute ? -1 < (" " + (b.getAttribute("class") || "") + " ").replace(/[\n\t]/g, " ").indexOf(" " + a + " ") : !1
}
function zb(b, a) {
a && b.setAttribute &&
p(a.split(" "), function(a) {
b.setAttribute("class", ba((" " + (b.getAttribute("class") || "") + " ").replace(/[\n\t]/g, " ").replace(" " + ba(a) + " ", " ")))
})
}
function Ab(b, a) {
if (a && b.setAttribute) {
var c = (" " + (b.getAttribute("class") || "") + " ").replace(/[\n\t]/g, " ");
p(a.split(" "), function(a) {
a = ba(a);
-1 === c.indexOf(" " + a + " ") && (c += a + " ")
});
b.setAttribute("class", ba(c))
}
}
function vb(b, a) {
if (a) {
a = a.nodeName || !w(a.length) || ya(a) ? [a] : a;
for (var c = 0; c < a.length; c++)
b.push(a[c])
}
}
function Xb(b, a) {
return bb(b, "$" + (a ||
"ngController") + "Controller")
}
function bb(b, a, c) {
b = x(b);
for (9 == b[0].nodeType && (b = b.find("html")); b.length; ) {
if ((c = b.data(a)) !== s)
return c;
b = b.parent()
}
}
function Yb(b, a) {
var c = cb[a.toLowerCase()];
return c && Zb[b.nodeName] && c
}
function Sc(b, a) {
var c = function(c, e) {
c.preventDefault || (c.preventDefault = function() {
c.returnValue = !1
});
c.stopPropagation || (c.stopPropagation = function() {
c.cancelBubble = !0
});
c.target || (c.target = c.srcElement || R);
if (z(c.defaultPrevented)) {
var f = c.preventDefault;
c.preventDefault = function() {
c.defaultPrevented =
!0;
f.call(c)
};
c.defaultPrevented = !1
}
c.isDefaultPrevented = function() {
return c.defaultPrevented || !1 == c.returnValue
};
p(a[e || c.type], function(a) {
a.call(b, c)
});
8 >= Q ? (c.preventDefault = null, c.stopPropagation = null, c.isDefaultPrevented = null) : (delete c.preventDefault, delete c.stopPropagation, delete c.isDefaultPrevented)
};
c.elem = b;
return c
}
function Ca(b) {
var a = typeof b, c;
"object" == a && null !== b ? "function" == typeof (c = b.$$hashKey) ? c = b.$$hashKey() : c === s && (c = b.$$hashKey = Va()) : c = b;
return a + ":" + c
}
function Pa(b) {
p(b,
this.put, this)
}
function $b(b) {
var a, c;
"function" == typeof b ? (a = b.$inject) || (a = [], b.length && (c = b.toString().replace(Tc, ""), c = c.match(Uc), p(c[1].split(Vc), function(b) {
b.replace(Wc, function(b, c, d) {
a.push(d)
})
})), b.$inject = a) : H(b) ? (c = b.length - 1, La(b[c], "fn"), a = b.slice(0, c)) : La(b, "fn", !0);
return a
}
function Tb(b) {
function a(a) {
return function(b, c) {
if (S(b))
p(b, Mb(a));
else
return a(b, c)
}
}
function c(a, b) {
pa(a, "service");
if (E(b) || H(b))
b = r.instantiate(b);
if (!b.$get)
throw Qa("pget", a);
return l[a + h] = b
}
function d(a,
b) {
return c(a, {$get: b})
}
function e(a) {
var b = [];
p(a, function(a) {
if (!k.get(a)) {
k.put(a, !0);
try {
if (F(a)) {
var c = Ra(a);
b = b.concat(e(c.requires)).concat(c._runBlocks);
for (var d = c._invokeQueue, c = 0, f = d.length; c < f; c++) {
var h = d[c], g = r.get(h[0]);
g[h[1]].apply(g, h[2])
}
} else
E(a) ? b.push(r.invoke(a)) : H(a) ? b.push(r.invoke(a)) : La(a, "module")
} catch (m) {
throw H(a) && (a = a[a.length - 1]), m.message && (m.stack && -1 == m.stack.indexOf(m.message)) && (m = m.message + "\n" + m.stack), Qa("modulerr", a, m.stack || m.message || m);
}
}
});
return b
}
function f(a, b) {
function c(d) {
if (a.hasOwnProperty(d)) {
if (a[d] === g)
throw Qa("cdep", m.join(" <- "));
return a[d]
}
try {
return m.unshift(d), a[d] = g, a[d] = b(d)
} finally {
m.shift()
}
}
function d(a, b, e) {
var f = [], k = $b(a), h, g, m;
g = 0;
for (h = k.length; g < h; g++) {
m = k[g];
if ("string" !== typeof m)
throw Qa("itkn", m);
f.push(e && e.hasOwnProperty(m) ? e[m] : c(m))
}
a.$inject || (a = a[h]);
switch (b ? -1 : f.length) {
case 0:
return a();
case 1:
return a(f[0]);
case 2:
return a(f[0], f[1]);
case 3:
return a(f[0], f[1], f[2]);
case 4:
return a(f[0], f[1], f[2],
f[3]);
case 5:
return a(f[0], f[1], f[2], f[3], f[4]);
case 6:
return a(f[0], f[1], f[2], f[3], f[4], f[5]);
case 7:
return a(f[0], f[1], f[2], f[3], f[4], f[5], f[6]);
case 8:
return a(f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]);
case 9:
return a(f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8]);
case 10:
return a(f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9]);
default:
return a.apply(b, f)
}
}
return{invoke: d, instantiate: function(a, b) {
var c = function() {
}, e;
c.prototype = (H(a) ? a[a.length - 1] : a).prototype;
c = new c;
e = d(a, c, b);
return S(e) ?
e : c
}, get: c, annotate: $b, has: function(b) {
return l.hasOwnProperty(b + h) || a.hasOwnProperty(b)
}}
}
var g = {}, h = "Provider", m = [], k = new Pa, l = {$provide: {provider: a(c), factory: a(d), service: a(function(a, b) {
return d(a, ["$injector", function(a) {
return a.instantiate(b)
}])
}), value: a(function(a, b) {
return d(a, aa(b))
}), constant: a(function(a, b) {
pa(a, "constant");
l[a] = b;
q[a] = b
}), decorator: function(a, b) {
var c = r.get(a + h), d = c.$get;
c.$get = function() {
var a = n.invoke(d, c);
return n.invoke(b, null, {$delegate: a})
}
}}}, r = l.$injector = f(l,
function() {
throw Qa("unpr", m.join(" <- "));
}), q = {}, n = q.$injector = f(q, function(a) {
a = r.get(a + h);
return n.invoke(a.$get, a)
});
p(e(b), function(a) {
n.invoke(a || v)
});
return n
}
function Xc() {
var b = !0;
this.disableAutoScrolling = function() {
b = !1
};
this.$get = ["$window", "$location", "$rootScope", function(a, c, d) {
function e(a) {
var b = null;
p(a, function(a) {
b || "a" !== B(a.nodeName) || (b = a)
});
return b
}
function f() {
var b = c.hash(), d;
b ? (d = g.getElementById(b)) ? d.scrollIntoView() : (d = e(g.getElementsByName(b))) ? d.scrollIntoView() :
"top" === b && a.scrollTo(0, 0) : a.scrollTo(0, 0)
}
var g = a.document;
b && d.$watch(function() {
return c.hash()
}, function() {
d.$evalAsync(f)
});
return f
}]
}
function Yc(b, a, c, d) {
function e(a) {
try {
a.apply(null, ua.call(arguments, 1))
} finally {
if (y--, 0 === y)
for (; A.length; )
try {
A.pop()()
} catch (b) {
c.error(b)
}
}
}
function f(a, b) {
(function Bb() {
p(C, function(a) {
a()
});
u = b(Bb, a)
})()
}
function g() {
t = null;
U != h.url() && (U = h.url(), p(T, function(a) {
a(h.url())
}))
}
var h = this, m = a[0], k = b.location, l = b.history, r = b.setTimeout, q = b.clearTimeout,
n = {};
h.isMock = !1;
var y = 0, A = [];
h.$$completeOutstandingRequest = e;
h.$$incOutstandingRequestCount = function() {
y++
};
h.notifyWhenNoOutstandingRequests = function(a) {
p(C, function(a) {
a()
});
0 === y ? a() : A.push(a)
};
var C = [], u;
h.addPollFn = function(a) {
z(u) && f(100, r);
C.push(a);
return a
};
var U = k.href, M = a.find("base"), t = null;
h.url = function(a, c) {
k !== b.location && (k = b.location);
if (a) {
if (U != a)
return U = a, d.history ? c ? l.replaceState(null, "", a) : (l.pushState(null, "", a), M.attr("href", M.attr("href"))) : (t = a, c ? k.replace(a) : k.href =
a), h
} else
return t || k.href.replace(/%27/g, "'")
};
var T = [], ca = !1;
h.onUrlChange = function(a) {
if (!ca) {
if (d.history)
x(b).on("popstate", g);
if (d.hashchange)
x(b).on("hashchange", g);
else
h.addPollFn(g);
ca = !0
}
T.push(a);
return a
};
h.baseHref = function() {
var a = M.attr("href");
return a ? a.replace(/^https?\:\/\/[^\/]*/, "") : ""
};
var N = {}, da = "", ka = h.baseHref();
h.cookies = function(a, b) {
var d, e, f, k;
if (a)
b === s ? m.cookie = escape(a) + "=;path=" + ka + ";expires=Thu, 01 Jan 1970 00:00:00 GMT" : F(b) && (d = (m.cookie = escape(a) + "=" + escape(b) +
";path=" + ka).length + 1, 4096 < d && c.warn("Cookie '" + a + "' possibly not set or overflowed because it was too large (" + d + " > 4096 bytes)!"));
else {
if (m.cookie !== da)
for (da = m.cookie, d = da.split("; "), N = {}, f = 0; f < d.length; f++)
e = d[f], k = e.indexOf("="), 0 < k && (a = unescape(e.substring(0, k)), N[a] === s && (N[a] = unescape(e.substring(k + 1))));
return N
}
};
h.defer = function(a, b) {
var c;
y++;
c = r(function() {
delete n[c];
e(a)
}, b || 0);
n[c] = !0;
return c
};
h.defer.cancel = function(a) {
return n[a] ? (delete n[a], q(a), e(v), !0) : !1
}
}
function Zc() {
this.$get =
["$window", "$log", "$sniffer", "$document", function(b, a, c, d) {
return new Yc(b, d, a, c)
}]
}
function $c() {
this.$get = function() {
function b(b, d) {
function e(a) {
a != r && (q ? q == a && (q = a.n) : q = a, f(a.n, a.p), f(a, r), r = a, r.n = null)
}
function f(a, b) {
a != b && (a && (a.p = b), b && (b.n = a))
}
if (b in a)
throw D("$cacheFactory")("iid", b);
var g = 0, h = G({}, d, {id: b}), m = {}, k = d && d.capacity || Number.MAX_VALUE, l = {}, r = null, q = null;
return a[b] = {put: function(a, b) {
var c = l[a] || (l[a] = {key: a});
e(c);
if (!z(b))
return a in m || g++, m[a] = b, g > k && this.remove(q.key),
b
}, get: function(a) {
var b = l[a];
if (b)
return e(b), m[a]
}, remove: function(a) {
var b = l[a];
b && (b == r && (r = b.p), b == q && (q = b.n), f(b.n, b.p), delete l[a], delete m[a], g--)
}, removeAll: function() {
m = {};
g = 0;
l = {};
r = q = null
}, destroy: function() {
l = h = m = null;
delete a[b]
}, info: function() {
return G({}, h, {size: g})
}}
}
var a = {};
b.info = function() {
var b = {};
p(a, function(a, e) {
b[e] = a.info()
});
return b
};
b.get = function(b) {
return a[b]
};
return b
}
}
function ad() {
this.$get = ["$cacheFactory", function(b) {
return b("templates")
}]
}
function bc(b) {
var a =
{}, c = "Directive", d = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, e = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, f = /^\s*(https?|ftp|mailto|tel|file):/, g = /^\s*(https?|ftp|file):|data:image\//, h = /^(on[a-z]+|formaction)$/;
this.directive = function k(d, e) {
pa(d, "directive");
F(d) ? (rb(e, "directiveFactory"), a.hasOwnProperty(d) || (a[d] = [], b.factory(d + c, ["$injector", "$exceptionHandler", function(b, c) {
var e = [];
p(a[d], function(a, f) {
try {
var k = b.invoke(a);
E(k) ? k = {compile: aa(k)} : !k.compile && k.link && (k.compile = aa(k.link));
k.priority =
k.priority || 0;
k.index = f;
k.name = k.name || d;
k.require = k.require || k.controller && k.name;
k.restrict = k.restrict || "A";
e.push(k)
} catch (g) {
c(g)
}
});
return e
}])), a[d].push(e)) : p(d, Mb(k));
return this
};
this.aHrefSanitizationWhitelist = function(a) {
return w(a) ? (f = a, this) : f
};
this.imgSrcSanitizationWhitelist = function(a) {
return w(a) ? (g = a, this) : g
};
this.$get = ["$injector", "$interpolate", "$exceptionHandler", "$http", "$templateCache", "$parse", "$controller", "$rootScope", "$document", "$sce", "$animate", function(b, l, r, q, n, y, A,
C, u, U, M) {
function t(a, b, c, d, e) {
a instanceof x || (a = x(a));
p(a, function(b, c) {
3 == b.nodeType && b.nodeValue.match(/\S+/) && (a[c] = x(b).wrap("<span></span>").parent()[0])
});
var f = ca(a, b, a, c, d, e);
return function(b, c) {
rb(b, "scope");
for (var d = c ? Sa.clone.call(a) : a, e = 0, k = d.length; e < k; e++) {
var g = d[e];
1 != g.nodeType && 9 != g.nodeType || d.eq(e).data("$scope", b)
}
T(d, "ng-scope");
c && c(d, b);
f && f(b, d, d);
return d
}
}
function T(a, b) {
try {
a.addClass(b)
} catch (c) {
}
}
function ca(a, b, c, d, e, f) {
function k(a, c, d, e) {
var f, h, l, r, n, q, y, $ = [];
n = 0;
for (q = c.length; n < q; n++)
$.push(c[n]);
y = n = 0;
for (q = g.length; n < q; y++)
h = $[y], c = g[n++], f = g[n++], c ? (c.scope ? (l = a.$new(S(c.scope)), x(h).data("$scope", l)) : l = a, (r = c.transclude) || !e && b ? c(f, l, h, d, function(b) {
return function(c) {
var d = a.$new();
d.$$transcluded = !0;
return b(d, c).on("$destroy", pb(d, d.$destroy))
}
}(r || b)) : c(f, l, h, s, e)) : f && f(a, h.childNodes, s, e)
}
for (var g = [], h, l, r, n = 0; n < a.length; n++)
l = new z, h = N(a[n], [], l, 0 == n ? d : s, e), h = (f = h.length ? L(h, a[n], l, b, c, null, [], [], f) : null) && f.terminal || !a[n].childNodes || !a[n].childNodes.length ?
null : ca(a[n].childNodes, f ? f.transclude : b), g.push(f), g.push(h), r = r || f || h, f = null;
return r ? k : null
}
function N(a, b, c, f, k) {
var g = c.$attr, h;
switch (a.nodeType) {
case 1:
Z(b, la(Da(a).toLowerCase()), "E", f, k);
var l, r, n;
h = a.attributes;
for (var q = 0, y = h && h.length; q < y; q++) {
var A = !1, p = !1;
l = h[q];
if (!Q || 8 <= Q || l.specified) {
r = l.name;
n = la(r);
ma.test(n) && (r = $a(n.substr(6), "-"));
var t = n.replace(/(Start|End)$/, "");
n === t + "Start" && (A = r, p = r.substr(0, r.length - 5) + "end", r = r.substr(0, r.length - 6));
n = la(r.toLowerCase());
g[n] = r;
c[n] =
l = ba(Q && "href" == r ? decodeURIComponent(a.getAttribute(r, 2)) : l.value);
Yb(a, n) && (c[n] = !0);
B(a, b, l, n);
Z(b, n, "A", f, k, A, p)
}
}
a = a.className;
if (F(a) && "" !== a)
for (; h = e.exec(a); )
n = la(h[2]), Z(b, n, "C", f, k) && (c[n] = ba(h[3])), a = a.substr(h.index + h[0].length);
break;
case 3:
w(b, a.nodeValue);
break;
case 8:
try {
if (h = d.exec(a.nodeValue))
n = la(h[1]), Z(b, n, "M", f, k) && (c[n] = ba(h[2]))
} catch (U) {
}
}
b.sort(O);
return b
}
function da(a, b, c) {
var d = [], e = 0;
if (b && a.hasAttribute && a.hasAttribute(b)) {
do {
if (!a)
throw ha("uterdir", b, c);
1 == a.nodeType &&
(a.hasAttribute(b) && e++, a.hasAttribute(c) && e--);
d.push(a);
a = a.nextSibling
} while (0 < e)
} else
d.push(a);
return x(d)
}
function ka(a, b, c) {
return function(d, e, f, k) {
e = da(e[0], b, c);
return a(d, e, f, k)
}
}
function L(a, b, c, d, e, f, k, h, g) {
function n(a, b, c, d) {
a && (c && (a = ka(a, c, d)), a.require = I.require, k.push(a));
b && (c && (b = ka(b, c, d)), b.require = I.require, h.push(b))
}
function q(a, b) {
var c, d = "data", e = !1;
if (F(a)) {
for (; "^" == (c = a.charAt(0)) || "?" == c; )
a = a.substr(1), "^" == c && (d = "inheritedData"), e = e || "?" == c;
c = b[d]("$" + a + "Controller");
8 == b[0].nodeType && b[0].$$controller && (c = c || b[0].$$controller, b[0].$$controller = null);
if (!c && !e)
throw ha("ctreq", a, Z);
} else
H(a) && (c = [], p(a, function(a) {
c.push(q(a, b))
}));
return c
}
function U(a, d, e, f, g) {
var n, $, t, C, T;
n = b === e ? c : Kc(c, new z(x(e), c.$attr));
$ = n.$$element;
if (u) {
var ca = /^\s*([@=&])(\??)\s*(\w*)\s*$/, N = d.$parent || d;
p(u.scope, function(a, b) {
var c = a.match(ca) || [], e = c[3] || b, f = "?" == c[2], c = c[1], k, g, h;
d.$$isolateBindings[b] = c + e;
switch (c) {
case "@":
n.$observe(e, function(a) {
d[b] = a
});
n.$$observers[e].$$scope =
N;
n[e] && (d[b] = l(n[e])(N));
break;
case "=":
if (f && !n[e])
break;
g = y(n[e]);
h = g.assign || function() {
k = d[b] = g(N);
throw ha("nonassign", n[e], u.name);
};
k = d[b] = g(N);
d.$watch(function() {
var a = g(N);
a !== d[b] && (a !== k ? k = d[b] = a : h(N, a = k = d[b]));
return a
});
break;
case "&":
g = y(n[e]);
d[b] = function(a) {
return g(N, a)
};
break;
default:
throw ha("iscp", u.name, b, a);
}
})
}
v && p(v, function(a) {
var b = {$scope: d, $element: $, $attrs: n, $transclude: g}, c;
T = a.controller;
"@" == T && (T = n[a.name]);
c = A(T, b);
8 == $[0].nodeType ? $[0].$$controller = c : $.data("$" +
a.name + "Controller", c);
a.controllerAs && (b.$scope[a.controllerAs] = c)
});
f = 0;
for (t = k.length; f < t; f++)
try {
C = k[f], C(d, $, n, C.require && q(C.require, $))
} catch (L) {
r(L, ga($))
}
a && a(d, e.childNodes, s, g);
for (f = h.length - 1; 0 <= f; f--)
try {
C = h[f], C(d, $, n, C.require && q(C.require, $))
} catch (ka) {
r(ka, ga($))
}
}
g = g || {};
var C = -Number.MAX_VALUE, ca, u = g.newIsolateScopeDirective, M = g.templateDirective, L = c.$$element = x(b), I, Z, w;
g = g.transcludeDirective;
for (var O = d, v, B, ma = 0, K = a.length; ma < K; ma++) {
I = a[ma];
var G = I.$$start, D = I.$$end;
G && (L =
da(b, G, D));
w = s;
if (C > I.priority)
break;
if (w = I.scope)
ca = ca || I, I.templateUrl || (P("new/isolated scope", u, I, L), S(w) && (T(L, "ng-isolate-scope"), u = I), T(L, "ng-scope"));
Z = I.name;
!I.templateUrl && I.controller && (w = I.controller, v = v || {}, P("'" + Z + "' controller", v[Z], I, L), v[Z] = I);
if (w = I.transclude)
"ngRepeat" !== Z && (P("transclusion", g, I, L), g = I), "element" == w ? (C = I.priority, w = da(b, G, D), L = c.$$element = x(R.createComment(" " + Z + ": " + c[Z] + " ")), b = L[0], db(e, x(ua.call(w, 0)), b), O = t(w, d, C, f && f.name, {newIsolateScopeDirective: u, transcludeDirective: g,
templateDirective: M})) : (w = x(wb(b)).contents(), L.html(""), O = t(w, d));
if (I.template)
if (P("template", M, I, L), M = I, w = E(I.template) ? I.template(L, c) : I.template, w = cc(w), I.replace) {
f = I;
w = x("<div>" + ba(w) + "</div>").contents();
b = w[0];
if (1 != w.length || 1 !== b.nodeType)
throw ha("tplrt", Z, "");
db(e, L, b);
K = {$attr: {}};
a = a.concat(N(b, a.splice(ma + 1, a.length - (ma + 1)), K));
ac(c, K);
K = a.length
} else
L.html(w);
if (I.templateUrl)
P("template", M, I, L), M = I, I.replace && (f = I), U = Bb(a.splice(ma, a.length - ma), L, c, e, O, k, h, {newIsolateScopeDirective: u,
transcludeDirective: g, templateDirective: M}), K = a.length;
else if (I.compile)
try {
B = I.compile(L, c, O), E(B) ? n(null, B, G, D) : B && n(B.pre, B.post, G, D)
} catch (J) {
r(J, ga(L))
}
I.terminal && (U.terminal = !0, C = Math.max(C, I.priority))
}
U.scope = ca && ca.scope;
U.transclude = g && O;
return U
}
function Z(d, e, f, g, h, l, n) {
if (e === h)
return null;
h = null;
if (a.hasOwnProperty(e)) {
var q;
e = b.get(e + c);
for (var y = 0, A = e.length; y < A; y++)
try {
q = e[y], (g === s || g > q.priority) && -1 != q.restrict.indexOf(f) && (l && (q = Hc(q, {$$start: l, $$end: n})), d.push(q), h = q)
} catch (C) {
r(C)
}
}
return h
}
function ac(a, b) {
var c = b.$attr, d = a.$attr, e = a.$$element;
p(a, function(d, e) {
"$" != e.charAt(0) && (b[e] && (d += ("style" === e ? ";" : " ") + b[e]), a.$set(e, d, !0, c[e]))
});
p(b, function(b, f) {
"class" == f ? (T(e, b), a["class"] = (a["class"] ? a["class"] + " " : "") + b) : "style" == f ? e.attr("style", e.attr("style") + ";" + b) : "$" == f.charAt(0) || a.hasOwnProperty(f) || (a[f] = b, d[f] = c[f])
})
}
function Bb(a, b, c, d, e, f, k, g) {
var h = [], l, r, y = b[0], A = a.shift(), C = G({}, A, {templateUrl: null, transclude: null, replace: null}), t = E(A.templateUrl) ? A.templateUrl(b, c) :
A.templateUrl;
b.html("");
q.get(U.getTrustedResourceUrl(t), {cache: n}).success(function(n) {
var q;
n = cc(n);
if (A.replace) {
n = x("<div>" + ba(n) + "</div>").contents();
q = n[0];
if (1 != n.length || 1 !== q.nodeType)
throw ha("tplrt", A.name, t);
n = {$attr: {}};
db(d, b, q);
N(q, a, n);
ac(c, n)
} else
q = y, b.html(n);
a.unshift(C);
l = L(a, q, c, e, b, A, f, k, g);
p(d, function(a, c) {
a == q && (d[c] = b[0])
});
for (r = ca(b[0].childNodes, e); h.length; ) {
n = h.shift();
var U = h.shift(), T = h.shift(), s = h.shift(), u = b[0];
U !== y && (u = wb(q), db(T, x(U), u));
l(r, n, u, d, s)
}
h = null
}).error(function(a,
b, c, d) {
throw ha("tpload", d.url);
});
return function(a, b, c, d, e) {
h ? (h.push(b), h.push(c), h.push(d), h.push(e)) : l(r, b, c, d, e)
}
}
function O(a, b) {
var c = b.priority - a.priority;
return 0 !== c ? c : a.name !== b.name ? a.name < b.name ? -1 : 1 : a.index - b.index
}
function P(a, b, c, d) {
if (b)
throw ha("multidir", b.name, c.name, a, ga(d));
}
function w(a, b) {
var c = l(b, !0);
c && a.push({priority: 0, compile: aa(function(a, b) {
var d = b.parent(), e = d.data("$binding") || [];
e.push(c);
T(d.data("$binding", e), "ng-binding");
a.$watch(c, function(a) {
b[0].nodeValue =
a
})
})})
}
function v(a, b) {
if ("xlinkHref" == b || "IMG" != Da(a) && ("src" == b || "ngSrc" == b))
return U.RESOURCE_URL
}
function B(a, b, c, d) {
var e = l(c, !0);
if (e) {
if ("multiple" === d && "SELECT" === Da(a))
throw ha("selmulti", ga(a));
b.push({priority: -100, compile: aa(function(b, c, f) {
c = f.$$observers || (f.$$observers = {});
if (h.test(d))
throw ha("nodomevents");
if (e = l(f[d], !0, v(a, d)))
f[d] = e(b), (c[d] || (c[d] = [])).$$inter = !0, (f.$$observers && f.$$observers[d].$$scope || b).$watch(e, function(a) {
f.$set(d, a)
})
})})
}
}
function db(a, b, c) {
var d = b[0],
e = b.length, f = d.parentNode, h, k;
if (a)
for (h = 0, k = a.length; h < k; h++)
if (a[h] == d) {
a[h++] = c;
k = h + e - 1;
for (var g = a.length; h < g; h++, k++)
k < g ? a[h] = a[k] : delete a[h];
a.length -= e - 1;
break
}
f && f.replaceChild(c, d);
a = R.createDocumentFragment();
a.appendChild(d);
c[x.expando] = d[x.expando];
d = 1;
for (e = b.length; d < e; d++)
f = b[d], x(f).remove(), a.appendChild(f), delete b[d];
b[0] = c;
b.length = 1
}
var z = function(a, b) {
this.$$element = a;
this.$attr = b || {}
};
z.prototype = {$normalize: la, $addClass: function(a) {
a && 0 < a.length && M.addClass(this.$$element,
a)
}, $removeClass: function(a) {
a && 0 < a.length && M.removeClass(this.$$element, a)
}, $set: function(a, b, c, d) {
function e(a, b) {
var c = [], d = a.split(/\s+/), f = b.split(/\s+/), h = 0;
a:for (; h < d.length; h++) {
for (var k = d[h], g = 0; g < f.length; g++)
if (k == f[g])
continue a;
c.push(k)
}
return c
}
if ("class" == a)
b = b || "", c = this.$$element.attr("class") || "", this.$removeClass(e(c, b).join(" ")), this.$addClass(e(b, c).join(" "));
else {
var h = Yb(this.$$element[0], a);
h && (this.$$element.prop(a, b), d = h);
this[a] = b;
d ? this.$attr[a] = d : (d = this.$attr[a]) ||
(this.$attr[a] = d = $a(a, "-"));
h = Da(this.$$element);
if ("A" === h && "href" === a || "IMG" === h && "src" === a)
if (!Q || 8 <= Q)
h = wa(b).href, "" !== h && ("href" === a && !h.match(f) || "src" === a && !h.match(g)) && (this[a] = b = "unsafe:" + h);
!1 !== c && (null === b || b === s ? this.$$element.removeAttr(d) : this.$$element.attr(d, b))
}
(c = this.$$observers) && p(c[a], function(a) {
try {
a(b)
} catch (c) {
r(c)
}
})
}, $observe: function(a, b) {
var c = this, d = c.$$observers || (c.$$observers = {}), e = d[a] || (d[a] = []);
e.push(b);
C.$evalAsync(function() {
e.$$inter || b(c[a])
});
return b
}};
var D = l.startSymbol(), J = l.endSymbol(), cc = "{{" == D || "}}" == J ? za : function(a) {
return a.replace(/\{\{/g, D).replace(/}}/g, J)
}, ma = /^ngAttr[A-Z]/;
return t
}]
}
function la(b) {
return Ma(b.replace(bd, ""))
}
function cd() {
var b = {}, a = /^(\S+)(\s+as\s+(\w+))?$/;
this.register = function(a, d) {
pa(a, "controller");
S(a) ? G(b, a) : b[a] = d
};
this.$get = ["$injector", "$window", function(c, d) {
return function(e, f) {
var g, h, m;
F(e) && (g = e.match(a), h = g[1], m = g[3], e = b.hasOwnProperty(h) ? b[h] : sb(f.$scope, h, !0) || sb(d, h, !0), La(e, h, !0));
g = c.instantiate(e,
f);
if (m) {
if (!f || "object" != typeof f.$scope)
throw D("$controller")("noscp", h || e.name, m);
f.$scope[m] = g
}
return g
}
}]
}
function dd() {
this.$get = ["$window", function(b) {
return x(b.document)
}]
}
function ed() {
this.$get = ["$log", function(b) {
return function(a, c) {
b.error.apply(b, arguments)
}
}]
}
function dc(b) {
var a = {}, c, d, e;
if (!b)
return a;
p(b.split("\n"), function(b) {
e = b.indexOf(":");
c = B(ba(b.substr(0, e)));
d = ba(b.substr(e + 1));
c && (a[c] = a[c] ? a[c] + (", " + d) : d)
});
return a
}
function ec(b) {
var a = S(b) ? b : s;
return function(c) {
a ||
(a = dc(b));
return c ? a[B(c)] || null : a
}
}
function fc(b, a, c) {
if (E(c))
return c(b, a);
p(c, function(c) {
b = c(b, a)
});
return b
}
function fd() {
var b = /^\s*(\[|\{[^\{])/, a = /[\}\]]\s*$/, c = /^\)\]\}',?\n/, d = {"Content-Type": "application/json;charset=utf-8"}, e = this.defaults = {transformResponse: [function(d) {
F(d) && (d = d.replace(c, ""), b.test(d) && a.test(d) && (d = Ob(d)));
return d
}], transformRequest: [function(a) {
return S(a) && "[object File]" !== Wa.apply(a) ? oa(a) : a
}], headers: {common: {Accept: "application/json, text/plain, */*"}, post: d,
put: d, patch: d}, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN"}, f = this.interceptors = [], g = this.responseInterceptors = [];
this.$get = ["$httpBackend", "$browser", "$cacheFactory", "$rootScope", "$q", "$injector", function(a, b, c, d, r, q) {
function n(a) {
function c(a) {
var b = G({}, a, {data: fc(a.data, a.headers, d.transformResponse)});
return 200 <= a.status && 300 > a.status ? b : r.reject(b)
}
var d = {transformRequest: e.transformRequest, transformResponse: e.transformResponse}, f = function(a) {
function b(a) {
var c;
p(a, function(b,
d) {
E(b) && (c = b(), null != c ? a[d] = c : delete a[d])
})
}
var c = e.headers, d = G({}, a.headers), f, h, c = G({}, c.common, c[B(a.method)]);
b(c);
b(d);
a:for (f in c) {
a = B(f);
for (h in d)
if (B(h) === a)
continue a;
d[f] = c[f]
}
return d
}(a);
G(d, a);
d.headers = f;
d.method = Ea(d.method);
(a = Cb(d.url) ? b.cookies()[d.xsrfCookieName || e.xsrfCookieName] : s) && (f[d.xsrfHeaderName || e.xsrfHeaderName] = a);
var h = [function(a) {
f = a.headers;
var b = fc(a.data, ec(f), a.transformRequest);
z(a.data) && p(f, function(a, b) {
"content-type" === B(b) && delete f[b]
});
z(a.withCredentials) &&
!z(e.withCredentials) && (a.withCredentials = e.withCredentials);
return y(a, b, f).then(c, c)
}, s], k = r.when(d);
for (p(u, function(a) {
(a.request || a.requestError) && h.unshift(a.request, a.requestError);
(a.response || a.responseError) && h.push(a.response, a.responseError)
}); h.length; ) {
a = h.shift();
var g = h.shift(), k = k.then(a, g)
}
k.success = function(a) {
k.then(function(b) {
a(b.data, b.status, b.headers, d)
});
return k
};
k.error = function(a) {
k.then(null, function(b) {
a(b.data, b.status, b.headers, d)
});
return k
};
return k
}
function y(b,
c, f) {
function k(a, b, c) {
p && (200 <= a && 300 > a ? p.put(s, [a, b, dc(c)]) : p.remove(s));
g(b, a, c);
d.$$phase || d.$apply()
}
function g(a, c, d) {
c = Math.max(c, 0);
(200 <= c && 300 > c ? q.resolve : q.reject)({data: a, status: c, headers: ec(d), config: b})
}
function m() {
var a = Ya(n.pendingRequests, b);
-1 !== a && n.pendingRequests.splice(a, 1)
}
var q = r.defer(), y = q.promise, p, u, s = A(b.url, b.params);
n.pendingRequests.push(b);
y.then(m, m);
(b.cache || e.cache) && (!1 !== b.cache && "GET" == b.method) && (p = S(b.cache) ? b.cache : S(e.cache) ? e.cache : C);
if (p)
if (u = p.get(s),
w(u)) {
if (u.then)
return u.then(m, m), u;
H(u) ? g(u[1], u[0], fa(u[2])) : g(u, 200, {})
} else
p.put(s, y);
z(u) && a(b.method, s, c, k, f, b.timeout, b.withCredentials, b.responseType);
return y
}
function A(a, b) {
if (!b)
return a;
var c = [];
Gc(b, function(a, b) {
null != a && a != s && (H(a) || (a = [a]), p(a, function(a) {
S(a) && (a = oa(a));
c.push(va(b) + "=" + va(a))
}))
});
return a + (-1 == a.indexOf("?") ? "?" : "&") + c.join("&")
}
var C = c("$http"), u = [];
p(f, function(a) {
u.unshift(F(a) ? q.get(a) : q.invoke(a))
});
p(g, function(a, b) {
var c = F(a) ? q.get(a) : q.invoke(a);
u.splice(b,
0, {response: function(a) {
return c(r.when(a))
}, responseError: function(a) {
return c(r.reject(a))
}})
});
n.pendingRequests = [];
(function(a) {
p(arguments, function(a) {
n[a] = function(b, c) {
return n(G(c || {}, {method: a, url: b}))
}
})
})("get", "delete", "head", "jsonp");
(function(a) {
p(arguments, function(a) {
n[a] = function(b, c, d) {
return n(G(d || {}, {method: a, url: b, data: c}))
}
})
})("post", "put");
n.defaults = e;
return n
}]
}
function gd() {
this.$get = ["$browser", "$window", "$document", function(b, a, c) {
return hd(b, id, b.defer, a.angular.callbacks,
c[0], a.location.protocol.replace(":", ""))
}]
}
function hd(b, a, c, d, e, f) {
function g(a, b) {
var c = e.createElement("script"), d = function() {
e.body.removeChild(c);
b && b()
};
c.type = "text/javascript";
c.src = a;
Q ? c.onreadystatechange = function() {
/loaded|complete/.test(c.readyState) && d()
} : c.onload = c.onerror = d;
e.body.appendChild(c);
return d
}
return function(e, m, k, l, r, q, n, y) {
function A() {
u = -1;
M && M();
t && t.abort()
}
function C(a, d, e, h) {
var g = f || wa(m).protocol;
T && c.cancel(T);
M = t = null;
d = "file" == g ? e ? 200 : 404 : d;
a(1223 == d ? 204 : d,
e, h);
b.$$completeOutstandingRequest(v)
}
var u;
b.$$incOutstandingRequestCount();
m = m || b.url();
if ("jsonp" == B(e)) {
var s = "_" + (d.counter++).toString(36);
d[s] = function(a) {
d[s].data = a
};
var M = g(m.replace("JSON_CALLBACK", "angular.callbacks." + s), function() {
d[s].data ? C(l, 200, d[s].data) : C(l, u || -2);
delete d[s]
})
} else {
var t = new a;
t.open(e, m, !0);
p(r, function(a, b) {
w(a) && t.setRequestHeader(b, a)
});
t.onreadystatechange = function() {
if (4 == t.readyState) {
var a = t.getAllResponseHeaders();
C(l, u || t.status, t.responseType ? t.response :
t.responseText, a)
}
};
n && (t.withCredentials = !0);
y && (t.responseType = y);
t.send(k || null)
}
if (0 < q)
var T = c(A, q);
else
q && q.then && q.then(A)
}
}
function jd() {
var b = "{{", a = "}}";
this.startSymbol = function(a) {
return a ? (b = a, this) : b
};
this.endSymbol = function(b) {
return b ? (a = b, this) : a
};
this.$get = ["$parse", "$exceptionHandler", "$sce", function(c, d, e) {
function f(f, k, l) {
for (var r, q, n = 0, y = [], A = f.length, p = !1, u = []; n < A; )
-1 != (r = f.indexOf(b, n)) && -1 != (q = f.indexOf(a, r + g)) ? (n != r && y.push(f.substring(n, r)), y.push(n = c(p = f.substring(r +
g, q))), n.exp = p, n = q + h, p = !0) : (n != A && y.push(f.substring(n)), n = A);
(A = y.length) || (y.push(""), A = 1);
if (l && 1 < y.length)
throw gc("noconcat", f);
if (!k || p)
return u.length = A, n = function(a) {
try {
for (var b = 0, c = A, h; b < c; b++)
"function" == typeof (h = y[b]) && (h = h(a), h = l ? e.getTrusted(l, h) : e.valueOf(h), null == h || h == s ? h = "" : "string" != typeof h && (h = oa(h))), u[b] = h;
return u.join("")
} catch (g) {
a = gc("interr", f, g.toString()), d(a)
}
}, n.exp = f, n.parts = y, n
}
var g = b.length, h = a.length;
f.startSymbol = function() {
return b
};
f.endSymbol = function() {
return a
};
return f
}]
}
function kd() {
this.$get = ["$rootScope", "$window", "$q", function(b, a, c) {
function d(d, g, h, m) {
var k = a.setInterval, l = a.clearInterval, r = c.defer(), q = r.promise;
h = w(h) ? h : 0;
var n = 0, y = w(m) && !m;
q.then(null, null, d);
q.$$intervalId = k(function() {
r.notify(n++);
0 < h && n >= h && (r.resolve(n), l(q.$$intervalId), delete e[q.$$intervalId]);
y || b.$apply()
}, g);
e[q.$$intervalId] = r;
return q
}
var e = {};
d.cancel = function(a) {
return a && a.$$intervalId in e ? (e[a.$$intervalId].reject("canceled"), clearInterval(a.$$intervalId), delete e[a.$$intervalId],
!0) : !1
};
return d
}]
}
function ld() {
this.$get = function() {
return{id: "en-us", NUMBER_FORMATS: {DECIMAL_SEP: ".", GROUP_SEP: ",", PATTERNS: [{minInt: 1, minFrac: 0, maxFrac: 3, posPre: "", posSuf: "", negPre: "-", negSuf: "", gSize: 3, lgSize: 3}, {minInt: 1, minFrac: 2, maxFrac: 2, posPre: "\u00a4", posSuf: "", negPre: "(\u00a4", negSuf: ")", gSize: 3, lgSize: 3}], CURRENCY_SYM: "$"}, DATETIME_FORMATS: {MONTH: "January February March April May June July August September October November December".split(" "), SHORTMONTH: "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),
DAY: "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), SHORTDAY: "Sun Mon Tue Wed Thu Fri Sat".split(" "), AMPMS: ["AM", "PM"], medium: "MMM d, y h:mm:ss a", "short": "M/d/yy h:mm a", fullDate: "EEEE, MMMM d, y", longDate: "MMMM d, y", mediumDate: "MMM d, y", shortDate: "M/d/yy", mediumTime: "h:mm:ss a", shortTime: "h:mm a"}, pluralCat: function(b) {
return 1 === b ? "one" : "other"
}}
}
}
function hc(b) {
b = b.split("/");
for (var a = b.length; a--; )
b[a] = qb(b[a]);
return b.join("/")
}
function ic(b, a) {
var c = wa(b);
a.$$protocol =
c.protocol;
a.$$host = c.hostname;
a.$$port = W(c.port) || md[c.protocol] || null
}
function jc(b, a) {
var c = "/" !== b.charAt(0);
c && (b = "/" + b);
var d = wa(b);
a.$$path = decodeURIComponent(c && "/" === d.pathname.charAt(0) ? d.pathname.substring(1) : d.pathname);
a.$$search = Qb(d.search);
a.$$hash = decodeURIComponent(d.hash);
a.$$path && "/" != a.$$path.charAt(0) && (a.$$path = "/" + a.$$path)
}
function na(b, a) {
if (0 == a.indexOf(b))
return a.substr(b.length)
}
function Ta(b) {
var a = b.indexOf("#");
return-1 == a ? b : b.substr(0, a)
}
function Db(b) {
return b.substr(0,
Ta(b).lastIndexOf("/") + 1)
}
function kc(b, a) {
this.$$html5 = !0;
a = a || "";
var c = Db(b);
ic(b, this);
this.$$parse = function(a) {
var b = na(c, a);
if (!F(b))
throw Eb("ipthprfx", a, c);
jc(b, this);
this.$$path || (this.$$path = "/");
this.$$compose()
};
this.$$compose = function() {
var a = Rb(this.$$search), b = this.$$hash ? "#" + qb(this.$$hash) : "";
this.$$url = hc(this.$$path) + (a ? "?" + a : "") + b;
this.$$absUrl = c + this.$$url.substr(1)
};
this.$$rewrite = function(d) {
var e;
if ((e = na(b, d)) !== s)
return d = e, (e = na(a, e)) !== s ? c + (na("/", e) || e) : b + d;
if ((e = na(c,
d)) !== s)
return c + e;
if (c == d + "/")
return c
}
}
function Fb(b, a) {
var c = Db(b);
ic(b, this);
this.$$parse = function(d) {
var e = na(b, d) || na(c, d), e = "#" == e.charAt(0) ? na(a, e) : this.$$html5 ? e : "";
if (!F(e))
throw Eb("ihshprfx", d, a);
jc(e, this);
this.$$compose()
};
this.$$compose = function() {
var c = Rb(this.$$search), e = this.$$hash ? "#" + qb(this.$$hash) : "";
this.$$url = hc(this.$$path) + (c ? "?" + c : "") + e;
this.$$absUrl = b + (this.$$url ? a + this.$$url : "")
};
this.$$rewrite = function(a) {
if (Ta(b) == Ta(a))
return a
}
}
function lc(b, a) {
this.$$html5 = !0;
Fb.apply(this,
arguments);
var c = Db(b);
this.$$rewrite = function(d) {
var e;
if (b == Ta(d))
return d;
if (e = na(c, d))
return b + a + e;
if (c === d + "/")
return c
}
}
function eb(b) {
return function() {
return this[b]
}
}
function mc(b, a) {
return function(c) {
if (z(c))
return this[b];
this[b] = a(c);
this.$$compose();
return this
}
}
function nd() {
var b = "", a = !1;
this.hashPrefix = function(a) {
return w(a) ? (b = a, this) : b
};
this.html5Mode = function(b) {
return w(b) ? (a = b, this) : a
};
this.$get = ["$rootScope", "$browser", "$sniffer", "$rootElement", function(c, d, e, f) {
function g(a) {
c.$broadcast("$locationChangeSuccess",
h.absUrl(), a)
}
var h, m = d.baseHref(), k = d.url();
a ? (m = k.substring(0, k.indexOf("/", k.indexOf("//") + 2)) + (m || "/"), e = e.history ? kc : lc) : (m = Ta(k), e = Fb);
h = new e(m, "#" + b);
h.$$parse(h.$$rewrite(k));
f.on("click", function(a) {
if (!a.ctrlKey && !a.metaKey && 2 != a.which) {
for (var b = x(a.target); "a" !== B(b[0].nodeName); )
if (b[0] === f[0] || !(b = b.parent())[0])
return;
var e = b.prop("href"), g = h.$$rewrite(e);
e && (!b.attr("target") && g && !a.isDefaultPrevented()) && (a.preventDefault(), g != d.url() && (h.$$parse(g), c.$apply(), Y.angular["ff-684208-preventDefault"] =
!0))
}
});
h.absUrl() != k && d.url(h.absUrl(), !0);
d.onUrlChange(function(a) {
h.absUrl() != a && (c.$broadcast("$locationChangeStart", a, h.absUrl()).defaultPrevented ? d.url(h.absUrl()) : (c.$evalAsync(function() {
var b = h.absUrl();
h.$$parse(a);
g(b)
}), c.$$phase || c.$digest()))
});
var l = 0;
c.$watch(function() {
var a = d.url(), b = h.$$replace;
l && a == h.absUrl() || (l++, c.$evalAsync(function() {
c.$broadcast("$locationChangeStart", h.absUrl(), a).defaultPrevented ? h.$$parse(a) : (d.url(h.absUrl(), b), g(a))
}));
h.$$replace = !1;
return l
});
return h
}]
}
function od() {
var b = !0, a = this;
this.debugEnabled = function(a) {
return w(a) ? (b = a, this) : b
};
this.$get = ["$window", function(c) {
function d(a) {
a instanceof Error && (a.stack ? a = a.message && -1 === a.stack.indexOf(a.message) ? "Error: " + a.message + "\n" + a.stack : a.stack : a.sourceURL && (a = a.message + "\n" + a.sourceURL + ":" + a.line));
return a
}
function e(a) {
var b = c.console || {}, e = b[a] || b.log || v;
return e.apply ? function() {
var a = [];
p(arguments, function(b) {
a.push(d(b))
});
return e.apply(b, a)
} : function(a, b) {
e(a, null == b ? "" : b)
}
}
return{log: e("log"),
info: e("info"), warn: e("warn"), error: e("error"), debug: function() {
var c = e("debug");
return function() {
b && c.apply(a, arguments)
}
}()}
}]
}
function qa(b, a) {
if ("constructor" === b)
throw xa("isecfld", a);
return b
}
function fb(b, a) {
if (b && b.constructor === b)
throw xa("isecfn", a);
if (b && b.document && b.location && b.alert && b.setInterval)
throw xa("isecwindow", a);
if (b && (b.nodeName || b.on && b.find))
throw xa("isecdom", a);
return b
}
function gb(b, a, c, d, e) {
e = e || {};
a = a.split(".");
for (var f, g = 0; 1 < a.length; g++) {
f = qa(a.shift(), d);
var h =
b[f];
h || (h = {}, b[f] = h);
b = h;
b.then && e.unwrapPromises && (ra(d), "$$v"in b || function(a) {
a.then(function(b) {
a.$$v = b
})
}(b), b.$$v === s && (b.$$v = {}), b = b.$$v)
}
f = qa(a.shift(), d);
return b[f] = c
}
function nc(b, a, c, d, e, f, g) {
qa(b, f);
qa(a, f);
qa(c, f);
qa(d, f);
qa(e, f);
return g.unwrapPromises ? function(h, g) {
var k = g && g.hasOwnProperty(b) ? g : h, l;
if (null === k || k === s)
return k;
(k = k[b]) && k.then && (ra(f), "$$v"in k || (l = k, l.$$v = s, l.then(function(a) {
l.$$v = a
})), k = k.$$v);
if (!a || null === k || k === s)
return k;
(k = k[a]) && k.then && (ra(f), "$$v"in k ||
(l = k, l.$$v = s, l.then(function(a) {
l.$$v = a
})), k = k.$$v);
if (!c || null === k || k === s)
return k;
(k = k[c]) && k.then && (ra(f), "$$v"in k || (l = k, l.$$v = s, l.then(function(a) {
l.$$v = a
})), k = k.$$v);
if (!d || null === k || k === s)
return k;
(k = k[d]) && k.then && (ra(f), "$$v"in k || (l = k, l.$$v = s, l.then(function(a) {
l.$$v = a
})), k = k.$$v);
if (!e || null === k || k === s)
return k;
(k = k[e]) && k.then && (ra(f), "$$v"in k || (l = k, l.$$v = s, l.then(function(a) {
l.$$v = a
})), k = k.$$v);
return k
} : function(f, g) {
var k = g && g.hasOwnProperty(b) ? g : f;
if (null === k || k === s)
return k;
k = k[b];
if (!a || null === k || k === s)
return k;
k = k[a];
if (!c || null === k || k === s)
return k;
k = k[c];
if (!d || null === k || k === s)
return k;
k = k[d];
return e && null !== k && k !== s ? k = k[e] : k
}
}
function oc(b, a, c) {
if (Gb.hasOwnProperty(b))
return Gb[b];
var d = b.split("."), e = d.length, f;
if (a.csp)
f = 6 > e ? nc(d[0], d[1], d[2], d[3], d[4], c, a) : function(b, f) {
var h = 0, g;
do
g = nc(d[h++], d[h++], d[h++], d[h++], d[h++], c, a)(b, f), f = s, b = g;
while (h < e);
return g
};
else {
var g = "var l, fn, p;\n";
p(d, function(b, d) {
qa(b, c);
g += "if(s === null || s === undefined) return s;\nl=s;\ns=" +
(d ? "s" : '((k&&k.hasOwnProperty("' + b + '"))?k:s)') + '["' + b + '"];\n' + (a.unwrapPromises ? 'if (s && s.then) {\n pw("' + c.replace(/\"/g, '\\"') + '");\n if (!("$$v" in s)) {\n p=s;\n p.$$v = undefined;\n p.then(function(v) {p.$$v=v;});\n}\n s=s.$$v\n}\n' : "")
});
var g = g + "return s;", h = Function("s", "k", "pw", g);
h.toString = function() {
return g
};
f = function(a, b) {
return h(a, b, ra)
}
}
"hasOwnProperty" !== b && (Gb[b] = f);
return f
}
function pd() {
var b = {}, a = {csp: !1, unwrapPromises: !1, logPromiseWarnings: !0};
this.unwrapPromises = function(b) {
return w(b) ?
(a.unwrapPromises = !!b, this) : a.unwrapPromises
};
this.logPromiseWarnings = function(b) {
return w(b) ? (a.logPromiseWarnings = b, this) : a.logPromiseWarnings
};
this.$get = ["$filter", "$sniffer", "$log", function(c, d, e) {
a.csp = d.csp;
ra = function(b) {
a.logPromiseWarnings && !pc.hasOwnProperty(b) && (pc[b] = !0, e.warn("[$parse] Promise found in the expression `" + b + "`. Automatic unwrapping of promises in Angular expressions is deprecated."))
};
return function(d) {
var e;
switch (typeof d) {
case "string":
if (b.hasOwnProperty(d))
return b[d];
e = new Hb(a);
e = (new Ua(e, c, a)).parse(d, !1);
"hasOwnProperty" !== d && (b[d] = e);
return e;
case "function":
return d;
default:
return v
}
}
}]
}
function qd() {
this.$get = ["$rootScope", "$exceptionHandler", function(b, a) {
return rd(function(a) {
b.$evalAsync(a)
}, a)
}]
}
function rd(b, a) {
function c(a) {
return a
}
function d(a) {
return g(a)
}
var e = function() {
var h = [], m, k;
return k = {resolve: function(a) {
if (h) {
var c = h;
h = s;
m = f(a);
c.length && b(function() {
for (var a, b = 0, d = c.length; b < d; b++)
a = c[b], m.then(a[0], a[1], a[2])
})
}
}, reject: function(a) {
k.resolve(g(a))
},
notify: function(a) {
if (h) {
var c = h;
h.length && b(function() {
for (var b, d = 0, e = c.length; d < e; d++)
b = c[d], b[2](a)
})
}
}, promise: {then: function(b, f, g) {
var k = e(), y = function(d) {
try {
k.resolve((E(b) ? b : c)(d))
} catch (e) {
k.reject(e), a(e)
}
}, A = function(b) {
try {
k.resolve((E(f) ? f : d)(b))
} catch (c) {
k.reject(c), a(c)
}
}, p = function(b) {
try {
k.notify((E(g) ? g : c)(b))
} catch (d) {
a(d)
}
};
h ? h.push([y, A, p]) : m.then(y, A, p);
return k.promise
}, "catch": function(a) {
return this.then(null, a)
}, "finally": function(a) {
function b(a, c) {
var d = e();
c ? d.resolve(a) :
d.reject(a);
return d.promise
}
function d(e, f) {
var h = null;
try {
h = (a || c)()
} catch (g) {
return b(g, !1)
}
return h && E(h.then) ? h.then(function() {
return b(e, f)
}, function(a) {
return b(a, !1)
}) : b(e, f)
}
return this.then(function(a) {
return d(a, !0)
}, function(a) {
return d(a, !1)
})
}}}
}, f = function(a) {
return a && E(a.then) ? a : {then: function(c) {
var d = e();
b(function() {
d.resolve(c(a))
});
return d.promise
}}
}, g = function(c) {
return{then: function(f, g) {
var l = e();
b(function() {
try {
l.resolve((E(g) ? g : d)(c))
} catch (b) {
l.reject(b), a(b)
}
});
return l.promise
}}
};
return{defer: e, reject: g, when: function(h, m, k, l) {
var r = e(), q, n = function(b) {
try {
return(E(m) ? m : c)(b)
} catch (d) {
return a(d), g(d)
}
}, y = function(b) {
try {
return(E(k) ? k : d)(b)
} catch (c) {
return a(c), g(c)
}
}, p = function(b) {
try {
return(E(l) ? l : c)(b)
} catch (d) {
a(d)
}
};
b(function() {
f(h).then(function(a) {
q || (q = !0, r.resolve(f(a).then(n, y, p)))
}, function(a) {
q || (q = !0, r.resolve(y(a)))
}, function(a) {
q || r.notify(p(a))
})
});
return r.promise
}, all: function(a) {
var b = e(), c = 0, d = H(a) ? [] : {};
p(a, function(a, e) {
c++;
f(a).then(function(a) {
d.hasOwnProperty(e) ||
(d[e] = a, --c || b.resolve(d))
}, function(a) {
d.hasOwnProperty(e) || b.reject(a)
})
});
0 === c && b.resolve(d);
return b.promise
}}
}
function sd() {
var b = 10, a = D("$rootScope");
this.digestTtl = function(a) {
arguments.length && (b = a);
return b
};
this.$get = ["$injector", "$exceptionHandler", "$parse", "$browser", function(c, d, e, f) {
function g() {
this.$id = Va();
this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null;
this["this"] = this.$root = this;
this.$$destroyed = !1;
this.$$asyncQueue =
[];
this.$$postDigestQueue = [];
this.$$listeners = {};
this.$$isolateBindings = {}
}
function h(b) {
if (l.$$phase)
throw a("inprog", l.$$phase);
l.$$phase = b
}
function m(a, b) {
var c = e(a);
La(c, b);
return c
}
function k() {
}
g.prototype = {constructor: g, $new: function(a) {
a ? (a = new g, a.$root = this.$root, a.$$asyncQueue = this.$$asyncQueue, a.$$postDigestQueue = this.$$postDigestQueue) : (a = function() {
}, a.prototype = this, a = new a, a.$id = Va());
a["this"] = a;
a.$$listeners = {};
a.$parent = this;
a.$$watchers = a.$$nextSibling = a.$$childHead = a.$$childTail =
null;
a.$$prevSibling = this.$$childTail;
this.$$childHead ? this.$$childTail = this.$$childTail.$$nextSibling = a : this.$$childHead = this.$$childTail = a;
return a
}, $watch: function(a, b, c) {
var d = m(a, "watch"), e = this.$$watchers, f = {fn: b, last: k, get: d, exp: a, eq: !!c};
if (!E(b)) {
var g = m(b || v, "listener");
f.fn = function(a, b, c) {
g(c)
}
}
if ("string" == typeof a && d.constant) {
var h = f.fn;
f.fn = function(a, b, c) {
h.call(this, a, b, c);
Ia(e, f)
}
}
e || (e = this.$$watchers = []);
e.unshift(f);
return function() {
Ia(e, f)
}
}, $watchCollection: function(a, b) {
var c =
this, d, f, g = 0, h = e(a), k = [], l = {}, m = 0;
return this.$watch(function() {
f = h(c);
var a, b;
if (S(f))
if (nb(f))
for (d !== k && (d = k, m = d.length = 0, g++), a = f.length, m !== a && (g++, d.length = m = a), b = 0; b < a; b++)
d[b] !== f[b] && (g++, d[b] = f[b]);
else {
d !== l && (d = l = {}, m = 0, g++);
a = 0;
for (b in f)
f.hasOwnProperty(b) && (a++, d.hasOwnProperty(b) ? d[b] !== f[b] && (g++, d[b] = f[b]) : (m++, d[b] = f[b], g++));
if (m > a)
for (b in g++, d)
d.hasOwnProperty(b) && !f.hasOwnProperty(b) && (m--, delete d[b])
}
else
d !== f && (d = f, g++);
return g
}, function() {
b(f, d, c)
})
}, $digest: function() {
var c,
e, f, g, m = this.$$asyncQueue, p = this.$$postDigestQueue, s, w, M = b, t, x = [], v, N, da;
h("$digest");
do {
w = !1;
for (t = this; m.length; )
try {
da = m.shift(), da.scope.$eval(da.expression)
} catch (ka) {
d(ka)
}
do {
if (g = t.$$watchers)
for (s = g.length; s--; )
try {
(c = g[s]) && ((e = c.get(t)) !== (f = c.last) && !(c.eq ? Aa(e, f) : "number" == typeof e && "number" == typeof f && isNaN(e) && isNaN(f))) && (w = !0, c.last = c.eq ? fa(e) : e, c.fn(e, f === k ? e : f, t), 5 > M && (v = 4 - M, x[v] || (x[v] = []), N = E(c.exp) ? "fn: " + (c.exp.name || c.exp.toString()) : c.exp, N += "; newVal: " + oa(e) + "; oldVal: " +
oa(f), x[v].push(N)))
} catch (L) {
d(L)
}
if (!(g = t.$$childHead || t !== this && t.$$nextSibling))
for (; t !== this && !(g = t.$$nextSibling); )
t = t.$parent
} while (t = g);
if (w && !M--)
throw l.$$phase = null, a("infdig", b, oa(x));
} while (w || m.length);
for (l.$$phase = null; p.length; )
try {
p.shift()()
} catch (B) {
d(B)
}
}, $destroy: function() {
if (l != this && !this.$$destroyed) {
var a = this.$parent;
this.$broadcast("$destroy");
this.$$destroyed = !0;
a.$$childHead == this && (a.$$childHead = this.$$nextSibling);
a.$$childTail == this && (a.$$childTail = this.$$prevSibling);
this.$$prevSibling && (this.$$prevSibling.$$nextSibling = this.$$nextSibling);
this.$$nextSibling && (this.$$nextSibling.$$prevSibling = this.$$prevSibling);
this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null
}
}, $eval: function(a, b) {
return e(a)(this, b)
}, $evalAsync: function(a) {
l.$$phase || l.$$asyncQueue.length || f.defer(function() {
l.$$asyncQueue.length && l.$digest()
});
this.$$asyncQueue.push({scope: this, expression: a})
}, $$postDigest: function(a) {
this.$$postDigestQueue.push(a)
},
$apply: function(a) {
try {
return h("$apply"), this.$eval(a)
} catch (b) {
d(b)
} finally {
l.$$phase = null;
try {
l.$digest()
} catch (c) {
throw d(c), c;
}
}
}, $on: function(a, b) {
var c = this.$$listeners[a];
c || (this.$$listeners[a] = c = []);
c.push(b);
return function() {
c[Ya(c, b)] = null
}
}, $emit: function(a, b) {
var c = [], e, f = this, g = !1, h = {name: a, targetScope: f, stopPropagation: function() {
g = !0
}, preventDefault: function() {
h.defaultPrevented = !0
}, defaultPrevented: !1}, k = [h].concat(ua.call(arguments, 1)), l, m;
do {
e = f.$$listeners[a] || c;
h.currentScope =
f;
l = 0;
for (m = e.length; l < m; l++)
if (e[l])
try {
e[l].apply(null, k)
} catch (p) {
d(p)
}
else
e.splice(l, 1), l--, m--;
if (g)
break;
f = f.$parent
} while (f);
return h
}, $broadcast: function(a, b) {
var c = this, e = this, f = {name: a, targetScope: this, preventDefault: function() {
f.defaultPrevented = !0
}, defaultPrevented: !1}, g = [f].concat(ua.call(arguments, 1)), h, k;
do {
c = e;
f.currentScope = c;
e = c.$$listeners[a] || [];
h = 0;
for (k = e.length; h < k; h++)
if (e[h])
try {
e[h].apply(null, g)
} catch (l) {
d(l)
}
else
e.splice(h, 1), h--, k--;
if (!(e = c.$$childHead || c !== this && c.$$nextSibling))
for (; c !==
this && !(e = c.$$nextSibling); )
c = c.$parent
} while (c = e);
return f
}};
var l = new g;
return l
}]
}
function td(b) {
if ("self" === b)
return b;
if (F(b)) {
if (-1 < b.indexOf("***"))
throw sa("iwcard", b);
b = b.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, "\\$1").replace(/\x08/g, "\\x08").replace("\\*\\*", ".*").replace("\\*", "[^:/.?&;]*");
return RegExp("^" + b + "$")
}
if (Xa(b))
return RegExp("^" + b.source + "$");
throw sa("imatcher");
}
function qc(b) {
var a = [];
w(b) && p(b, function(b) {
a.push(td(b))
});
return a
}
function ud() {
this.SCE_CONTEXTS = ea;
var b =
["self"], a = [];
this.resourceUrlWhitelist = function(a) {
arguments.length && (b = qc(a));
return b
};
this.resourceUrlBlacklist = function(b) {
arguments.length && (a = qc(b));
return a
};
this.$get = ["$log", "$document", "$injector", function(c, d, e) {
function f(a) {
var b = function(a) {
this.$$unwrapTrustedValue = function() {
return a
}
};
a && (b.prototype = new a);
b.prototype.valueOf = function() {
return this.$$unwrapTrustedValue()
};
b.prototype.toString = function() {
return this.$$unwrapTrustedValue().toString()
};
return b
}
var g = function(a) {
throw sa("unsafe");
};
e.has("$sanitize") && (g = e.get("$sanitize"));
var h = f(), m = {};
m[ea.HTML] = f(h);
m[ea.CSS] = f(h);
m[ea.URL] = f(h);
m[ea.JS] = f(h);
m[ea.RESOURCE_URL] = f(m[ea.URL]);
return{trustAs: function(a, b) {
var c = m.hasOwnProperty(a) ? m[a] : null;
if (!c)
throw sa("icontext", a, b);
if (null === b || b === s || "" === b)
return b;
if ("string" !== typeof b)
throw sa("itype", a);
return new c(b)
}, getTrusted: function(c, d) {
if (null === d || d === s || "" === d)
return d;
var e = m.hasOwnProperty(c) ? m[c] : null;
if (e && d instanceof e)
return d.$$unwrapTrustedValue();
if (c ===
ea.RESOURCE_URL) {
var e = wa(d.toString()), f, h, p = !1;
f = 0;
for (h = b.length; f < h; f++)
if ("self" === b[f] ? Cb(e) : b[f].exec(e.href)) {
p = !0;
break
}
if (p)
for (f = 0, h = a.length; f < h; f++)
if ("self" === a[f] ? Cb(e) : a[f].exec(e.href)) {
p = !1;
break
}
if (p)
return d;
throw sa("insecurl", d.toString());
}
if (c === ea.HTML)
return g(d);
throw sa("unsafe");
}, valueOf: function(a) {
return a instanceof h ? a.$$unwrapTrustedValue() : a
}}
}]
}
function vd() {
var b = !0;
this.enabled = function(a) {
arguments.length && (b = !!a);
return b
};
this.$get = ["$parse", "$document", "$sceDelegate",
function(a, c, d) {
if (b && Q && (c = c[0].documentMode, c !== s && 8 > c))
throw sa("iequirks");
var e = fa(ea);
e.isEnabled = function() {
return b
};
e.trustAs = d.trustAs;
e.getTrusted = d.getTrusted;
e.valueOf = d.valueOf;
b || (e.trustAs = e.getTrusted = function(a, b) {
return b
}, e.valueOf = za);
e.parseAs = function(b, c) {
var d = a(c);
return d.literal && d.constant ? d : function(a, c) {
return e.getTrusted(b, d(a, c))
}
};
var f = e.parseAs, g = e.getTrusted, h = e.trustAs;
p(ea, function(a, b) {
var c = B(b);
e[Ma("parse_as_" + c)] = function(b) {
return f(a, b)
};
e[Ma("get_trusted_" +
c)] = function(b) {
return g(a, b)
};
e[Ma("trust_as_" + c)] = function(b) {
return h(a, b)
}
});
return e
}]
}
function wd() {
this.$get = ["$window", "$document", function(b, a) {
var c = {}, d = W((/android (\d+)/.exec(B((b.navigator || {}).userAgent)) || [])[1]), e = /Boxee/i.test((b.navigator || {}).userAgent), f = a[0] || {}, g, h = /^(Moz|webkit|O|ms)(?=[A-Z])/, m = f.body && f.body.style, k = !1, l = !1;
if (m) {
for (var r in m)
if (k = h.exec(r)) {
g = k[0];
g = g.substr(0, 1).toUpperCase() + g.substr(1);
break
}
g || (g = "WebkitOpacity"in m && "webkit");
k = !!("transition"in m ||
g + "Transition"in m);
l = !!("animation"in m || g + "Animation"in m);
!d || k && l || (k = F(f.body.style.webkitTransition), l = F(f.body.style.webkitAnimation))
}
return{history: !(!b.history || !b.history.pushState || 4 > d || e), hashchange: "onhashchange"in b && (!f.documentMode || 7 < f.documentMode), hasEvent: function(a) {
if ("input" == a && 9 == Q)
return!1;
if (z(c[a])) {
var b = f.createElement("div");
c[a] = "on" + a in b
}
return c[a]
}, csp: f.securityPolicy ? f.securityPolicy.isActive : !1, vendorPrefix: g, transitions: k, animations: l}
}]
}
function xd() {
this.$get =
["$rootScope", "$browser", "$q", "$exceptionHandler", function(b, a, c, d) {
function e(e, h, m) {
var k = c.defer(), l = k.promise, r = w(m) && !m;
h = a.defer(function() {
try {
k.resolve(e())
} catch (a) {
k.reject(a), d(a)
} finally {
delete f[l.$$timeoutId]
}
r || b.$apply()
}, h);
l.$$timeoutId = h;
f[h] = k;
return l
}
var f = {};
e.cancel = function(b) {
return b && b.$$timeoutId in f ? (f[b.$$timeoutId].reject("canceled"), delete f[b.$$timeoutId], a.defer.cancel(b.$$timeoutId)) : !1
};
return e
}]
}
function wa(b) {
Q && (V.setAttribute("href", b), b = V.href);
V.setAttribute("href",
b);
return{href: V.href, protocol: V.protocol ? V.protocol.replace(/:$/, "") : "", host: V.host, search: V.search ? V.search.replace(/^\?/, "") : "", hash: V.hash ? V.hash.replace(/^#/, "") : "", hostname: V.hostname, port: V.port, pathname: V.pathname && "/" === V.pathname.charAt(0) ? V.pathname : "/" + V.pathname}
}
function Cb(b) {
b = F(b) ? wa(b) : b;
return b.protocol === rc.protocol && b.host === rc.host
}
function yd() {
this.$get = aa(Y)
}
function sc(b) {
function a(d, e) {
if (S(d)) {
var f = {};
p(d, function(b, c) {
f[c] = a(c, b)
});
return f
}
return b.factory(d + c, e)
}
var c = "Filter";
this.register = a;
this.$get = ["$injector", function(a) {
return function(b) {
return a.get(b + c)
}
}];
a("currency", tc);
a("date", uc);
a("filter", zd);
a("json", Ad);
a("limitTo", Bd);
a("lowercase", Cd);
a("number", vc);
a("orderBy", wc);
a("uppercase", Dd)
}
function zd() {
return function(b, a, c) {
if (!H(b))
return b;
var d = [];
d.check = function(a) {
for (var b = 0; b < d.length; b++)
if (!d[b](a))
return!1;
return!0
};
switch (typeof c) {
case "function":
break;
case "boolean":
if (!0 == c) {
c = function(a, b) {
return Za.equals(a, b)
};
break
}
default:
c =
function(a, b) {
b = ("" + b).toLowerCase();
return-1 < ("" + a).toLowerCase().indexOf(b)
}
}
var e = function(a, b) {
if ("string" == typeof b && "!" === b.charAt(0))
return!e(a, b.substr(1));
switch (typeof a) {
case "boolean":
case "number":
case "string":
return c(a, b);
case "object":
switch (typeof b) {
case "object":
return c(a, b);
default:
for (var d in a)
if ("$" !== d.charAt(0) && e(a[d], b))
return!0
}
return!1;
case "array":
for (d = 0; d < a.length; d++)
if (e(a[d], b))
return!0;
return!1;
default:
return!1
}
};
switch (typeof a) {
case "boolean":
case "number":
case "string":
a =
{$: a};
case "object":
for (var f in a)
"$" == f ? function() {
if (a[f]) {
var b = f;
d.push(function(c) {
return e(c, a[b])
})
}
}() : function() {
if ("undefined" != typeof a[f]) {
var b = f;
d.push(function(c) {
return e(sb(c, b), a[b])
})
}
}();
break;
case "function":
d.push(a);
break;
default:
return b
}
for (var g = [], h = 0; h < b.length; h++) {
var m = b[h];
d.check(m) && g.push(m)
}
return g
}
}
function tc(b) {
var a = b.NUMBER_FORMATS;
return function(b, d) {
z(d) && (d = a.CURRENCY_SYM);
return xc(b, a.PATTERNS[1], a.GROUP_SEP, a.DECIMAL_SEP, 2).replace(/\u00A4/g, d)
}
}
function vc(b) {
var a =
b.NUMBER_FORMATS;
return function(b, d) {
return xc(b, a.PATTERNS[0], a.GROUP_SEP, a.DECIMAL_SEP, d)
}
}
function xc(b, a, c, d, e) {
if (isNaN(b) || !isFinite(b))
return"";
var f = 0 > b;
b = Math.abs(b);
var g = b + "", h = "", m = [], k = !1;
if (-1 !== g.indexOf("e")) {
var l = g.match(/([\d\.]+)e(-?)(\d+)/);
l && "-" == l[2] && l[3] > e + 1 ? g = "0" : (h = g, k = !0)
}
if (k)
0 < e && (-1 < b && 1 > b) && (h = b.toFixed(e));
else {
g = (g.split(yc)[1] || "").length;
z(e) && (e = Math.min(Math.max(a.minFrac, g), a.maxFrac));
g = Math.pow(10, e);
b = Math.round(b * g) / g;
b = ("" + b).split(yc);
g = b[0];
b = b[1] ||
"";
var k = 0, l = a.lgSize, r = a.gSize;
if (g.length >= l + r)
for (var k = g.length - l, q = 0; q < k; q++)
0 === (k - q) % r && 0 !== q && (h += c), h += g.charAt(q);
for (q = k; q < g.length; q++)
0 === (g.length - q) % l && 0 !== q && (h += c), h += g.charAt(q);
for (; b.length < e; )
b += "0";
e && "0" !== e && (h += d + b.substr(0, e))
}
m.push(f ? a.negPre : a.posPre);
m.push(h);
m.push(f ? a.negSuf : a.posSuf);
return m.join("")
}
function Ib(b, a, c) {
var d = "";
0 > b && (d = "-", b = -b);
for (b = "" + b; b.length < a; )
b = "0" + b;
c && (b = b.substr(b.length - a));
return d + b
}
function X(b, a, c, d) {
c = c || 0;
return function(e) {
e =
e["get" + b]();
if (0 < c || e > -c)
e += c;
0 === e && -12 == c && (e = 12);
return Ib(e, a, d)
}
}
function hb(b, a) {
return function(c, d) {
var e = c["get" + b](), f = Ea(a ? "SHORT" + b : b);
return d[f][e]
}
}
function uc(b) {
function a(a) {
var b;
if (b = a.match(c)) {
a = new Date(0);
var f = 0, g = 0, h = b[8] ? a.setUTCFullYear : a.setFullYear, m = b[8] ? a.setUTCHours : a.setHours;
b[9] && (f = W(b[9] + b[10]), g = W(b[9] + b[11]));
h.call(a, W(b[1]), W(b[2]) - 1, W(b[3]));
f = W(b[4] || 0) - f;
g = W(b[5] || 0) - g;
h = W(b[6] || 0);
b = Math.round(1E3 * parseFloat("0." + (b[7] || 0)));
m.call(a, f, g, h, b)
}
return a
}
var c = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
return function(c, e) {
var f = "", g = [], h, m;
e = e || "mediumDate";
e = b.DATETIME_FORMATS[e] || e;
F(c) && (c = Ed.test(c) ? W(c) : a(c));
ob(c) && (c = new Date(c));
if (!Ha(c))
return c;
for (; e; )
(m = Fd.exec(e)) ? (g = g.concat(ua.call(m, 1)), e = g.pop()) : (g.push(e), e = null);
p(g, function(a) {
h = Gd[a];
f += h ? h(c, b.DATETIME_FORMATS) : a.replace(/(^'|'$)/g, "").replace(/''/g, "'")
});
return f
}
}
function Ad() {
return function(b) {
return oa(b, !0)
}
}
function Bd() {
return function(b, a) {
if (!H(b) && !F(b))
return b;
a = W(a);
if (F(b))
return a ? 0 <= a ? b.slice(0, a) : b.slice(a, b.length) : "";
var c = [], d, e;
a > b.length ? a = b.length : a < -b.length && (a = -b.length);
0 < a ? (d = 0, e = a) : (d = b.length + a, e = b.length);
for (; d < e; d++)
c.push(b[d]);
return c
}
}
function wc(b) {
return function(a, c, d) {
function e(a, b) {
return Ka(b) ? function(b, c) {
return a(c, b)
} : a
}
if (!H(a) || !c)
return a;
c = H(c) ? c : [c];
c = Jc(c, function(a) {
var c = !1, d = a || za;
if (F(a)) {
if ("+" == a.charAt(0) || "-" == a.charAt(0))
c = "-" == a.charAt(0), a = a.substring(1);
d = b(a)
}
return e(function(a, b) {
var c;
c = d(a);
var e = d(b), f = typeof c, g = typeof e;
f == g ? ("string" == f && (c = c.toLowerCase(), e = e.toLowerCase()), c = c === e ? 0 : c < e ? -1 : 1) : c = f < g ? -1 : 1;
return c
}, c)
});
for (var f = [], g = 0; g < a.length; g++)
f.push(a[g]);
return f.sort(e(function(a, b) {
for (var d = 0; d < c.length; d++) {
var e = c[d](a, b);
if (0 !== e)
return e
}
return 0
}, d))
}
}
function ta(b) {
E(b) && (b = {link: b});
b.restrict = b.restrict || "AC";
return aa(b)
}
function zc(b, a) {
function c(a, c) {
c = c ? "-" + $a(c, "-") : "";
b.removeClass((a ? ib : jb) + c).addClass((a ? jb :
ib) + c)
}
var d = this, e = b.parent().controller("form") || kb, f = 0, g = d.$error = {}, h = [];
d.$name = a.name || a.ngForm;
d.$dirty = !1;
d.$pristine = !0;
d.$valid = !0;
d.$invalid = !1;
e.$addControl(d);
b.addClass(Fa);
c(!0);
d.$addControl = function(a) {
pa(a.$name, "input");
h.push(a);
a.$name && (d[a.$name] = a)
};
d.$removeControl = function(a) {
a.$name && d[a.$name] === a && delete d[a.$name];
p(g, function(b, c) {
d.$setValidity(c, !0, a)
});
Ia(h, a)
};
d.$setValidity = function(a, b, h) {
var r = g[a];
if (b)
r && (Ia(r, h), r.length || (f--, f || (c(b), d.$valid = !0, d.$invalid =
!1), g[a] = !1, c(!0, a), e.$setValidity(a, !0, d)));
else {
f || c(b);
if (r) {
if (-1 != Ya(r, h))
return
} else
g[a] = r = [], f++, c(!1, a), e.$setValidity(a, !1, d);
r.push(h);
d.$valid = !1;
d.$invalid = !0
}
};
d.$setDirty = function() {
b.removeClass(Fa).addClass(lb);
d.$dirty = !0;
d.$pristine = !1;
e.$setDirty()
};
d.$setPristine = function() {
b.removeClass(lb).addClass(Fa);
d.$dirty = !1;
d.$pristine = !0;
p(h, function(a) {
a.$setPristine()
})
}
}
function mb(b, a, c, d, e, f) {
var g = function() {
var e = a.val();
Ka(c.ngTrim || "T") && (e = ba(e));
d.$viewValue !== e && b.$apply(function() {
d.$setViewValue(e)
})
};
if (e.hasEvent("input"))
a.on("input", g);
else {
var h, m = function() {
h || (h = f.defer(function() {
g();
h = null
}))
};
a.on("keydown", function(a) {
a = a.keyCode;
91 === a || (15 < a && 19 > a || 37 <= a && 40 >= a) || m()
});
a.on("change", g);
if (e.hasEvent("paste"))
a.on("paste cut", m)
}
d.$render = function() {
a.val(d.$isEmpty(d.$viewValue) ? "" : d.$viewValue)
};
var k = c.ngPattern, l = function(a, b) {
if (d.$isEmpty(b) || a.test(b))
return d.$setValidity("pattern", !0), b;
d.$setValidity("pattern", !1);
return s
};
k && ((e = k.match(/^\/(.*)\/([gim]*)$/)) ? (k = RegExp(e[1],
e[2]), e = function(a) {
return l(k, a)
}) : e = function(c) {
var d = b.$eval(k);
if (!d || !d.test)
throw D("ngPattern")("noregexp", k, d, ga(a));
return l(d, c)
}, d.$formatters.push(e), d.$parsers.push(e));
if (c.ngMinlength) {
var r = W(c.ngMinlength);
e = function(a) {
if (!d.$isEmpty(a) && a.length < r)
return d.$setValidity("minlength", !1), s;
d.$setValidity("minlength", !0);
return a
};
d.$parsers.push(e);
d.$formatters.push(e)
}
if (c.ngMaxlength) {
var q = W(c.ngMaxlength);
e = function(a) {
if (!d.$isEmpty(a) && a.length > q)
return d.$setValidity("maxlength",
!1), s;
d.$setValidity("maxlength", !0);
return a
};
d.$parsers.push(e);
d.$formatters.push(e)
}
}
function Jb(b, a) {
b = "ngClass" + b;
return function() {
return{restrict: "AC", link: function(c, d, e) {
function f(b) {
if (!0 === a || c.$index % 2 === a)
h && !Aa(b, h) && e.$removeClass(g(h)), e.$addClass(g(b));
h = fa(b)
}
function g(a) {
if (H(a))
return a.join(" ");
if (S(a)) {
var b = [];
p(a, function(a, c) {
a && b.push(c)
});
return b.join(" ")
}
return a
}
var h = s;
c.$watch(e[b], f, !0);
e.$observe("class", function(a) {
f(c.$eval(e[b]))
});
"ngClass" !== b && c.$watch("$index",
function(d, f) {
var h = d & 1;
h !== f & 1 && (h === a ? (h = c.$eval(e[b]), e.$addClass(g(h))) : (h = c.$eval(e[b]), e.$removeClass(g(h))))
})
}}
}
}
var B = function(b) {
return F(b) ? b.toLowerCase() : b
}, Ea = function(b) {
return F(b) ? b.toUpperCase() : b
}, Q, x, Ba, ua = [].slice, Hd = [].push, Wa = Object.prototype.toString, Ja = D("ng"), Za = Y.angular || (Y.angular = {}), Ra, Da, ia = ["0", "0", "0"];
Q = W((/msie (\d+)/.exec(B(navigator.userAgent)) || [])[1]);
isNaN(Q) && (Q = W((/trident\/.*; rv:(\d+)/.exec(B(navigator.userAgent)) || [])[1]));
v.$inject = [];
za.$inject = [];
var ba =
function() {
return String.prototype.trim ? function(b) {
return F(b) ? b.trim() : b
} : function(b) {
return F(b) ? b.replace(/^\s*/, "").replace(/\s*$/, "") : b
}
}();
Da = 9 > Q ? function(b) {
b = b.nodeName ? b : b[0];
return b.scopeName && "HTML" != b.scopeName ? Ea(b.scopeName + ":" + b.nodeName) : b.nodeName
} : function(b) {
return b.nodeName ? b.nodeName : b[0].nodeName
};
var Nc = /[A-Z]/g, Id = {full: "1.2.0-rc.3", major: 1, minor: 2, dot: 0, codeName: "ferocious-twitch"}, Oa = J.cache = {}, ab = J.expando = "ng-" + (new Date).getTime(), Rc = 1, Ac = Y.document.addEventListener ?
function(b, a, c) {
b.addEventListener(a, c, !1)
} : function(b, a, c) {
b.attachEvent("on" + a, c)
}, xb = Y.document.removeEventListener ? function(b, a, c) {
b.removeEventListener(a, c, !1)
} : function(b, a, c) {
b.detachEvent("on" + a, c)
}, Pc = /([\:\-\_]+(.))/g, Qc = /^moz([A-Z])/, ub = D("jqLite"), Sa = J.prototype = {ready: function(b) {
function a() {
c || (c = !0, b())
}
var c = !1;
"complete" === R.readyState ? setTimeout(a) : (this.on("DOMContentLoaded", a), J(Y).on("load", a))
}, toString: function() {
var b = [];
p(this, function(a) {
b.push("" + a)
});
return"[" + b.join(", ") +
"]"
}, eq: function(b) {
return 0 <= b ? x(this[b]) : x(this[this.length + b])
}, length: 0, push: Hd, sort: [].sort, splice: [].splice}, cb = {};
p("multiple selected checked disabled readOnly required open".split(" "), function(b) {
cb[B(b)] = b
});
var Zb = {};
p("input select option textarea button form details".split(" "), function(b) {
Zb[Ea(b)] = !0
});
p({data: Wb, inheritedData: bb, scope: function(b) {
return bb(b, "$scope")
}, controller: Xb, injector: function(b) {
return bb(b, "$injector")
}, removeAttr: function(b, a) {
b.removeAttribute(a)
}, hasClass: yb,
css: function(b, a, c) {
a = Ma(a);
if (w(c))
b.style[a] = c;
else {
var d;
8 >= Q && (d = b.currentStyle && b.currentStyle[a], "" === d && (d = "auto"));
d = d || b.style[a];
8 >= Q && (d = "" === d ? s : d);
return d
}
}, attr: function(b, a, c) {
var d = B(a);
if (cb[d])
if (w(c))
c ? (b[a] = !0, b.setAttribute(a, d)) : (b[a] = !1, b.removeAttribute(d));
else
return b[a] || (b.attributes.getNamedItem(a) || v).specified ? d : s;
else if (w(c))
b.setAttribute(a, c);
else if (b.getAttribute)
return b = b.getAttribute(a, 2), null === b ? s : b
}, prop: function(b, a, c) {
if (w(c))
b[a] = c;
else
return b[a]
},
text: function() {
function b(b, d) {
var e = a[b.nodeType];
if (z(d))
return e ? b[e] : "";
b[e] = d
}
var a = [];
9 > Q ? (a[1] = "innerText", a[3] = "nodeValue") : a[1] = a[3] = "textContent";
b.$dv = "";
return b
}(), val: function(b, a) {
if (z(a)) {
if ("SELECT" === Da(b) && b.multiple) {
var c = [];
p(b.options, function(a) {
a.selected && c.push(a.value || a.text)
});
return 0 === c.length ? null : c
}
return b.value
}
b.value = a
}, html: function(b, a) {
if (z(a))
return b.innerHTML;
for (var c = 0, d = b.childNodes; c < d.length; c++)
Na(d[c]);
b.innerHTML = a
}}, function(b, a) {
J.prototype[a] =
function(a, d) {
var e, f;
if ((2 == b.length && b !== yb && b !== Xb ? a : d) === s) {
if (S(a)) {
for (e = 0; e < this.length; e++)
if (b === Wb)
b(this[e], a);
else
for (f in a)
b(this[e], f, a[f]);
return this
}
e = b.$dv;
f = e == s ? Math.min(this.length, 1) : this.length;
for (var g = 0; g < f; g++) {
var h = b(this[g], a, d);
e = e ? e + h : h
}
return e
}
for (e = 0; e < this.length; e++)
b(this[e], a, d);
return this
}
});
p({removeData: Ub, dealoc: Na, on: function a(c, d, e, f) {
if (w(f))
throw ub("onargs");
var g = ja(c, "events"), h = ja(c, "handle");
g || ja(c, "events", g = {});
h || ja(c, "handle", h = Sc(c, g));
p(d.split(" "), function(d) {
var f = g[d];
if (!f) {
if ("mouseenter" == d || "mouseleave" == d) {
var l = R.body.contains || R.body.compareDocumentPosition ? function(a, c) {
var d = 9 === a.nodeType ? a.documentElement : a, e = c && c.parentNode;
return a === e || !!(e && 1 === e.nodeType && (d.contains ? d.contains(e) : a.compareDocumentPosition && a.compareDocumentPosition(e) & 16))
} : function(a, c) {
if (c)
for (; c = c.parentNode; )
if (c === a)
return!0;
return!1
};
g[d] = [];
a(c, {mouseleave: "mouseout", mouseenter: "mouseover"}[d], function(a) {
var c = a.relatedTarget;
c && (c ===
this || l(this, c)) || h(a, d)
})
} else
Ac(c, d, h), g[d] = [];
f = g[d]
}
f.push(e)
})
}, off: Vb, replaceWith: function(a, c) {
var d, e = a.parentNode;
Na(a);
p(new J(c), function(c) {
d ? e.insertBefore(c, d.nextSibling) : e.replaceChild(c, a);
d = c
})
}, children: function(a) {
var c = [];
p(a.childNodes, function(a) {
1 === a.nodeType && c.push(a)
});
return c
}, contents: function(a) {
return a.childNodes || []
}, append: function(a, c) {
p(new J(c), function(c) {
1 !== a.nodeType && 11 !== a.nodeType || a.appendChild(c)
})
}, prepend: function(a, c) {
if (1 === a.nodeType) {
var d = a.firstChild;
p(new J(c), function(c) {
a.insertBefore(c, d)
})
}
}, wrap: function(a, c) {
c = x(c)[0];
var d = a.parentNode;
d && d.replaceChild(c, a);
c.appendChild(a)
}, remove: function(a) {
Na(a);
var c = a.parentNode;
c && c.removeChild(a)
}, after: function(a, c) {
var d = a, e = a.parentNode;
p(new J(c), function(a) {
e.insertBefore(a, d.nextSibling);
d = a
})
}, addClass: Ab, removeClass: zb, toggleClass: function(a, c, d) {
z(d) && (d = !yb(a, c));
(d ? Ab : zb)(a, c)
}, parent: function(a) {
return(a = a.parentNode) && 11 !== a.nodeType ? a : null
}, next: function(a) {
if (a.nextElementSibling)
return a.nextElementSibling;
for (a = a.nextSibling; null != a && 1 !== a.nodeType; )
a = a.nextSibling;
return a
}, find: function(a, c) {
return a.getElementsByTagName(c)
}, clone: wb, triggerHandler: function(a, c, d) {
c = (ja(a, "events") || {})[c];
d = d || [];
var e = [{preventDefault: v, stopPropagation: v}];
p(c, function(c) {
c.apply(a, e.concat(d))
})
}}, function(a, c) {
J.prototype[c] = function(c, e, f) {
for (var g, h = 0; h < this.length; h++)
g == s ? (g = a(this[h], c, e, f), g !== s && (g = x(g))) : vb(g, a(this[h], c, e, f));
return g == s ? this : g
};
J.prototype.bind = J.prototype.on;
J.prototype.unbind = J.prototype.off
});
Pa.prototype = {put: function(a, c) {
this[Ca(a)] = c
}, get: function(a) {
return this[Ca(a)]
}, remove: function(a) {
var c = this[a = Ca(a)];
delete this[a];
return c
}};
var Uc = /^function\s*[^\(]*\(\s*([^\)]*)\)/m, Vc = /,/, Wc = /^\s*(_?)(\S+?)\1\s*$/, Tc = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, Qa = D("$injector"), Jd = D("$animate"), Kd = ["$provide", function(a) {
this.$$selectors = {};
this.register = function(c, d) {
var e = c + "-animation";
if (c && "." != c.charAt(0))
throw Jd("notcsel", c);
this.$$selectors[c.substr(1)] = e;
a.factory(e, d)
};
this.$get = ["$timeout",
function(a) {
return{enter: function(d, e, f, g) {
f = f && f[f.length - 1];
var h = e && e[0] || f && f.parentNode, m = f && f.nextSibling || null;
p(d, function(a) {
h.insertBefore(a, m)
});
g && a(g, 0, !1)
}, leave: function(d, e) {
d.remove();
e && a(e, 0, !1)
}, move: function(a, c, f, g) {
this.enter(a, c, f, g)
}, addClass: function(d, e, f) {
e = F(e) ? e : H(e) ? e.join(" ") : "";
p(d, function(a) {
Ab(a, e)
});
f && a(f, 0, !1)
}, removeClass: function(d, e, f) {
e = F(e) ? e : H(e) ? e.join(" ") : "";
p(d, function(a) {
zb(a, e)
});
f && a(f, 0, !1)
}, enabled: v}
}]
}], ha = D("$compile");
bc.$inject = ["$provide"];
var bd = /^(x[\:\-_]|data[\:\-_])/i, id = Y.XMLHttpRequest || function() {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0")
} catch (a) {
}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0")
} catch (c) {
}
try {
return new ActiveXObject("Msxml2.XMLHTTP")
} catch (d) {
}
throw D("$httpBackend")("noxhr");
}, gc = D("$interpolate"), Ld = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, md = {http: 80, https: 443, ftp: 21}, Eb = D("$location");
lc.prototype = Fb.prototype = kc.prototype = {$$html5: !1, $$replace: !1, absUrl: eb("$$absUrl"), url: function(a, c) {
if (z(a))
return this.$$url;
var d = Ld.exec(a);
d[1] && this.path(decodeURIComponent(d[1]));
(d[2] || d[1]) && this.search(d[3] || "");
this.hash(d[5] || "", c);
return this
}, protocol: eb("$$protocol"), host: eb("$$host"), port: eb("$$port"), path: mc("$$path", function(a) {
return"/" == a.charAt(0) ? a : "/" + a
}), search: function(a, c) {
switch (arguments.length) {
case 0:
return this.$$search;
case 1:
if (F(a))
this.$$search = Qb(a);
else if (S(a))
this.$$search = a;
else
throw Eb("isrcharg");
break;
default:
c == s || null == c ? delete this.$$search[a] : this.$$search[a] = c
}
this.$$compose();
return this
}, hash: mc("$$hash", za), replace: function() {
this.$$replace = !0;
return this
}};
var xa = D("$parse"), pc = {}, ra, Ga = {"null": function() {
return null
}, "true": function() {
return!0
}, "false": function() {
return!1
}, undefined: v, "+": function(a, c, d, e) {
d = d(a, c);
e = e(a, c);
return w(d) ? w(e) ? d + e : d : w(e) ? e : s
}, "-": function(a, c, d, e) {
d = d(a, c);
e = e(a, c);
return(w(d) ? d : 0) - (w(e) ? e : 0)
}, "*": function(a, c, d, e) {
return d(a, c) * e(a, c)
}, "/": function(a, c, d, e) {
return d(a, c) / e(a, c)
}, "%": function(a, c, d, e) {
return d(a, c) % e(a, c)
}, "^": function(a,
c, d, e) {
return d(a, c) ^ e(a, c)
}, "=": v, "===": function(a, c, d, e) {
return d(a, c) === e(a, c)
}, "!==": function(a, c, d, e) {
return d(a, c) !== e(a, c)
}, "==": function(a, c, d, e) {
return d(a, c) == e(a, c)
}, "!=": function(a, c, d, e) {
return d(a, c) != e(a, c)
}, "<": function(a, c, d, e) {
return d(a, c) < e(a, c)
}, ">": function(a, c, d, e) {
return d(a, c) > e(a, c)
}, "<=": function(a, c, d, e) {
return d(a, c) <= e(a, c)
}, ">=": function(a, c, d, e) {
return d(a, c) >= e(a, c)
}, "&&": function(a, c, d, e) {
return d(a, c) && e(a, c)
}, "||": function(a, c, d, e) {
return d(a, c) || e(a, c)
}, "&": function(a,
c, d, e) {
return d(a, c) & e(a, c)
}, "|": function(a, c, d, e) {
return e(a, c)(a, c, d(a, c))
}, "!": function(a, c, d) {
return!d(a, c)
}}, Md = {n: "\n", f: "\f", r: "\r", t: "\t", v: "\v", "'": "'", '"': '"'}, Hb = function(a) {
this.options = a
};
Hb.prototype = {constructor: Hb, lex: function(a) {
this.text = a;
this.index = 0;
this.ch = s;
this.lastCh = ":";
this.tokens = [];
var c;
for (a = []; this.index < this.text.length; ) {
this.ch = this.text.charAt(this.index);
if (this.is("\"'"))
this.readString(this.ch);
else if (this.isNumber(this.ch) || this.is(".") && this.isNumber(this.peek()))
this.readNumber();
else if (this.isIdent(this.ch))
this.readIdent(), this.was("{,") && ("{" === a[0] && (c = this.tokens[this.tokens.length - 1])) && (c.json = -1 === c.text.indexOf("."));
else if (this.is("(){}[].,;:?"))
this.tokens.push({index: this.index, text: this.ch, json: this.was(":[,") && this.is("{[") || this.is("}]:,")}), this.is("{[") && a.unshift(this.ch), this.is("}]") && a.shift(), this.index++;
else if (this.isWhitespace(this.ch)) {
this.index++;
continue
} else {
var d = this.ch + this.peek(), e = d + this.peek(2), f = Ga[this.ch], g = Ga[d], h = Ga[e];
h ? (this.tokens.push({index: this.index,
text: e, fn: h}), this.index += 3) : g ? (this.tokens.push({index: this.index, text: d, fn: g}), this.index += 2) : f ? (this.tokens.push({index: this.index, text: this.ch, fn: f, json: this.was("[,:") && this.is("+-")}), this.index += 1) : this.throwError("Unexpected next character ", this.index, this.index + 1)
}
this.lastCh = this.ch
}
return this.tokens
}, is: function(a) {
return-1 !== a.indexOf(this.ch)
}, was: function(a) {
return-1 !== a.indexOf(this.lastCh)
}, peek: function(a) {
a = a || 1;
return this.index + a < this.text.length ? this.text.charAt(this.index +
a) : !1
}, isNumber: function(a) {
return"0" <= a && "9" >= a
}, isWhitespace: function(a) {
return" " === a || "\r" === a || "\t" === a || "\n" === a || "\v" === a || "\u00a0" === a
}, isIdent: function(a) {
return"a" <= a && "z" >= a || "A" <= a && "Z" >= a || "_" === a || "$" === a
}, isExpOperator: function(a) {
return"-" === a || "+" === a || this.isNumber(a)
}, throwError: function(a, c, d) {
d = d || this.index;
c = w(c) ? "s " + c + "-" + this.index + " [" + this.text.substring(c, d) + "]" : " " + d;
throw xa("lexerr", a, c, this.text);
}, readNumber: function() {
for (var a = "", c = this.index; this.index < this.text.length; ) {
var d =
B(this.text.charAt(this.index));
if ("." == d || this.isNumber(d))
a += d;
else {
var e = this.peek();
if ("e" == d && this.isExpOperator(e))
a += d;
else if (this.isExpOperator(d) && e && this.isNumber(e) && "e" == a.charAt(a.length - 1))
a += d;
else if (!this.isExpOperator(d) || e && this.isNumber(e) || "e" != a.charAt(a.length - 1))
break;
else
this.throwError("Invalid exponent")
}
this.index++
}
a *= 1;
this.tokens.push({index: c, text: a, json: !0, fn: function() {
return a
}})
}, readIdent: function() {
for (var a = this, c = "", d = this.index, e, f, g, h; this.index < this.text.length; ) {
h =
this.text.charAt(this.index);
if ("." === h || this.isIdent(h) || this.isNumber(h))
"." === h && (e = this.index), c += h;
else
break;
this.index++
}
if (e)
for (f = this.index; f < this.text.length; ) {
h = this.text.charAt(f);
if ("(" === h) {
g = c.substr(e - d + 1);
c = c.substr(0, e - d);
this.index = f;
break
}
if (this.isWhitespace(h))
f++;
else
break
}
d = {index: d, text: c};
if (Ga.hasOwnProperty(c))
d.fn = Ga[c], d.json = Ga[c];
else {
var m = oc(c, this.options, this.text);
d.fn = G(function(a, c) {
return m(a, c)
}, {assign: function(d, e) {
return gb(d, c, e, a.text, a.options)
}})
}
this.tokens.push(d);
g && (this.tokens.push({index: e, text: ".", json: !1}), this.tokens.push({index: e + 1, text: g, json: !1}))
}, readString: function(a) {
var c = this.index;
this.index++;
for (var d = "", e = a, f = !1; this.index < this.text.length; ) {
var g = this.text.charAt(this.index), e = e + g;
if (f)
"u" === g ? (g = this.text.substring(this.index + 1, this.index + 5), g.match(/[\da-f]{4}/i) || this.throwError("Invalid unicode escape [\\u" + g + "]"), this.index += 4, d += String.fromCharCode(parseInt(g, 16))) : d = (f = Md[g]) ? d + f : d + g, f = !1;
else if ("\\" === g)
f = !0;
else {
if (g === a) {
this.index++;
this.tokens.push({index: c, text: e, string: d, json: !0, fn: function() {
return d
}});
return
}
d += g
}
this.index++
}
this.throwError("Unterminated quote", c)
}};
var Ua = function(a, c, d) {
this.lexer = a;
this.$filter = c;
this.options = d
};
Ua.ZERO = function() {
return 0
};
Ua.prototype = {constructor: Ua, parse: function(a, c) {
this.text = a;
this.json = c;
this.tokens = this.lexer.lex(a);
c && (this.assignment = this.logicalOR, this.functionCall = this.fieldAccess = this.objectIndex = this.filterChain = function() {
this.throwError("is not valid json", {text: a,
index: 0})
});
var d = c ? this.primary() : this.statements();
0 !== this.tokens.length && this.throwError("is an unexpected token", this.tokens[0]);
d.literal = !!d.literal;
d.constant = !!d.constant;
return d
}, primary: function() {
var a;
if (this.expect("("))
a = this.filterChain(), this.consume(")");
else if (this.expect("["))
a = this.arrayDeclaration();
else if (this.expect("{"))
a = this.object();
else {
var c = this.expect();
(a = c.fn) || this.throwError("not a primary expression", c);
c.json && (a.constant = !0, a.literal = !0)
}
for (var d; c = this.expect("(",
"[", "."); )
"(" === c.text ? (a = this.functionCall(a, d), d = null) : "[" === c.text ? (d = a, a = this.objectIndex(a)) : "." === c.text ? (d = a, a = this.fieldAccess(a)) : this.throwError("IMPOSSIBLE");
return a
}, throwError: function(a, c) {
throw xa("syntax", c.text, a, c.index + 1, this.text, this.text.substring(c.index));
}, peekToken: function() {
if (0 === this.tokens.length)
throw xa("ueoe", this.text);
return this.tokens[0]
}, peek: function(a, c, d, e) {
if (0 < this.tokens.length) {
var f = this.tokens[0], g = f.text;
if (g === a || g === c || g === d || g === e || !(a || c || d || e))
return f
}
return!1
},
expect: function(a, c, d, e) {
return(a = this.peek(a, c, d, e)) ? (this.json && !a.json && this.throwError("is not valid json", a), this.tokens.shift(), a) : !1
}, consume: function(a) {
this.expect(a) || this.throwError("is unexpected, expecting [" + a + "]", this.peek())
}, unaryFn: function(a, c) {
return G(function(d, e) {
return a(d, e, c)
}, {constant: c.constant})
}, ternaryFn: function(a, c, d) {
return G(function(e, f) {
return a(e, f) ? c(e, f) : d(e, f)
}, {constant: a.constant && c.constant && d.constant})
}, binaryFn: function(a, c, d) {
return G(function(e, f) {
return c(e,
f, a, d)
}, {constant: a.constant && d.constant})
}, statements: function() {
for (var a = []; ; )
if (0 < this.tokens.length && !this.peek("}", ")", ";", "]") && a.push(this.filterChain()), !this.expect(";"))
return 1 === a.length ? a[0] : function(c, d) {
for (var e, f = 0; f < a.length; f++) {
var g = a[f];
g && (e = g(c, d))
}
return e
}
}, filterChain: function() {
for (var a = this.expression(), c; ; )
if (c = this.expect("|"))
a = this.binaryFn(a, c.fn, this.filter());
else
return a
}, filter: function() {
for (var a = this.expect(), c = this.$filter(a.text), d = []; ; )
if (a = this.expect(":"))
d.push(this.expression());
else {
var e = function(a, e, h) {
h = [h];
for (var m = 0; m < d.length; m++)
h.push(d[m](a, e));
return c.apply(a, h)
};
return function() {
return e
}
}
}, expression: function() {
return this.assignment()
}, assignment: function() {
var a = this.ternary(), c, d;
return(d = this.expect("=")) ? (a.assign || this.throwError("implies assignment but [" + this.text.substring(0, d.index) + "] can not be assigned to", d), c = this.ternary(), function(d, f) {
return a.assign(d, c(d, f), f)
}) : a
}, ternary: function() {
var a = this.logicalOR(), c, d;
if (this.expect("?")) {
c = this.ternary();
if (d = this.expect(":"))
return this.ternaryFn(a, c, this.ternary());
this.throwError("expected :", d)
} else
return a
}, logicalOR: function() {
for (var a = this.logicalAND(), c; ; )
if (c = this.expect("||"))
a = this.binaryFn(a, c.fn, this.logicalAND());
else
return a
}, logicalAND: function() {
var a = this.equality(), c;
if (c = this.expect("&&"))
a = this.binaryFn(a, c.fn, this.logicalAND());
return a
}, equality: function() {
var a = this.relational(), c;
if (c = this.expect("==", "!=", "===", "!=="))
a = this.binaryFn(a, c.fn, this.equality());
return a
},
relational: function() {
var a = this.additive(), c;
if (c = this.expect("<", ">", "<=", ">="))
a = this.binaryFn(a, c.fn, this.relational());
return a
}, additive: function() {
for (var a = this.multiplicative(), c; c = this.expect("+", "-"); )
a = this.binaryFn(a, c.fn, this.multiplicative());
return a
}, multiplicative: function() {
for (var a = this.unary(), c; c = this.expect("*", "/", "%"); )
a = this.binaryFn(a, c.fn, this.unary());
return a
}, unary: function() {
var a;
return this.expect("+") ? this.primary() : (a = this.expect("-")) ? this.binaryFn(Ua.ZERO, a.fn,
this.unary()) : (a = this.expect("!")) ? this.unaryFn(a.fn, this.unary()) : this.primary()
}, fieldAccess: function(a) {
var c = this, d = this.expect().text, e = oc(d, this.options, this.text);
return G(function(c, d, h) {
return e(h || a(c, d), d)
}, {assign: function(e, g, h) {
return gb(a(e, h), d, g, c.text, c.options)
}})
}, objectIndex: function(a) {
var c = this, d = this.expression();
this.consume("]");
return G(function(e, f) {
var g = a(e, f), h = d(e, f), m;
if (!g)
return s;
(g = fb(g[h], c.text)) && (g.then && c.options.unwrapPromises) && (m = g, "$$v"in g || (m.$$v = s,
m.then(function(a) {
m.$$v = a
})), g = g.$$v);
return g
}, {assign: function(e, f, g) {
var h = d(e, g);
return fb(a(e, g), c.text)[h] = f
}})
}, functionCall: function(a, c) {
var d = [];
if (")" !== this.peekToken().text) {
do
d.push(this.expression());
while (this.expect(","))
}
this.consume(")");
var e = this;
return function(f, g) {
for (var h = [], m = c ? c(f, g) : f, k = 0; k < d.length; k++)
h.push(d[k](f, g));
k = a(f, g, m) || v;
fb(k, e.text);
h = k.apply ? k.apply(m, h) : k(h[0], h[1], h[2], h[3], h[4]);
return fb(h, e.text)
}
}, arrayDeclaration: function() {
var a = [], c = !0;
if ("]" !==
this.peekToken().text) {
do {
var d = this.expression();
a.push(d);
d.constant || (c = !1)
} while (this.expect(","))
}
this.consume("]");
return G(function(c, d) {
for (var g = [], h = 0; h < a.length; h++)
g.push(a[h](c, d));
return g
}, {literal: !0, constant: c})
}, object: function() {
var a = [], c = !0;
if ("}" !== this.peekToken().text) {
do {
var d = this.expect(), d = d.string || d.text;
this.consume(":");
var e = this.expression();
a.push({key: d, value: e});
e.constant || (c = !1)
} while (this.expect(","))
}
this.consume("}");
return G(function(c, d) {
for (var e = {}, m =
0; m < a.length; m++) {
var k = a[m];
e[k.key] = k.value(c, d)
}
return e
}, {literal: !0, constant: c})
}};
var Gb = {}, sa = D("$sce"), ea = {HTML: "html", CSS: "css", URL: "url", RESOURCE_URL: "resourceUrl", JS: "js"}, V = R.createElement("a"), rc = wa(Y.location.href, !0);
sc.$inject = ["$provide"];
tc.$inject = ["$locale"];
vc.$inject = ["$locale"];
var yc = ".", Gd = {yyyy: X("FullYear", 4), yy: X("FullYear", 2, 0, !0), y: X("FullYear", 1), MMMM: hb("Month"), MMM: hb("Month", !0), MM: X("Month", 2, 1), M: X("Month", 1, 1), dd: X("Date", 2), d: X("Date", 1), HH: X("Hours", 2), H: X("Hours",
1), hh: X("Hours", 2, -12), h: X("Hours", 1, -12), mm: X("Minutes", 2), m: X("Minutes", 1), ss: X("Seconds", 2), s: X("Seconds", 1), sss: X("Milliseconds", 3), EEEE: hb("Day"), EEE: hb("Day", !0), a: function(a, c) {
return 12 > a.getHours() ? c.AMPMS[0] : c.AMPMS[1]
}, Z: function(a) {
a = -1 * a.getTimezoneOffset();
return a = (0 <= a ? "+" : "") + (Ib(Math[0 < a ? "floor" : "ceil"](a / 60), 2) + Ib(Math.abs(a % 60), 2))
}}, Fd = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, Ed = /^\-?\d+$/;
uc.$inject = ["$locale"];
var Cd = aa(B), Dd = aa(Ea);
wc.$inject =
["$parse"];
var Nd = aa({restrict: "E", compile: function(a, c) {
8 >= Q && (c.href || c.name || c.$set("href", ""), a.append(R.createComment("IE fix")));
return function(a, c) {
c.on("click", function(a) {
c.attr("href") || a.preventDefault()
})
}
}}), Kb = {};
p(cb, function(a, c) {
if ("multiple" != a) {
var d = la("ng-" + c);
Kb[d] = function() {
return{priority: 100, compile: function() {
return function(a, f, g) {
a.$watch(g[d], function(a) {
g.$set(c, !!a)
})
}
}}
}
}
});
p(["src", "srcset", "href"], function(a) {
var c = la("ng-" + a);
Kb[c] = function() {
return{priority: 99,
link: function(d, e, f) {
f.$observe(c, function(c) {
c && (f.$set(a, c), Q && e.prop(a, f[a]))
})
}}
}
});
var kb = {$addControl: v, $removeControl: v, $setValidity: v, $setDirty: v, $setPristine: v};
zc.$inject = ["$element", "$attrs", "$scope"];
var Bc = function(a) {
return["$timeout", function(c) {
return{name: "form", restrict: a ? "EAC" : "E", controller: zc, compile: function() {
return{pre: function(a, e, f, g) {
if (!f.action) {
var h = function(a) {
a.preventDefault ? a.preventDefault() : a.returnValue = !1
};
Ac(e[0], "submit", h);
e.on("$destroy", function() {
c(function() {
xb(e[0],
"submit", h)
}, 0, !1)
})
}
var m = e.parent().controller("form"), k = f.name || f.ngForm;
k && gb(a, k, g, k);
if (m)
e.on("$destroy", function() {
m.$removeControl(g);
k && gb(a, k, s, k);
G(g, kb)
})
}}
}}
}]
}, Od = Bc(), Pd = Bc(!0), Qd = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/, Rd = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/, Sd = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/, Cc = {text: mb, number: function(a, c, d, e, f, g) {
mb(a, c, d, e, f, g);
e.$parsers.push(function(a) {
var c = e.$isEmpty(a);
if (c || Sd.test(a))
return e.$setValidity("number",
!0), "" === a ? null : c ? a : parseFloat(a);
e.$setValidity("number", !1);
return s
});
e.$formatters.push(function(a) {
return e.$isEmpty(a) ? "" : "" + a
});
if (d.min) {
var h = parseFloat(d.min);
a = function(a) {
if (!e.$isEmpty(a) && a < h)
return e.$setValidity("min", !1), s;
e.$setValidity("min", !0);
return a
};
e.$parsers.push(a);
e.$formatters.push(a)
}
if (d.max) {
var m = parseFloat(d.max);
d = function(a) {
if (!e.$isEmpty(a) && a > m)
return e.$setValidity("max", !1), s;
e.$setValidity("max", !0);
return a
};
e.$parsers.push(d);
e.$formatters.push(d)
}
e.$formatters.push(function(a) {
if (e.$isEmpty(a) ||
ob(a))
return e.$setValidity("number", !0), a;
e.$setValidity("number", !1);
return s
})
}, url: function(a, c, d, e, f, g) {
mb(a, c, d, e, f, g);
a = function(a) {
if (e.$isEmpty(a) || Qd.test(a))
return e.$setValidity("url", !0), a;
e.$setValidity("url", !1);
return s
};
e.$formatters.push(a);
e.$parsers.push(a)
}, email: function(a, c, d, e, f, g) {
mb(a, c, d, e, f, g);
a = function(a) {
if (e.$isEmpty(a) || Rd.test(a))
return e.$setValidity("email", !0), a;
e.$setValidity("email", !1);
return s
};
e.$formatters.push(a);
e.$parsers.push(a)
}, radio: function(a, c, d,
e) {
z(d.name) && c.attr("name", Va());
c.on("click", function() {
c[0].checked && a.$apply(function() {
e.$setViewValue(d.value)
})
});
e.$render = function() {
c[0].checked = d.value == e.$viewValue
};
d.$observe("value", e.$render)
}, checkbox: function(a, c, d, e) {
var f = d.ngTrueValue, g = d.ngFalseValue;
F(f) || (f = !0);
F(g) || (g = !1);
c.on("click", function() {
a.$apply(function() {
e.$setViewValue(c[0].checked)
})
});
e.$render = function() {
c[0].checked = e.$viewValue
};
e.$isEmpty = function(a) {
return a !== f
};
e.$formatters.push(function(a) {
return a ===
f
});
e.$parsers.push(function(a) {
return a ? f : g
})
}, hidden: v, button: v, submit: v, reset: v}, Dc = ["$browser", "$sniffer", function(a, c) {
return{restrict: "E", require: "?ngModel", link: function(d, e, f, g) {
g && (Cc[B(f.type)] || Cc.text)(d, e, f, g, c, a)
}}
}], jb = "ng-valid", ib = "ng-invalid", Fa = "ng-pristine", lb = "ng-dirty", Td = ["$scope", "$exceptionHandler", "$attrs", "$element", "$parse", function(a, c, d, e, f) {
function g(a, c) {
c = c ? "-" + $a(c, "-") : "";
e.removeClass((a ? ib : jb) + c).addClass((a ? jb : ib) + c)
}
this.$modelValue = this.$viewValue = Number.NaN;
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$pristine = !0;
this.$dirty = !1;
this.$valid = !0;
this.$invalid = !1;
this.$name = d.name;
var h = f(d.ngModel), m = h.assign;
if (!m)
throw D("ngModel")("nonassign", d.ngModel, ga(e));
this.$render = v;
this.$isEmpty = function(a) {
return z(a) || "" === a || null === a || a !== a
};
var k = e.inheritedData("$formController") || kb, l = 0, r = this.$error = {};
e.addClass(Fa);
g(!0);
this.$setValidity = function(a, c) {
r[a] !== !c && (c ? (r[a] && l--, l || (g(!0), this.$valid = !0, this.$invalid = !1)) : (g(!1),
this.$invalid = !0, this.$valid = !1, l++), r[a] = !c, g(c, a), k.$setValidity(a, c, this))
};
this.$setPristine = function() {
this.$dirty = !1;
this.$pristine = !0;
e.removeClass(lb).addClass(Fa)
};
this.$setViewValue = function(d) {
this.$viewValue = d;
this.$pristine && (this.$dirty = !0, this.$pristine = !1, e.removeClass(Fa).addClass(lb), k.$setDirty());
p(this.$parsers, function(a) {
d = a(d)
});
this.$modelValue !== d && (this.$modelValue = d, m(a, d), p(this.$viewChangeListeners, function(a) {
try {
a()
} catch (d) {
c(d)
}
}))
};
var q = this;
a.$watch(function() {
var c =
h(a);
if (q.$modelValue !== c) {
var d = q.$formatters, e = d.length;
for (q.$modelValue = c; e--; )
c = d[e](c);
q.$viewValue !== c && (q.$viewValue = c, q.$render())
}
})
}], Ud = function() {
return{require: ["ngModel", "^?form"], controller: Td, link: function(a, c, d, e) {
var f = e[0], g = e[1] || kb;
g.$addControl(f);
c.on("$destroy", function() {
g.$removeControl(f)
})
}}
}, Vd = aa({require: "ngModel", link: function(a, c, d, e) {
e.$viewChangeListeners.push(function() {
a.$eval(d.ngChange)
})
}}), Ec = function() {
return{require: "?ngModel", link: function(a, c, d, e) {
if (e) {
d.required =
!0;
var f = function(a) {
if (d.required && e.$isEmpty(a))
e.$setValidity("required", !1);
else
return e.$setValidity("required", !0), a
};
e.$formatters.push(f);
e.$parsers.unshift(f);
d.$observe("required", function() {
f(e.$viewValue)
})
}
}}
}, Wd = function() {
return{require: "ngModel", link: function(a, c, d, e) {
var f = (a = /\/(.*)\//.exec(d.ngList)) && RegExp(a[1]) || d.ngList || ",";
e.$parsers.push(function(a) {
if (!z(a)) {
var c = [];
a && p(a.split(f), function(a) {
a && c.push(ba(a))
});
return c
}
});
e.$formatters.push(function(a) {
return H(a) ? a.join(", ") :
s
});
e.$isEmpty = function(a) {
return!a || !a.length
}
}}
}, Xd = /^(true|false|\d+)$/, Yd = function() {
return{priority: 100, compile: function(a, c) {
return Xd.test(c.ngValue) ? function(a, c, f) {
f.$set("value", a.$eval(f.ngValue))
} : function(a, c, f) {
a.$watch(f.ngValue, function(a) {
f.$set("value", a)
})
}
}}
}, Zd = ta(function(a, c, d) {
c.addClass("ng-binding").data("$binding", d.ngBind);
a.$watch(d.ngBind, function(a) {
c.text(a == s ? "" : a)
})
}), $d = ["$interpolate", function(a) {
return function(c, d, e) {
c = a(d.attr(e.$attr.ngBindTemplate));
d.addClass("ng-binding").data("$binding",
c);
e.$observe("ngBindTemplate", function(a) {
d.text(a)
})
}
}], ae = ["$sce", "$parse", function(a, c) {
return function(d, e, f) {
e.addClass("ng-binding").data("$binding", f.ngBindHtml);
var g = c(f.ngBindHtml);
d.$watch(function() {
return(g(d) || "").toString()
}, function(c) {
e.html(a.getTrustedHtml(g(d)) || "")
})
}
}], be = Jb("", !0), ce = Jb("Odd", 0), de = Jb("Even", 1), ee = ta({compile: function(a, c) {
c.$set("ngCloak", s);
a.removeClass("ng-cloak")
}}), fe = [function() {
return{scope: !0, controller: "@"}
}], ge = ["$sniffer", function(a) {
return{priority: 1E3,
compile: function() {
a.csp = !0
}}
}], Fc = {};
p("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "), function(a) {
var c = la("ng-" + a);
Fc[c] = ["$parse", function(d) {
return function(e, f, g) {
var h = d(g[c]);
f.on(B(a), function(a) {
e.$apply(function() {
h(e, {$event: a})
})
})
}
}]
});
var he = ["$animate", function(a) {
return{transclude: "element", priority: 600, terminal: !0, restrict: "A", compile: function(c, d, e) {
return function(c, d, h) {
var m,
k;
c.$watch(h.ngIf, function(h) {
m && (a.leave(m), m = s);
k && (k.$destroy(), k = s);
Ka(h) && (k = c.$new(), e(k, function(c) {
m = c;
a.enter(c, d.parent(), d)
}))
})
}
}}
}], ie = ["$http", "$templateCache", "$anchorScroll", "$compile", "$animate", "$sce", function(a, c, d, e, f, g) {
return{restrict: "ECA", priority: 400, terminal: !0, transclude: "element", compile: function(h, m, k) {
var l = m.ngInclude || m.src, p = m.onload || "", q = m.autoscroll;
return function(h, m) {
var s = 0, C, u, x = function() {
C && (C.$destroy(), C = null);
u && (f.leave(u), u = null)
};
h.$watch(g.parseAsResourceUrl(l),
function(g) {
var l = ++s;
g ? (a.get(g, {cache: c}).success(function(a) {
if (l === s) {
var c = h.$new();
k(c, function(g) {
x();
C = c;
u = g;
u.html(a);
f.enter(u, null, m);
e(u.contents())(C);
!w(q) || q && !h.$eval(q) || d();
C.$emit("$includeContentLoaded");
h.$eval(p)
})
}
}).error(function() {
l === s && x()
}), h.$emit("$includeContentRequested")) : x()
})
}
}}
}], je = ta({compile: function() {
return{pre: function(a, c, d) {
a.$eval(d.ngInit)
}}
}}), ke = ta({terminal: !0, priority: 1E3}), le = ["$locale", "$interpolate", function(a, c) {
var d = /{}/g;
return{restrict: "EA",
link: function(e, f, g) {
var h = g.count, m = g.$attr.when && f.attr(g.$attr.when), k = g.offset || 0, l = e.$eval(m) || {}, r = {}, q = c.startSymbol(), n = c.endSymbol(), s = /^when(Minus)?(.+)$/;
p(g, function(a, c) {
s.test(c) && (l[B(c.replace("when", "").replace("Minus", "-"))] = f.attr(g.$attr[c]))
});
p(l, function(a, e) {
r[e] = c(a.replace(d, q + h + "-" + k + n))
});
e.$watch(function() {
var c = parseFloat(e.$eval(h));
if (isNaN(c))
return"";
c in l || (c = a.pluralCat(c - k));
return r[c](e, f, !0)
}, function(a) {
f.text(a)
})
}}
}], me = ["$parse", "$animate", function(a,
c) {
function d(a) {
if (a.startNode === a.endNode)
return x(a.startNode);
var c = a.startNode, d = [c];
do {
c = c.nextSibling;
if (!c)
break;
d.push(c)
} while (c !== a.endNode);
return x(d)
}
var e = D("ngRepeat");
return{transclude: "element", priority: 1E3, terminal: !0, compile: function(f, g, h) {
return function(f, g, l) {
var r = l.ngRepeat, q = r.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/), n, s, w, C, u, v, B, t = {$id: Ca};
if (!q)
throw e("iexp", r);
l = q[1];
u = q[2];
(q = q[4]) ? (n = a(q), s = function(a, c, d) {
B && (t[B] = a);
t[v] = c;
t.$index = d;
return n(f,
t)
}) : (w = function(a, c) {
return Ca(c)
}, C = function(a) {
return a
});
q = l.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!q)
throw e("iidexp", l);
v = q[3] || q[1];
B = q[2];
var F = {};
f.$watchCollection(u, function(a) {
var l, q, n = g[0], u, t = {}, G, D, O, P, H, K, z = [];
if (nb(a))
H = a, u = s || w;
else {
u = s || C;
H = [];
for (O in a)
a.hasOwnProperty(O) && "$" != O.charAt(0) && H.push(O);
H.sort()
}
G = H.length;
q = z.length = H.length;
for (l = 0; l < q; l++)
if (O = a === H ? l : H[l], P = a[O], P = u(O, P, l), pa(P, "`track by` id"), F.hasOwnProperty(P))
K = F[P], delete F[P], t[P] =
K, z[l] = K;
else {
if (t.hasOwnProperty(P))
throw p(z, function(a) {
a && a.startNode && (F[a.id] = a)
}), e("dupes", r, P);
z[l] = {id: P};
t[P] = !1
}
for (O in F)
F.hasOwnProperty(O) && (K = F[O], l = d(K), c.leave(l), p(l, function(a) {
a.$$NG_REMOVED = !0
}), K.scope.$destroy());
l = 0;
for (q = H.length; l < q; l++) {
O = a === H ? l : H[l];
P = a[O];
K = z[l];
z[l - 1] && (n = z[l - 1].endNode);
if (K.startNode) {
D = K.scope;
u = n;
do
u = u.nextSibling;
while (u && u.$$NG_REMOVED);
K.startNode != u && c.move(d(K), null, x(n));
n = K.endNode
} else
D = f.$new();
D[v] = P;
B && (D[B] = O);
D.$index = l;
D.$first =
0 === l;
D.$last = l === G - 1;
D.$middle = !(D.$first || D.$last);
D.$odd = !(D.$even = 0 == l % 2);
K.startNode || h(D, function(a) {
a[a.length++] = R.createComment(" end ngRepeat: " + r + " ");
c.enter(a, null, x(n));
n = a;
K.scope = D;
K.startNode = n && n.endNode ? n.endNode : a[0];
K.endNode = a[a.length - 1];
t[K.id] = K
})
}
F = t
})
}
}}
}], ne = ["$animate", function(a) {
return function(c, d, e) {
c.$watch(e.ngShow, function(c) {
a[Ka(c) ? "removeClass" : "addClass"](d, "ng-hide")
})
}
}], oe = ["$animate", function(a) {
return function(c, d, e) {
c.$watch(e.ngHide, function(c) {
a[Ka(c) ?
"addClass" : "removeClass"](d, "ng-hide")
})
}
}], pe = ta(function(a, c, d) {
a.$watch(d.ngStyle, function(a, d) {
d && a !== d && p(d, function(a, d) {
c.css(d, "")
});
a && c.css(a)
}, !0)
}), qe = ["$animate", function(a) {
return{restrict: "EA", require: "ngSwitch", controller: ["$scope", function() {
this.cases = {}
}], link: function(c, d, e, f) {
var g, h, m = [];
c.$watch(e.ngSwitch || e.on, function(d) {
for (var l = 0, r = m.length; l < r; l++)
m[l].$destroy(), a.leave(h[l]);
h = [];
m = [];
if (g = f.cases["!" + d] || f.cases["?"])
c.$eval(e.change), p(g, function(d) {
var e = c.$new();
m.push(e);
d.transclude(e, function(c) {
var e = d.element;
h.push(c);
a.enter(c, e.parent(), e)
})
})
})
}}
}], re = ta({transclude: "element", priority: 800, require: "^ngSwitch", compile: function(a, c, d) {
return function(a, f, g, h) {
h.cases["!" + c.ngSwitchWhen] = h.cases["!" + c.ngSwitchWhen] || [];
h.cases["!" + c.ngSwitchWhen].push({transclude: d, element: f})
}
}}), se = ta({transclude: "element", priority: 800, require: "^ngSwitch", compile: function(a, c, d) {
return function(a, c, g, h) {
h.cases["?"] = h.cases["?"] || [];
h.cases["?"].push({transclude: d,
element: c})
}
}}), te = ta({controller: ["$element", "$transclude", function(a, c) {
if (!c)
throw D("ngTransclude")("orphan", ga(a));
this.$transclude = c
}], link: function(a, c, d, e) {
e.$transclude(function(a) {
c.html("");
c.append(a)
})
}}), ue = ["$templateCache", function(a) {
return{restrict: "E", terminal: !0, compile: function(c, d) {
"text/ng-template" == d.type && a.put(d.id, c[0].text)
}}
}], ve = D("ngOptions"), we = aa({terminal: !0}), xe = ["$compile", "$parse", function(a, c) {
var d = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/,
e = {$setViewValue: v};
return{restrict: "E", require: ["select", "?ngModel"], controller: ["$element", "$scope", "$attrs", function(a, c, d) {
var m = this, k = {}, l = e, p;
m.databound = d.ngModel;
m.init = function(a, c, d) {
l = a;
p = d
};
m.addOption = function(c) {
pa(c, '"option value"');
k[c] = !0;
l.$viewValue == c && (a.val(c), p.parent() && p.remove())
};
m.removeOption = function(a) {
this.hasOption(a) && (delete k[a], l.$viewValue == a && this.renderUnknownOption(a))
};
m.renderUnknownOption = function(c) {
c = "? " + Ca(c) + " ?";
p.val(c);
a.prepend(p);
a.val(c);
p.prop("selected",
!0)
};
m.hasOption = function(a) {
return k.hasOwnProperty(a)
};
c.$on("$destroy", function() {
m.renderUnknownOption = v
})
}], link: function(e, g, h, m) {
function k(a, c, d, e) {
d.$render = function() {
var a = d.$viewValue;
e.hasOption(a) ? (t.parent() && t.remove(), c.val(a), "" === a && u.prop("selected", !0)) : z(a) && u ? c.val("") : e.renderUnknownOption(a)
};
c.on("change", function() {
a.$apply(function() {
t.parent() && t.remove();
d.$setViewValue(c.val())
})
})
}
function l(a, c, d) {
var e;
d.$render = function() {
var a = new Pa(d.$viewValue);
p(c.find("option"),
function(c) {
c.selected = w(a.get(c.value))
})
};
a.$watch(function() {
Aa(e, d.$viewValue) || (e = fa(d.$viewValue), d.$render())
});
c.on("change", function() {
a.$apply(function() {
var a = [];
p(c.find("option"), function(c) {
c.selected && a.push(c.value)
});
d.$setViewValue(a)
})
})
}
function r(e, f, h) {
function g() {
var a = {"": []}, c = [""], d, k, t, v, x;
v = h.$modelValue;
x = r(e) || [];
var B = n ? Lb(x) : x, G, z, A;
z = {};
t = !1;
var E, J;
if (y)
if (u && H(v))
for (t = new Pa([]), A = 0; A < v.length; A++)
z[m] = v[A], t.put(u(e, z), v[A]);
else
t = new Pa(v);
for (A = 0; G = B.length,
A < G; A++) {
k = A;
if (n) {
k = B[A];
if ("$" === k.charAt(0))
continue;
z[n] = k
}
z[m] = x[k];
d = q(e, z) || "";
(k = a[d]) || (k = a[d] = [], c.push(d));
y ? d = t.remove(u ? u(e, z) : p(e, z)) !== s : (u ? (d = {}, d[m] = v, d = u(e, d) === u(e, z)) : d = v === p(e, z), t = t || d);
E = l(e, z);
E = E === s ? "" : E;
k.push({id: u ? u(e, z) : n ? B[A] : A, label: E, selected: d})
}
y || (C || null === v ? a[""].unshift({id: "", label: "", selected: !t}) : t || a[""].unshift({id: "?", label: "", selected: !0}));
z = 0;
for (B = c.length; z < B; z++) {
d = c[z];
k = a[d];
w.length <= z ? (v = {element: F.clone().attr("label", d), label: k.label}, x = [v],
w.push(x), f.append(v.element)) : (x = w[z], v = x[0], v.label != d && v.element.attr("label", v.label = d));
E = null;
A = 0;
for (G = k.length; A < G; A++)
t = k[A], (d = x[A + 1]) ? (E = d.element, d.label !== t.label && E.text(d.label = t.label), d.id !== t.id && E.val(d.id = t.id), E[0].selected !== t.selected && E.prop("selected", d.selected = t.selected)) : ("" === t.id && C ? J = C : (J = D.clone()).val(t.id).attr("selected", t.selected).text(t.label), x.push({element: J, label: t.label, id: t.id, selected: t.selected}), E ? E.after(J) : v.element.append(J), E = J);
for (A++; x.length >
A; )
x.pop().element.remove()
}
for (; w.length > z; )
w.pop()[0].element.remove()
}
var k;
if (!(k = v.match(d)))
throw ve("iexp", v, ga(f));
var l = c(k[2] || k[1]), m = k[4] || k[6], n = k[5], q = c(k[3] || ""), p = c(k[2] ? k[1] : m), r = c(k[7]), u = k[8] ? c(k[8]) : null, w = [[{element: f, label: ""}]];
C && (a(C)(e), C.removeClass("ng-scope"), C.remove());
f.html("");
f.on("change", function() {
e.$apply(function() {
var a, c = r(e) || [], d = {}, g, k, l, q, t, v, x;
if (y)
for (k = [], q = 0, v = w.length; q < v; q++)
for (a = w[q], l = 1, t = a.length; l < t; l++) {
if ((g = a[l].element)[0].selected) {
g = g.val();
n && (d[n] = g);
if (u)
for (x = 0; x < c.length && (d[m] = c[x], u(e, d) != g); x++)
;
else
d[m] = c[g];
k.push(p(e, d))
}
}
else if (g = f.val(), "?" == g)
k = s;
else if ("" == g)
k = null;
else if (u)
for (x = 0; x < c.length; x++) {
if (d[m] = c[x], u(e, d) == g) {
k = p(e, d);
break
}
}
else
d[m] = c[g], n && (d[n] = g), k = p(e, d);
h.$setViewValue(k)
})
});
h.$render = g;
e.$watch(g)
}
if (m[1]) {
var q = m[0], n = m[1], y = h.multiple, v = h.ngOptions, C = !1, u, D = x(R.createElement("option")), F = x(R.createElement("optgroup")), t = D.clone();
m = 0;
for (var B = g.children(), G = B.length; m < G; m++)
if ("" == B[m].value) {
u =
C = B.eq(m);
break
}
q.init(n, C, t);
if (y && (h.required || h.ngRequired)) {
var E = function(a) {
n.$setValidity("required", !h.required || a && a.length);
return a
};
n.$parsers.push(E);
n.$formatters.unshift(E);
h.$observe("required", function() {
E(n.$viewValue)
})
}
v ? r(e, g, n) : y ? l(e, g, n) : k(e, g, n, q)
}
}}
}], ye = ["$interpolate", function(a) {
var c = {addOption: v, removeOption: v};
return{restrict: "E", priority: 100, compile: function(d, e) {
if (z(e.value)) {
var f = a(d.text(), !0);
f || e.$set("value", d.text())
}
return function(a, d, e) {
var k = d.parent(),
l = k.data("$selectController") || k.parent().data("$selectController");
l && l.databound ? d.prop("selected", !1) : l = c;
f ? a.$watch(f, function(a, c) {
e.$set("value", a);
a !== c && l.removeOption(c);
l.addOption(a)
}) : l.addOption(e.value);
d.on("$destroy", function() {
l.removeOption(e.value)
})
}
}}
}], ze = aa({restrict: "E", terminal: !0});
(Ba = Y.jQuery) ? (x = Ba, G(Ba.fn, {scope: Sa.scope, controller: Sa.controller, injector: Sa.injector, inheritedData: Sa.inheritedData}), tb("remove", !0, !0, !1), tb("empty", !1, !1, !1), tb("html", !1, !1, !0)) : x = J;
Za.element =
x;
(function(a) {
G(a, {bootstrap: Sb, copy: fa, extend: G, equals: Aa, element: x, forEach: p, injector: Tb, noop: v, bind: pb, toJson: oa, fromJson: Ob, identity: za, isUndefined: z, isDefined: w, isString: F, isFunction: E, isObject: S, isNumber: ob, isElement: Ic, isArray: H, $$minErr: D, version: Id, isDate: Ha, lowercase: B, uppercase: Ea, callbacks: {counter: 0}});
Ra = Oc(Y);
try {
Ra("ngLocale")
} catch (c) {
Ra("ngLocale", []).provider("$locale", ld)
}
Ra("ng", ["ngLocale"], ["$provide", function(a) {
a.provider("$compile", bc).directive({a: Nd, input: Dc, textarea: Dc,
form: Od, script: ue, select: xe, style: ze, option: ye, ngBind: Zd, ngBindHtml: ae, ngBindTemplate: $d, ngClass: be, ngClassEven: de, ngClassOdd: ce, ngCsp: ge, ngCloak: ee, ngController: fe, ngForm: Pd, ngHide: oe, ngIf: he, ngInclude: ie, ngInit: je, ngNonBindable: ke, ngPluralize: le, ngRepeat: me, ngShow: ne, ngStyle: pe, ngSwitch: qe, ngSwitchWhen: re, ngSwitchDefault: se, ngOptions: we, ngTransclude: te, ngModel: Ud, ngList: Wd, ngChange: Vd, required: Ec, ngRequired: Ec, ngValue: Yd}).directive(Kb).directive(Fc);
a.provider({$anchorScroll: Xc, $animate: Kd, $browser: Zc,
$cacheFactory: $c, $controller: cd, $document: dd, $exceptionHandler: ed, $filter: sc, $interpolate: jd, $interval: kd, $http: fd, $httpBackend: gd, $location: nd, $log: od, $parse: pd, $rootScope: sd, $q: qd, $sce: vd, $sceDelegate: ud, $sniffer: wd, $templateCache: ad, $timeout: xd, $window: yd})
}])
})(Za);
x(R).ready(function() {
Mc(R, Sb)
})
})(window, document);
angular.element(document).find("head").prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}</style>');
//# sourceMappingURL=angular.min.js.map
|
const xlsx = require('xlsx');
const fs = require('fs');
function parseCsv(path, sep) {
const data = fs.readFileSync(path).toString().split('\n');
const header = data.shift().split(sep);
const results = [];
data.forEach(row => {
if (!row.trim().length) {return;}
const res = {};
row.split(sep).forEach((val, i) => {
const k = header[i].replace('\r', '');
const v = val.replace('\r', '');
res[k] = v;
});
results.push(res);
});
return {'data': results};
}
function parseFile(path) {
const extension = path.split('.').reverse()[0];
if (extension === 'csv') {
return parseCsv(path, ',');
}
if (extension === 'tsv') {
return parseCsv(path, '\t');
}
const data = xlsx.readFile(path);
const sheets = data.SheetNames;
const res = {};
sheets.forEach(sheetName => {
res[sheetName] = xlsx.utils.sheet_to_json(data.Sheets[sheetName]);
});
return res;
}
function parseAllFiles(dirPath) {
const res = {};
fs.readdirSync(dirPath)
.filter(name => /(csv|tsv|ods|xlsx)$/.test(name))
.forEach(filePath => {
const name = filePath.replace(/\./g, '_');
res[name] = parseFile(dirPath + '/' + filePath);
});
return res;
}
module.exports.parseFile = parseFile;
module.exports.parseAllFiles = parseAllFiles;
|
define([
"intern!object",
"intern/chai!assert",
"tests/support/helper"
], function ( registerSuite, assert, testHelper ) {
var signIn = testHelper.getAppUrl( "admin/auth/signin" );
registerSuite({
name: "Admin signin",
/** Check if sign in form is visible. */
"Sign in form is visible.": function () {
return this.remote
.get( signIn )
.setFindTimeout( testHelper.getTimeoutForPageAction() )
/** Only check if sign in form is vibisle. */
.findByCssSelector( "div.admin-auth" )
.isDisplayed()
.then( function ( visible ) {
assert.ok( visible, "Sign in form loaded." );
});
},
/** Check if form cannot be submited with invalid email. */
"Sign in form cannot be submitted with invalid email.": function () {
return this.remote
.get( signIn )
.setFindTimeout( testHelper.getTimeoutForPageAction() )
.findByCssSelector( "div.admin-auth" )
/** Type invalid email. */
.findByCssSelector( "input[name=\"email\"]" )
.type( "invalidEmail" )
.end()
.findByCssSelector( "button[type=\"submit\"]" )
.isEnabled()
.then( function ( disabled ) {
/** Assert that submit button is disabled. */
assert.notOk( disabled, "Submit button is disabled with invalid email typed." );
})
.end();
},
/** Check if form cannot be submited with empty password. */
"Sign in form cannot be submitted with no password.": function () {
return this.remote
.get( signIn )
.setFindTimeout( testHelper.getTimeoutForPageAction() )
.findByCssSelector( "div.admin-auth" )
/** Type valid, non-empty email. */
.findByCssSelector( "input[name=\"email\"]" )
.type( "valid@email.com" )
.end()
.findByCssSelector( "button[type=\"submit\"]" )
.isEnabled()
.then( function ( disabled ) {
/** Assert that submit button is disabled. */
assert.notOk( disabled, "Submit button is disabled when no password is typed." );
})
.end();
},
/** Check if form can be submited with credentials, and error is shown when credentials are invalid. */
"Sign in form with invalid credentials show error when submitted.": function () {
return this.remote
.get( signIn )
.setFindTimeout( testHelper.getTimeoutForPageAction() )
.findByCssSelector( "div.admin-auth" )
/** Type valid, non-empty email. */
.findByCssSelector( "input[name=\"email\"]" )
.type( "valid@email.com" )
.end()
/** Type valid, non-empty password. */
.findByCssSelector( "input[name=\"password\"]" )
.type( "invalidPassword" )
.end()
/** Submit form. */
.findByCssSelector( "button[type=\"submit\"]" )
.click()
.end()
.setFindTimeout( testHelper.getTimeoutForAjaxRequests() )
/** Find form's alert box. */
.findByCssSelector( ".alert.alert-danger" )
.isDisplayed()
.then( function ( displayed ) {
/** Assert that the allert box is visible. */
assert.ok( displayed );
})
.getVisibleText()
.then( function( text ) {
/** Assert that the alert box contains proper message. */
assert.include( text, "Authorization failed." );
})
.end();
},
/** Check if form can be submited with credentials, and user is redirected when credentials were valid. */
"Sign in form with valid credentials signs user in.": function () {
return this.remote
.get( signIn )
.setFindTimeout( testHelper.getTimeoutForPageAction() )
.findByCssSelector( "div.admin-auth" )
/** Type valid, non-empty email. */
.findByCssSelector( "input[name=\"email\"]" )
.type( testHelper.getAdminCredentials().email )
.end()
/** Type valid, non-empty password. */
.findByCssSelector( "input[name=\"password\"]" )
.type( testHelper.getAdminCredentials().password )
.end()
/** Submit form. */
.findByCssSelector( "button[type=\"submit\"]" )
.click()
.end()
.end()
.setFindTimeout( testHelper.getTimeoutForAjaxRequests() )
/** Assert that admin panel Angular app can be found, therefore authentication was successful. */
.findByCssSelector( "div[ng-app=\"admin\"]" )
.end();
}
});
});
|
// Auto initialize function for scroll to top
function animateToTop(event) {
event.preventDefault();
var scrollToTop = window.setInterval(function() {
var position = window.pageYOffset;
if (position > 0) {
window.scrollTo(0, position - 20);
console.log("text",event);
} else {
window.clearInterval(scrollToTop);
}
}, 8);
}
// Auto initialize function for scroll position
(function() {
var previousScroll = 0;
window.onscroll = function() {
var currentScroll = this.pageYOffset,
SCROLL_AFTER_POS = 200;
//while going down
if (currentScroll > previousScroll) {
bullbear.style.backgroundPosition = '2px -1px';
if (currentScroll > SCROLL_AFTER_POS) {
bullbear.style.transform = 'scale(1)';
bullbear.style.display = 'block';
}
} else {
bullbear.style.backgroundPosition = '2px -58px';
if (currentScroll < SCROLL_AFTER_POS) {
bullbear.style.transform = 'scale(0)';
bullbear.style.display = 'none';
}
}
previousScroll = currentScroll;
}
})();
var bullbear = document.getElementById('bullbear');
bullbear.addEventListener('click', animateToTop, false);
window.onload = function() {
document.getElementById('bestway').style.transform = "translateY(0px)";
document.getElementById('bestway').style.opacity = "1";
document.getElementById('learn-forex').style.transform = "scale(1)";
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:65c4257e1080f5fd253ab5f1d90a791215534d0bffa4ee71112004c47752c114
size 7551
|
import good from 'good';
import goodConsole from 'good-console';
import inert from 'inert';
import vision from 'vision';
export default [
{
register: good,
options: {
reporters: [{
reporter: goodConsole,
events: {
response: '*',
log: '*',
},
}],
},
},
{ register: inert },
{ register: vision },
];
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M17.73 12.02l3.98-3.98c.39-.39.39-1.02 0-1.41l-4.34-4.34a.9959.9959 0 00-1.41 0l-3.98 3.98L8 2.29C7.8 2.1 7.55 2 7.29 2c-.25 0-.51.1-.7.29L2.25 6.63c-.39.39-.39 1.02 0 1.41l3.98 3.98L2.25 16c-.39.39-.39 1.02 0 1.41l4.34 4.34c.39.39 1.02.39 1.41 0l3.98-3.98 3.98 3.98c.2.2.45.29.71.29.26 0 .51-.1.71-.29l4.34-4.34c.39-.39.39-1.02 0-1.41l-3.99-3.98zM12 9c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-4.71 1.96L3.66 7.34l3.63-3.63 3.62 3.62-3.62 3.63zM10 13c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2 2c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2-4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2.66 9.34l-3.63-3.62 3.63-3.63 3.62 3.62-3.62 3.63z" />
, 'HealingRounded');
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
angular.module('eappApp').controller('AccountController', ["$scope", "$http", "$mdToast", "eapp", "$company", "$rootScope", "appService", "$timeout", "$location", function($scope, $http, $mdToast, eapp, $company, $rootScope, appService, $timeout, $location)
{
"use strict";
var ctrl = this;
$scope.address =
{
name : ''
};
$scope.options = {
types: ['(cities)'],
componentRestrictions: { country: 'CA' }
};
$scope.false = false;
$scope.true = true;
$scope.enterVerificationNumber = true;
$scope.message = null;
$scope.confirm_password = null;
$scope.userPhoneVerified = false;
$scope.$watch('loggedUserClone', function(oldValue, newVale)
{
$scope.userPhoneVerified = !angular.isNullOrUndefined($scope.loggedUserClone) && parseInt($scope.loggedUserClone.phone_verified) === 1;
});
ctrl.statusChangeCallback = function(response)
{
if(response.status == 'not_authorized')
{
}
};
$scope.Init = function()
{
if(!appService.isUserLogged && appService.redirectToLogin)
{
window.location.href = appService.siteUrl.concat("/account/login");
}
$scope.load_icons();
var securityQuestionsPromise = eapp.getSecurityQuestions();
securityQuestionsPromise.then(function(response)
{
$scope.securityQuestions = response.data;
});
if($scope.isUserLogged && appService.loggedUser.company && appService.loggedUser.company.is_new == 1)
{
$scope.isNewAccount = true;
}
// Create a copy of the logged user
$scope.loggedUserClone = angular.copy(appService.loggedUser);
};
$rootScope.showSimpleToast = function(message, parent_id) {
$mdToast.show(
$mdToast.simple()
.textContent(message)
.position("left bottom")
.hideDelay(3000)
.parent(document.getElementById(parent_id))
);
};
$scope.load_icons = function()
{
$scope.icons =
{
person : appService.baseUrl + "/assets/icons/ic_person_white_24px.svg",
flag : appService.baseUrl + "/assets/icons/ic_flag_white_24px.svg",
place : appService.baseUrl + "/assets/icons/ic_place_white_24px.svg",
phone : appService.baseUrl + "/assets/icons/ic_local_phone_white_24px.svg",
email : appService.baseUrl + "/assets/icons/ic_email_white_24px.svg",
lock : appService.baseUrl + "/assets/icons/ic_lock_white_24px.svg",
favorite : appService.baseUrl + "/assets/icons/ic_favorite_white_24px.svg",
delete : appService.baseUrl + "/assets/icons/ic_delete_white_24px.svg",
add : appService.baseUrl + "/assets/icons/ic_add_circle_white_24px.svg",
search : appService.baseUrl + "/assets/icons/ic_search_black_24px.svg",
add_img : appService.baseUrl + "/assets/img/add_image.png"
};
};
$scope.user =
{
email : '',
password : '',
security_question_id : 1,
security_question_answer : '',
firstname : '',
lastname : '',
country : 'Canada',
state : 'Quebec',
city : '',
address : '',
postcode : '',
phone1 : '',
phone2 : '',
rememberme : false
};
$scope.profile =
{
country : 'Canada',
state : 'Quebec'
};
$scope.account =
{
security_question_id : 1
};
$scope.storeLogo = null;
$scope.submit_favorite_stores = function()
{
$scope.listChangedSuccess = false;
if($scope.selected_retailers.length < $scope.max_stores)
{
$scope.showSimpleToast("Vous devez sélectionner au moins "+$scope.max_stores+" magasins.", "select-store-box");
}
else
{
$scope.registering_user = true;
var formData = new FormData();
formData.append("selected_retailers", JSON.stringify($scope.selected_retailers));
formData.append("email", $scope.registered_email);
// Send request to server to get optimized list
$http.post( appService.siteUrl.concat("/account/submit_favorite_stores"),
formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined}}).then(
function(response)
{
if(response.data.success)
{
// redirect to login.
if(!$scope.isUserLogged)
{
window.sessionStorage.setItem("accountCreated", "Votre compte a été créé avec succès.");
window.location = appService.siteUrl.concat("/account/login");
}
else
{
$scope.listChangedSuccess = true;
$scope.listChangedSuccessMessage = "Votre liste de magasins a été modifiée.";
}
}
else
{
$scope.showSimpleToast("une erreur inattendue est apparue. Veuillez réessayer plus tard.", "select-store-box");
}
$scope.registering_user = false;
});
}
};
$scope.register = function()
{
$scope.message = null;
if($scope.signupForm.$valid)
{
var registrationPromise = eapp.registerUser($scope.user);
registrationPromise.then
(
function(result)
{
if(result.data.success)
{
appService.loggedUser = result.data.user;
window.sessionStorage.setItem('newAccount', 'true');
window.location = appService.siteUrl.concat("/account/account_created");
}
if(!result.data.success)
{
$scope.message = result.data.message;
$("html").animate({ scrollTop: 0 }, "slow");
}
},
function(error)
{
if(!error.data.success)
{
$scope.message = error.data.message;
}
}
);
}
};
$scope.imageChanged= function(image)
{
$scope.storeLogo = image;
};
$scope.creatingAccount = false;
$scope.registerCompany = function()
{
$scope.message = null;
if($scope.signupForm.$valid)
{
$scope.creatingAccount = true;
var registrationPromise = $company.register($scope.account, $scope.profile, $scope.company, $scope.storeLogo);
registrationPromise.then
(
function(result)
{
if(result.data.success)
{
appService.loggedUser = result.data.user;
$scope.creatingAccount = false;
// redirect to subscription selection page
window.location = appService.siteUrl.concat("/account/select_subscription");
}
if(!result.data.success)
{
$scope.message = result.data.message;
$scope.creatingAccount = false;
$("html").animate({ scrollTop: 0 }, "slow");
}
},
function(error)
{
if(!error.data.success)
{
$scope.timeoutPromise = $timeout(cancelTimeout, 5000);
$scope.message = error.data.message;
}
}
);
}
};
function cancelTimeout()
{
$scope.message = null;
$scope.saveProfileSucess = false;
$timeout.cancel($scope.timeoutPromise);
}
$scope.finishCompanyRegistration = function()
{
eapp.toggleIsNew().then(function(response)
{
if(response.data)
{
// Send the user to his account
window.location.href = appService.siteUrl.concat("/account");
}
});
};
$scope.login = function()
{
if($scope.loginForm.$valid)
{
var formData = new FormData();
formData.append("email", $scope.user.email);
formData.append("password", $scope.user.password);
formData.append("rememberme", $scope.user.rememberme ? 1 : 0);
// Send request to server to get optimized list
$http.post( appService.siteUrl.concat("/account/perform_login"),
formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined}}).then(
function(response)
{
if(response.data.success)
{
// redirect to home page.
window.location = appService.siteUrl.concat("/" + response.data.redirect);
}
else
{
$scope.message = response.data.message;
}
});
}
};
$scope.updateProfile = function()
{
if(!$scope.userInfoForm.$valid)
{
return;
}
$scope.saveProfileError = false;
$scope.saveProfileSucess = false;
var updatePromise = eapp.updateUserProfile($scope.loggedUserClone);
updatePromise.then
(
function(response)
{
if(response.data.success)
{
$scope.saveProfileSucess = true;
appService.loggedUser = response.data.user;
$scope.saveProfileSuccessMessage = "Les informations de votre profil ont été modifiées.";
document.getElementById('saveProfileSucess').scrollIntoView();
}
else
{
$scope.saveProfileError = true;
$scope.saveProfileErrorMessage = "Une erreur de serveur est survenue. Veuillez réessayer plus tard.";
document.getElementById('saveProfileError').scrollIntoView();
}
}
);
};
$scope.changePassword = function()
{
if(!$scope.userSecurityForm.$valid)
{
return;
}
$scope.changePasswordError = false;
$scope.changePasswordSuccess = false;
var formData = new FormData();
formData.append("old_password", $scope.old_password);
formData.append("password", $scope.password);
$http.post( appService.siteUrl.concat("/account/change_password"),
formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined}}).then(
function(response)
{
if(response.data.success)
{
$scope.changePasswordSuccess = true;
$scope.changePasswordSuccessMessage = response.data.message;
}
else
{
$scope.changePasswordError = true;
$scope.changePasswordErrorMessage = response.data.message;
}
});
};
$scope.changeSecurityQuestion = function()
{
if(!$scope.securityQuestionForm.$valid)
{
return;
}
$scope.changeSecurityQuestionError = false;
$scope.changeSecurityQuestionSuccess = false;
var formData = new FormData();
formData.append("security_question_answer", appService.loggedUser.security_question_answer);
formData.append("security_question_id", appService.loggedUser.security_question_id);
$http.post( appService.siteUrl.concat("/account/change_security_qa"),
formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined}}).then(
function(response)
{
if(response.data.success)
{
$scope.changeSecurityQuestionSuccess = true;
$scope.changeSecurityQuestionSuccessMessage = response.data.message;
}
else
{
$scope.changeSecurityQuestionError = true;
$scope.changeSecurityQuestionErrorMessage = response.data.message;
}
});
};
$scope.sendVerificationCode = function()
{
$scope.phoneNumberError = null;
var isValid = $("#phone").intlTelInput("isValidNumber");
if(isValid)
{
var intlNumber = $("#phone").intlTelInput("getNumber");
var sendVerificationPromise = eapp.sendVerification(intlNumber);
sendVerificationPromise.then(function(response)
{
if(response.data)
{
$scope.enterVerificationNumber = false;
}
});
}
else
{
var error = $("#phone").intlTelInput("getValidationError");
switch(error)
{
case intlTelInputUtils.validationError.IS_POSSIBLE:
$scope.phoneNumberError = "";
break;
case intlTelInputUtils.validationError.INVALID_COUNTRY_CODE:
$scope.phoneNumberError = "Le pays n'est pas valide";
break;
case intlTelInputUtils.validationError.TOO_SHORT:
$scope.phoneNumberError = "Le numéro de téléphone entré est trop court";
break;
case intlTelInputUtils.validationError.TOO_LONG:
$scope.phoneNumberError = "Le numéro de téléphone entré est trop long";
break;
case intlTelInputUtils.validationError.NOT_A_NUMBER:
$scope.phoneNumberError = "Le numéro de téléphone entré n'est pas valide.";
break;
default:
$scope.phoneNumberError = "Le numéro de téléphone entré n'est pas valide.";
break;
}
}
};
$scope.validateCode = function()
{
$scope.validateCodeMessage = null;
var validatePromise = eapp.validateCode($scope.verificationCode);
validatePromise.then(function(response)
{
if(response.data.success)
{
appService.loggedUser.phone_verified = 1;
$scope.enterVerificationNumber = true;
$scope.validateCodeMessage = response.data.message;
}
else
{
$scope.validateCodeMessage = response.data.message;
}
});
};
appService.ready.then(function()
{
if($("#phone").length == 1)
{
$("#phone").intlTelInput({utilsScript : `${appService.baseUrl}/node_modules/intl-tel-input/build/js/utils.js`});
}
$scope.Init();
});
}]);
|
import React from 'react';
import { mount } from 'enzyme';
import sinon from 'sinon';
import LoginPage from '../LoginPage';
import DocumentTitle from 'react-document-title';
import { APP_NAME } from '../../constants/AppConstants';
describe('<LoginPage/>', () => {
var wrapper;
beforeEach(() => {
jest.resetModules();
wrapper = mount(<LoginPage/>);
});
it('should initialize with empty state', () => {
expect(wrapper.state('user')).toBe('');
expect(wrapper.state('password')).toBe('');
});
it('should render <DocumentTitle/>', () => {
expect(wrapper.find(DocumentTitle).length).toBe(1);
expect(wrapper.find(DocumentTitle).props().title).toEqual('Login // ' + APP_NAME);
});
it('should render input field for username', () => {
let field = wrapper.find('input[id="user"]');
expect(field.length).toBe(1);
expect(field.props().value).toBe('');
expect(field.props().onChange).toBeDefined();
expect(typeof field.props().onChange).toBe('function');
field.simulate('change', { target: { id: 'user', value: 'test' } });
expect(wrapper.state('user')).toBe('test');
expect(field.props().value).toBe('test');
});
it('should render input field for password', () => {
let field = wrapper.find('input[id="password"]');
expect(field.length).toBe(1);
expect(field.props().value).toBe('');
expect(field.props().type).toBe('password');
expect(field.props().onChange).toBeDefined();
expect(typeof field.props().onChange).toBe('function');
field.simulate('change', { target: { id: 'password', value: 'password' } });
expect(wrapper.state('password')).toBe('password');
expect(field.props().value).toBe('password');
});
it('should render submit button', () => {
sinon.spy(LoginPage.prototype, 'login');
jest.resetModules();
wrapper = mount(<LoginPage/>);
let button = wrapper.find('button[type="submit"]');
expect(button.length).toBe(1);
expect(button.props().onClick).toBeDefined();
expect(typeof button.props().onClick).toBe('function');
button.simulate('click');
expect(LoginPage.prototype.login.callCount).toBe(1);
LoginPage.prototype.login.restore();
});
}); |
'use strict';
describe('iceDummy:', function() {
describe('test by using custom mock + spyOn another service before instantiating your service (to test service calls during instantiation):', function() {
var getCurrentWeatherCallBacker = {};
var currentWeatherResourceCallBacker = {};
var getGithubReposOfUserCallBacker = {};
var iceDummyResourceMock = {
getCurrentWeather: iceUnit.mock.$httpPromise(getCurrentWeatherCallBacker),
currentWeatherResource: iceUnit.builder.$resourceMock(currentWeatherResourceCallBacker).build(),
getGithubReposOfUser: iceUnit.builder.$resourceActionMock('query', getGithubReposOfUserCallBacker).acceptsPayload(false).returnsArray(true).build()
};
var iceDummy;
var $log;
beforeEach(function() {
// inject another service which we want to spy on before instantiating our service to test (iceDummy)
$log = iceUnit.builder
.service('ice.dummy', '$log')
.withMock('iceDummyResource', iceDummyResourceMock)
.build();
spyOn($log, 'info');
spyOn($log, 'error');
spyOn(iceDummyResourceMock, 'getCurrentWeather').and.callThrough();
spyOn(iceDummyResourceMock.currentWeatherResource, 'save').and.callThrough();
spyOn(iceDummyResourceMock.currentWeatherResource, 'get').and.callThrough();
spyOn(iceDummyResourceMock, 'getGithubReposOfUser').and.callThrough();
iceDummy = iceUnit.inject('iceDummy');
});
it('logs message when service is created', function() {
expect($log.info).toHaveBeenCalledWith('iceDummy created');
});
it('logs current temperature as info on success', function() {
iceDummy.logCurrentWeather();
expect(iceDummyResourceMock.getCurrentWeather).toHaveBeenCalledWith('Leuven', 'be');
getCurrentWeatherCallBacker.success(validCurrentWeather);
expect($log.info).toHaveBeenCalledWith('current weather: 123');
});
it('logs error message on failure', function() {
iceDummy.logCurrentWeather();
getCurrentWeatherCallBacker.error('backend down', 404);
expect($log.error).toHaveBeenCalledWith('getCurrentWeather failed - status: 404 - data: backend down');
});
describe('var currentWeatherByReferenceObject:', function() {
it('is an object that only has $promise and $resolved (false) before resource call returns success', function() {
expect(iceDummy.currentWeatherByReferenceObject.$promise).toBeDefined();
expect(iceDummy.currentWeatherByReferenceObject.$resolved).toBe(false);
expect(iceDummy.currentWeatherByReferenceObject.someField).toBeUndefined();
expect(angular.isObject(iceDummy.currentWeatherByReferenceObject)).toBe(true);
expect(angular.isArray(iceDummy.currentWeatherByReferenceObject)).toBe(false);
var argsGetCall = iceDummyResourceMock.currentWeatherResource.get.calls.mostRecent().args;
expect(argsGetCall[0].cityName).toBe('Leuven');
expect(argsGetCall[0].countryCode).toBe('be');
});
it('does not set payload on the callbacker as it is a get (non-payload) method', function () {
expect(currentWeatherResourceCallBacker.get.payload).toBeUndefined();
});
it('is populated with the return data on success', function() {
var successValue = {
someField: 'some data'
};
currentWeatherResourceCallBacker.get.success(successValue);
expect(iceDummy.currentWeatherByReferenceObject.someField).toBe('some data');
expect(iceDummy.currentWeatherByReferenceObject.promiseReturnedOk).toBe(true);
expect(iceDummy.currentWeatherByReferenceObject.$resolved).toBe(true);
expect(iceDummy.currentWeatherByReferenceObject.errorData).toBeUndefined();
expect(iceDummy.currentWeatherByReferenceObject.errorStatus).toBeUndefined();
});
it('takes the httpResponse data & status on error', function() {
var errorHttpResponse = {
data: 'some error reason',
status: 400
};
currentWeatherResourceCallBacker.get.error(errorHttpResponse);
expect(iceDummy.currentWeatherByReferenceObject.errorData).toBe('some error reason');
expect(iceDummy.currentWeatherByReferenceObject.errorStatus).toBe(400);
expect(iceDummy.currentWeatherByReferenceObject.someField).toBeUndefined();
expect(iceDummy.currentWeatherByReferenceObject.$resolved).toBe(true);
});
});
describe('var currentWeatherSave:', function() {
it('also payload passed in save call (vs. get) + puts payload on callbacker', function() {
expect(iceDummy.currentWeatherSave.$promise).toBeDefined();
expect(iceDummy.currentWeatherSave.$resolved).toBe(false);
expect(iceDummy.currentWeatherSave.someField).toBeUndefined();
expect(angular.isObject(iceDummy.currentWeatherSave)).toBe(true);
expect(angular.isArray(iceDummy.currentWeatherSave)).toBe(false);
var argsSaveCall = iceDummyResourceMock.currentWeatherResource.save.calls.mostRecent().args;
expect(argsSaveCall[0].cityName).toBe('Leuven');
expect(argsSaveCall[0].countryCode).toBe('be');
expect(argsSaveCall[1].saveField).toBe('save value');
expect(currentWeatherResourceCallBacker.save.payload.saveField).toBe('save value');
});
it('is populated with the return data on success', function() {
var successValue = {
someField: 'some data'
};
currentWeatherResourceCallBacker.save.success(successValue);
expect(iceDummy.currentWeatherSave.someField).toBe('some data');
expect(iceDummy.currentWeatherSave.promiseReturnedOk).toBe(true);
expect(iceDummy.currentWeatherSave.$resolved).toBe(true);
expect(iceDummy.currentWeatherSave.errorData).toBeUndefined();
expect(iceDummy.currentWeatherSave.errorStatus).toBeUndefined();
});
it('takes the httpResponse data & status on error', function() {
var errorHttpResponse = {
data: 'some error reason',
status: 400
};
currentWeatherResourceCallBacker.save.error(errorHttpResponse);
expect(iceDummy.currentWeatherSave.errorData).toBe('some error reason');
expect(iceDummy.currentWeatherSave.errorStatus).toBe(400);
expect(iceDummy.currentWeatherSave.someField).toBeUndefined();
expect(iceDummy.currentWeatherSave.$resolved).toBe(true);
});
});
describe('var currentWeatherNew:', function() {
it('is an instance object', function() {
expect(iceDummy.getCurrentWeatherNew().$save).toBeDefined();
expect(iceDummy.getCurrentWeatherNew().$remove).toBeDefined();
expect(iceDummy.getCurrentWeatherNew().$delete).toBeDefined();
expect(iceDummy.getCurrentWeatherNew().someField).toBeUndefined();
});
it('puts the payload on the callbacker', function () {
iceDummy.getCurrentWeatherNew().someField = 'some value';
iceDummy.getCurrentWeatherNew().otherField = 'other value';
expect(currentWeatherResourceCallBacker.$save.payload).toBeUndefined();
iceDummy.doCurrentWeatherNewSave();
expect(currentWeatherResourceCallBacker.$save.payload.someField).toBe('some value');
expect(currentWeatherResourceCallBacker.$save.payload.otherField).toBe('other value');
});
it('is populated with the return data on $save success', function() {
iceDummy.doCurrentWeatherNewSave();
expect(iceDummy.getCurrentWeatherNew().someField).toBeUndefined();
var successValue = {
someField: 'some data'
};
currentWeatherResourceCallBacker.$save.success(successValue);
expect(iceDummy.getCurrentWeatherNew().someField).toBe('some data');
expect(iceDummy.getCurrentWeatherNew().promiseReturnedOk).toBe(true);
expect(iceDummy.getCurrentWeatherNew().errorData).toBeUndefined();
expect(iceDummy.getCurrentWeatherNew().errorStatus).toBeUndefined();
});
it('takes the httpResponse data & status on error', function() {
iceDummy.doCurrentWeatherNewSave();
var errorHttpResponse = {
data: 'some error reason',
status: 400
};
currentWeatherResourceCallBacker.$save.error(errorHttpResponse);
expect(iceDummy.getCurrentWeatherNew().errorData).toBe('some error reason');
expect(iceDummy.getCurrentWeatherNew().errorStatus).toBe(400);
expect(iceDummy.getCurrentWeatherNew().someField).toBeUndefined();
});
});
describe('var currentWeatherByCallBack:', function() {
it('is an empty object before resource call returns success', function() {
expect(iceDummy.getCurrentWeatherByCallBack()).toBeDefined();
expect(iceDummy.getCurrentWeatherByCallBack().someField).toBeUndefined();
});
it('is populated with the return data on success', function() {
iceDummy.doCurrentWeatherByCallBack();
expect(iceDummy.getCurrentWeatherByCallBack().someField).toBeUndefined();
var successValue = {
someField: 'some data'
};
currentWeatherResourceCallBacker.get.success(successValue);
expect(iceDummy.getCurrentWeatherByCallBack().someField).toBe('some data');
expect(iceDummy.getCurrentWeatherByCallBack().promiseReturnedOk).toBe(true);
expect(iceDummy.getCurrentWeatherByCallBack().errorData).toBeUndefined();
expect(iceDummy.getCurrentWeatherByCallBack().errorStatus).toBeUndefined();
});
it('takes the httpResponse data & status on error', function() {
iceDummy.doCurrentWeatherByCallBack();
var errorHttpResponse = {
data: 'some error reason',
status: 400
};
currentWeatherResourceCallBacker.get.error(errorHttpResponse);
expect(iceDummy.getCurrentWeatherByCallBack().errorData).toBe('some error reason');
expect(iceDummy.getCurrentWeatherByCallBack().errorStatus).toBe(400);
expect(iceDummy.getCurrentWeatherByCallBack().someField).toBeUndefined();
});
});
describe('var currentWeatherByPromise:', function() {
it('is an empty object before resource call returns success', function() {
expect(iceDummy.getCurrentWeatherByPromise()).toBeDefined();
expect(iceDummy.getCurrentWeatherByPromise().someField).toBeUndefined();
});
it('is populated with the return data on success', function() {
iceDummy.doCurrentWeatherByPromise();
expect(iceDummy.getCurrentWeatherByPromise().someField).toBeUndefined();
var successValue = {
someField: 'some data'
};
currentWeatherResourceCallBacker.get.success(successValue);
expect(iceDummy.getCurrentWeatherByPromise().someField).toBe('some data');
expect(iceDummy.getCurrentWeatherByPromise().promiseReturnedOk).toBe(true);
expect(iceDummy.getCurrentWeatherByPromise().errorData).toBeUndefined();
expect(iceDummy.getCurrentWeatherByPromise().errorStatus).toBeUndefined();
});
it('takes the httpResponse data & status on error', function() {
iceDummy.doCurrentWeatherByPromise();
var errorHttpResponse = {
data: 'some error reason',
status: 400
};
currentWeatherResourceCallBacker.get.error(errorHttpResponse);
expect(iceDummy.getCurrentWeatherByPromise().errorData).toBe('some error reason');
expect(iceDummy.getCurrentWeatherByPromise().errorStatus).toBe(400);
expect(iceDummy.getCurrentWeatherByPromise().someField).toBeUndefined();
});
});
describe('var githubReposOfUser:', function() {
it('is an array that only has $promise and $resolved (false) before resource call returns success', function() {
expect(iceDummy.githubReposOfUser.$promise).toBeDefined();
expect(iceDummy.githubReposOfUser.$resolved).toBe(false);
expect(iceDummy.githubReposOfUser.someField).toBeUndefined();
expect(angular.isArray(iceDummy.githubReposOfUser)).toBe(true);
expect(iceDummy.githubReposOfUser.length).toBe(0);
var argsGetCall = iceDummyResourceMock.getGithubReposOfUser.calls.mostRecent().args;
expect(argsGetCall[0]).toBe('bverbist');
});
it('is populated with the return data on success + each elem is instance object', function() {
var successValue = [
{ someField: 'some data' },
{ someField: 'other data' }
];
getGithubReposOfUserCallBacker.query.success(successValue);
expect(iceDummy.githubReposOfUser.length).toBe(2);
expect(iceDummy.githubReposOfUser.promiseReturnedOk).toBe(true);
expect(iceDummy.githubReposOfUser.$resolved).toBe(true);
expect(iceDummy.githubReposOfUser[0].$save).toBeDefined();
expect(iceDummy.githubReposOfUser[0].$remove).toBeDefined();
expect(iceDummy.githubReposOfUser[0].$delete).toBeDefined();
expect(iceDummy.githubReposOfUser[1].$save).toBeDefined();
expect(iceDummy.githubReposOfUser[1].$remove).toBeDefined();
expect(iceDummy.githubReposOfUser[1].$delete).toBeDefined();
expect(iceDummy.githubReposOfUser.errorData).toBeUndefined();
expect(iceDummy.githubReposOfUser.errorStatus).toBeUndefined();
});
it('takes the httpResponse data & status on error', function() {
var errorHttpResponse = {
data: 'some error reason',
status: 400
};
getGithubReposOfUserCallBacker.query.error(errorHttpResponse);
expect(iceDummy.githubReposOfUser.errorData).toBe('some error reason');
expect(iceDummy.githubReposOfUser.errorStatus).toBe(400);
expect(iceDummy.githubReposOfUser.length).toBe(0);
expect(iceDummy.githubReposOfUser.$resolved).toBe(true);
});
});
});
describe('test by using jasmine mock:', function() {
var promiseCallBacker = {};
var iceDummyResource, $log;
var iceDummy;
beforeEach(function() {
iceDummy = iceUnit.builder
.service('ice.dummy', 'iceDummy')
.build();
iceDummyResource = iceUnit.inject('iceDummyResource');
spyOn(iceDummyResource, 'getCurrentWeather').and.callFake(iceUnit.mock.$httpPromise(promiseCallBacker));
$log = iceUnit.inject('$log');
spyOn($log, 'info');
spyOn($log, 'error');
});
it('logs current temperature as info on success', function() {
iceDummy.logCurrentWeather();
expect(iceDummyResource.getCurrentWeather).toHaveBeenCalledWith('Leuven', 'be');
promiseCallBacker.success(validCurrentWeather);
expect($log.info).toHaveBeenCalledWith('current weather: 123');
});
it('logs error message on failure', function() {
iceDummy.logCurrentWeather();
promiseCallBacker.error('backend down', 404);
expect($log.error).toHaveBeenCalledWith('getCurrentWeather failed - status: 404 - data: backend down');
});
it('also works if no success callback registered on http promise', function() {
iceDummy.logCurrentWeatherWithoutSuccessCallback();
expect(iceDummyResource.getCurrentWeather).toHaveBeenCalledWith('Leuven', 'be');
promiseCallBacker.success();
expect($log.info).not.toHaveBeenCalled();
});
});
var validCurrentWeather = {
main: {
temp: 123
}
};
});
|
Meteor.startup(function () {
if (!process.env.MAIL_URL) {
SetEmails.noreply();
}
Accounts.emailTemplates.from = 'Spacer mailbot <noreply@spacer.im>';
Accounts.emailTemplates.siteName = 'spacer.im';
Accounts.emailTemplates.verifyEmail.subject = function (user) {
return 'Welcome to Spacer! Please verify your email';
};
Accounts.emailTemplates.verifyEmail.text = function (user, url) {
return 'Hello, Spacer!\r\n\r\n' +
'Thank you for registering at our Web Space Station.' +
' Please click on the following link to verify your email address:\r\n' +
url +
"\r\n" +
"Here at Spacer[https://www.spacer.im/] you'll always stay updated with the latest news about space exploration, " +
"you'll see the most interesting career opportunities and get a chance to develop a solid space resume " +
"by showing your practical skills. Oh, and by the way, you might find likely minded Spacers to connect " +
"with and possibly to cooperate on real space projects.\r\n\r\n" +
"3... 2... 1... Liftoff!\r\n\r\n" +
"Spacer team";
};
Accounts.emailTemplates.resetPassword.text = function (user, url) {
return 'Hey there,\r\n\r\n' +
'Someone requested a new password for your Spacer account. If it was you, simply click the link below:\r\n' +
url + "\r\n" +
"If you didn't make this request then you can safely ignore this email.\r\n\r\n" +
'Spacer team';
};
Accounts.config({
sendVerificationEmail: true
});
}); |
module.exports = function() {
return {
map: this.env('development', true, false)
}
}
|
/**
* Tickets Model
*/
itsallagile.Model.Ticket = Backbone.Model.extend({
defaults: {
content: ''
},
/**
* Get the age of a ticket in days
*/
getAge: function() {
var now = new Date();
var last = new Date(this.get("modified"));
var age = Math.floor((now.getTime() - last.getTime()) / (1000 * 60 * 60 * 24));
return age >= 0 ? age : 0;
}
});
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides enumeration sap.ui.model.UpdateMethod
sap.ui.define(function() {
"use strict";
/**
* @class
* Different methods for update operations
*
* @static
* @public
* @alias sap.ui.model.odata.UpdateMethod
*/
var UpdateMethod = {
/**
* MERGE method will send update requests in a MERGE request
* @public
*/
Merge: "MERGE",
/**
* PUT method will send update requests in a PUT request
* @public
*/
Put: "PUT"
};
return UpdateMethod;
}, /* bExport= */ true);
|
'use strict';
// Global content
console.log('hello global');
(function() {
// Anonymous content
console.log('hello closure');
})();
|
let assert = require('assert');
describe("Numbers",function(){
it('should add two numbers',function(){
assert.equal(5, 3 + 2);
})
}) |
var searchData=
[
['main_2ecpp',['main.cpp',['../main_8cpp.html',1,'']]],
['main_5fip_5ftest_2ecpp',['main_ip_test.cpp',['../main__ip__test_8cpp.html',1,'']]],
['main_5fip_5ftest_5fread_2ecpp',['main_ip_test_read.cpp',['../main__ip__test__read_8cpp.html',1,'']]],
['message_2ecpp',['Message.cpp',['../Message_8cpp.html',1,'']]],
['message_2eh',['Message.h',['../Message_8h.html',1,'']]],
['messagequeue_2ecpp',['MessageQueue.cpp',['../MessageQueue_8cpp.html',1,'']]],
['messagequeue_2eh',['MessageQueue.h',['../MessageQueue_8h.html',1,'']]]
];
|
module.exports = {"YanoneKaffeesatz":{"bold":"YanoneKaffeesatz-Bold.ttf","extralight":"YanoneKaffeesatz-ExtraLight.ttf","light":"YanoneKaffeesatz-Light.ttf","normal":"YanoneKaffeesatz-Regular.ttf","italics":"YanoneKaffeesatz-Regular.ttf","bolditalics":"YanoneKaffeesatz-Bold.ttf"}}; |
var LettuceUtils = {
makeExternalLinkNewTab: function(){
//jquery needed
var self = this;
$("a").each(function(index , ele) {
if(self.isExternalLink($(ele).attr("href"))){
$(ele).attr("target" , "_blank");
}
});
},
isExternalLink: function(link) {
return link.indexOf("http") == 0;
}
}
|
module.exports = {
plugins: [
require('postcss-import')
]
}
|
/************************************************************************
*
* HIGHLY CUSTOMIZABLE AUTO-MAPPING EXTENSION FOR ALOOMA ETL PLATFORM
*
* @Author: oakromulo (Romulo-FanHero)
* @Date: 2017-10-27T19:47:19-02:00
* @Email: romulo@fanhero.com
* @Last modified by: oakromulo
* @Last modified time: 2017-10-31T16:07:21-02:00
* @License: MIT
*
************************************************************************/
// dependencies
const _ = require('lodash');
const promise = require('bluebird');
const decamelize = require('decamelize');
const request = require('request-promise').defaults({ jar: true, json: true }); // <-- VERY HANDY!
// alooma access credentials
const EMAIL = process.env.ALOOMA_EMAIL;
const PASSWORD = process.env.ALOOMA_PASSWORD;
const BASE_URL = 'https://app.alooma.com:443/rest';
// default mapping mode for new mappings
const DEFAULT_MAPPING_MODE = 'STRICT';
// default settings to be applied to all fields identified by auto-map as VARCHAR
const DEFAULT_VARCHAR_LENGTH = 512;
const DEFAULT_VARCHAR_TRUNCATION = true;
// choose between TIMESTAMP and TIMESTAMPTZ as default type for timestamp columns
const DEFAULT_TIMESTAMP_TYPE = 'TIMESTAMPTZ';
// define settings for the primary key (informative-only on Redshift)
const DEFAULT_PRIMARY_KEY = 'message_id';
const DEFAULT_PRIMARY_KEY_TYPE = 'CHAR';
const DEFAULT_PRIMARY_KEY_LENGTH = 36;
const DEFAULT_PRIMARY_KEY_TRUNCATION = false;
// define a column for an evenly distribution of fact table data across nodes
const DEFAULT_DISTRIBUTION_KEY = 'timestamp';
// default datatype settings for fields identified as `id` columns
const DEFAULT_ID_TYPE = 'VARCHAR';
const DEFAULT_ID_LENGTH = 256;
const DEFAULT_ID_TRUNCATION = false;
const ID_PATTERNS = ['id'];
// specify custom length for sortkeys with datatype varchar
const DEFAULT_SORT_KEY_VARCHAR_LENGTH = 256;
// determine patterns that indicate that a column is a good candidate for a compound/interleaved sortkey
const SORT_KEY_PATTERNS = ['timestamp', 'id', 'user', 'email', 'gender', 'os_name', 'birthday', 'created_at'];
// high-dispersion numeric fields that fit within the pattern below are cast into varchar
const FORCE_VARCHAR_PATTERNS = ['_id', 'version', 'timezone', 'build', 'floor_level', 'google_analytics'];
// large numeric fields in this pattern are cast into BIGINT
const FORCE_BIGINT_PATTERNS = ['geolocation_timestamp', 'properties_transaction'];
// patterns to identify fields that should be set as FLOATING POINT by default (e.g. IMU/GPS data)
const FORCE_FLOAT_PATTERNS = ['geolocation'];
// patterns on table names to be bypassed and not processed at all by this script
const EVENT_EXCLUSION_PATTERN = ['develop', 'other'];
// naïve helper method to check if `str` include any of the specified `patterns`
const inPattern = (str, patterns) => {
var found = false;
patterns.forEach(p => {
found = !found && str.toLowerCase().includes(p.toLowerCase()) ? true : found;
});
return found;
};
// helper function to fix column names by decamelizing and replacing spaces with underscores
const fixNaming = n => decamelize(n).replace(/ /g, '_');
// login (auth cookie is picked up here automatically and propagates to all subsequent calls)
request.post(`${BASE_URL}/login`, { json: { email: EMAIL, password: PASSWORD } })
// get all event-types
.then(() => request.get(`${BASE_URL}/event-types`))
// process all unmapped event-types
.then(evts => promise.map(
// filter unmapped types
evts.filter(e => e.state === 'UNMAPPED' && !inPattern(e.name, EVENT_EXCLUSION_PATTERN) && (e.name.includes('dataflux') || false)),
// load full data on each type
evt => request.get(`${BASE_URL}/event-types/${evt.name}`)
// run alooma's vanilla auto-mapper
.then(evt => request.post(`${BASE_URL}/event-types/${evt.name}/auto-map`, { json: evt }))
// process fields and commit new mapping on each automapped event type
.then(evt => {
console.log(evt.name, 'started');
// flat list to store the mapping for each field on the evt obj
var mappings = [];
// initial sort key index
var sortKeyIndex = 0;
// recursive function to iterate all fields and sub-fieldsm, applying a custom auto-map
var autoMap = e => e.fields.forEach(f => {
// fill parent fields
if (!e.father) e.father = '';
if (!e.fieldName) e.fieldName = '';
f.father = e.father + fixNaming(e.fieldName);
if (f.father) f.father += '_';
// continue iterating if not a root event
if (f.fields.length > 0) return autoMap(f);
// process non-meta fields
if (!(f.mapping.columnName.includes('_metadata') || f.father.includes('_metadata') || f.fieldName.includes('_metadata') || (f.father + fixNaming(f.fieldName)).includes('_metadata'))) {
// specifiy column name
f.mapping.columnName = f.father + fixNaming(f.fieldName);
delete f.father;
// verify discard conditions and set flag accordingly
f.mapping.isDiscarded = false;
// check if column type matches a data type change pattern
if (inPattern(f.mapping.columnName, FORCE_FLOAT_PATTERNS)) {
f.mapping.columnType.type = 'FLOAT_NORM';
}
if (inPattern(f.mapping.columnName, FORCE_BIGINT_PATTERNS)) {
f.mapping.columnType.type = 'BIGINT';
}
if (inPattern(f.mapping.columnName, FORCE_VARCHAR_PATTERNS)) {
f.mapping.columnType.type = 'VARCHAR';
}
// enforce default varchar behavior
if (f.mapping.columnType.type === 'VARCHAR') {
f.mapping.columnType.length = DEFAULT_VARCHAR_LENGTH;
f.mapping.columnType.truncate = DEFAULT_VARCHAR_TRUNCATION;
}
// enforce default timestamp behavior
if (f.mapping.columnType.type.toLowerCase().includes('timestamp')) {
f.mapping.columnType.type = DEFAULT_TIMESTAMP_TYPE;
}
// enforce default settings for ID fields
if (inPattern(f.mapping.columnName, ID_PATTERNS)) {
f.mapping.columnType.type = DEFAULT_ID_TYPE;
f.mapping.columnType.length = DEFAULT_ID_LENGTH;
f.mapping.columnType.truncate = DEFAULT_ID_TRUNCATION;
}
// set sort key if column within pattern
if (inPattern(f.mapping.columnName, SORT_KEY_PATTERNS)) {
f.mapping.sortKeyIndex = sortKeyIndex++;
if (f.mapping.columnType.type === 'VARCHAR') {
f.mapping.columnType.length = DEFAULT_SORT_KEY_VARCHAR_LENGTH;
}
}
else f.mapping.sortKeyIndex = -1;
// set distribution key if dist column
if (f.mapping.columnName === DEFAULT_DISTRIBUTION_KEY) {
f.mapping.distKey = true;
}
else f.mapping.distKey = false;
// set primary key if pk column
if (f.mapping.columnName === DEFAULT_PRIMARY_KEY) {
f.mapping.columnType.type = DEFAULT_PRIMARY_KEY_TYPE;
f.mapping.columnType.length = DEFAULT_PRIMARY_KEY_LENGTH;
f.mapping.columnType.truncate = DEFAULT_PRIMARY_KEY_TRUNCATION;
f.mapping.columnType.nonNull = true;
f.mapping.primaryKey = true;
}
else f.mapping.primaryKey = false;
// enforce no length/truncate fields on non-CHAR types
if (!f.mapping.columnType.type.toLowerCase().includes('char')) {
delete f.mapping.columnType.length;
delete f.mapping.columnType.truncate;
}
}
// metafields should NEVER be discarded
else {
delete f.father;
if (!f.mapping) f.mapping = {};
f.mapping.isDiscarded = false;
if (!f.mapping.columnName) {
f.mapping.columnName = `_metadata_${fixNaming(f.fieldName)}`;
}
if (!f.mapping.columnType) {
f.mapping.columnType = { nonNull: false };
}
if (
(f.mapping.columnName && f.mapping.columnName.includes('_object')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('_object')) ||
(f.mapping.columnName && f.mapping.columnName.includes('_url')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('_url')) ||
(f.mapping.columnName && f.mapping.columnName.includes('_id')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('_id')) ||
(f.mapping.columnName && f.mapping.columnName.includes('uuid')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('uuid')) ||
(f.mapping.columnName && f.mapping.columnName.includes('input')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('input')) ||
(f.mapping.columnName && f.mapping.columnName.includes('type')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('type')) ||
(f.mapping.columnName && f.mapping.columnName.includes('database')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('database')) ||
(f.mapping.columnName && f.mapping.columnName.includes('table')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('table')) ||
(f.mapping.columnName && f.mapping.columnName.includes('schema')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('schema')) ||
(f.mapping.columnName && f.mapping.columnName.includes('client')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('client')) ||
(f.mapping.columnName && f.mapping.columnName.includes('token')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('token')) ||
(f.mapping.columnName && f.mapping.columnName.includes('version')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('version'))
) {
f.mapping.columnType.type = 'VARCHAR';
f.mapping.columnType.length = 1024;
f.mapping.columnType.truncate = false;
}
if (
(f.mapping.columnName && f.mapping.columnName.includes('timestamp')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('timestamp')) ||
(f.mapping.columnName && f.mapping.columnName.includes('updated')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('updated')) ||
(f.mapping.columnName && f.mapping.columnName.includes('pull_time')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('pull_time'))
) {
f.mapping.columnType.type = 'TIMESTAMP';
}
if (
(f.mapping.columnName && f.mapping.columnName.includes('deleted')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('deleted'))
) {
f.mapping.columnType.type = 'BOOLEAN';
}
if (
(f.mapping.columnName && f.mapping.columnName.includes('restream_count')) ||
(f.mapping.fieldName && f.mapping.fieldName.includes('restream_count'))
) {
f.mapping.columnType.type = 'BIGINT';
}
}
mappings.push(_.omit(_.cloneDeep(f.mapping), ['isDiscarded', 'machineGenerated', 'subFields']));
});
autoMap(evt);
// exect recursive cleanup routine to discard extra fields not required for mapping
var cleanUp = e => e.fields.forEach(f => {
try { delete f.father; } catch (ex) {}
try { delete f.fields.father; } catch (ex) {}
try { delete f.stats; } catch (ex) {}
try { delete f.fields.stats; } catch (ex) {}
try { delete f.mapping.sortKeyIndex; } catch (ex) {}
try { delete f.mapping.distKey; } catch (ex) {}
try { delete f.mapping.primaryKey; } catch (ex) {}
try { delete e.father; } catch (ex) {}
try { delete e.fields.father; } catch (ex) {}
try { delete e.stats; } catch (ex) {}
try { delete e.fields.stats; } catch (ex) {}
try { delete e.mapping.sortKeyIndex; } catch (ex) {}
try { delete e.mapping.distKey; } catch (ex) {}
try { delete e.mapping.primaryKey; } catch (ex) {}
if (f.fields.length > 0) return cleanUp(f);
});
cleanUp(evt);
const schema = evt.name.split('.')[0];
const tableName = evt.name.split('.')[1];
// apply custom mapping
return request.post(`${BASE_URL}/tables/${schema}/${tableName}`, { json: mappings })
.then(() => request.post(`${BASE_URL}/event-types/${evt.name}/mapping`, { json: {
name: evt.name,
mapping: {
tableName: tableName,
schema: schema
},
fields: evt.fields,
mappingMode: DEFAULT_MAPPING_MODE
}}))
.then(() => console.log(evt.name, 'finished'))
.catch(console.error);
})
.catch(console.error)
))
.catch(console.error);
|
/*
* This file is part of the ice cream example.
*
* (c) Magnus Bergman <hello@magnus.sexy>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import THREE from 'three';
/**
* This is the HemisphereLight class.
*/
export default class HemisphereLight extends THREE.HemisphereLight {
/**
* Create HemisphereLight.
*
* @param {object} scene
* @param {object} options
*
* @return {void}
*/
constructor(scene, options) {
const opts = {
color: 0xffffff,
intensity: 1,
...options,
};
super(opts.color, opts.intensity);
if (scene) scene.add(this);
}
/**
* Update.
*
* @return {void}
*/
update() {
}
}
|
'use strict';
var $ = require('jquery'),
chai = require('chai'),
sinon = require('sinon'),
sinonChai = require('sinon-chai'),
chaiDom = require('chai-dom');
require('babel-polyfill');
// Expose jQuery globals
window.$ = window.jQuery = $;
// Load chai extensions
chai.use(sinonChai);
chai.use(chaiDom);
// Expose tools in the global scope
window.chai = chai;
window.describe = describe;
window.expect = chai.expect;
window.it = it;
window.sinon = sinon;
|
const logger = require('winston');
var userDao = require("../../../data/user_dao.js");
var config = require("../../../config.js");
var passwordService = require("../../../service/password_service.js");
logger.level = config.logging.level;
var createResponseAsJson = function(isSuccess, message) {
return {
success: isSuccess,
message: message
};
};
module.exports = function(req, res) {
var user = req.body;
userDao.loginExists(user.login, function(exists) {
if (exists) {
logger.log('warn', 'Can not create user. Login %s already exists', user.login);
res.status(403).json(createResponseAsJson(false, 'LOGIN_EXISTS'));
return;
}
user.password = passwordService.encrypt(user.password, config.password.saltRounds);
if (!user.orgs) {
user.orgs = [];
}
userDao.save(user, function(err, result) {
if (err) {
logger.log('err', err);
res.json(createResponseAsJson(false, 'Can not create user. \n'+err));
} else {
res.json(createResponseAsJson(true, 'CREATED'));
}
});
});
}; |
import { storeReAuthoriseState } from '../utils';
export const GET_AUTHORISED_APPS = 'GET_AUTHORISED_APPS';
export const REVOKE_APP = 'REVOKE_APP';
export const SET_APP_LIST = 'SET_APP_LIST';
export const CLEAR_APP_ERROR = 'CLEAR_APP_LIST';
export const SEARCH_APP = 'SEARCH_APP';
export const CLEAR_SEARCH = 'CLEAR_SEARCH';
export const SET_RE_AUTHORISE_STATE = 'SET_RE_AUTHORISE_STATE';
export const GET_ACCOUNT_INFO = 'GET_ACCOUNT_INFO';
export const getAuthorisedApps = () => ({
type: GET_AUTHORISED_APPS,
payload: window.safeAuthenticator.getAuthorisedApps()
});
export const revokeApp = (appId) => ({
type: REVOKE_APP,
payload: window.safeAuthenticator.revokeApp(appId)
});
export const setAppList = (appList) => ({
type: SET_APP_LIST,
apps: appList
});
export const clearAppError = () => ({
type: CLEAR_APP_ERROR
});
export const searchApp = (value) => ({
type: SEARCH_APP,
value
});
export const clearSearch = () => ({
type: CLEAR_SEARCH
});
export const setReAuthoriseState = (state) => {
storeReAuthoriseState(state);
window.safeAuthenticator.setReAuthoriseState(state);
return {
type: SET_RE_AUTHORISE_STATE,
state
};
};
export const getAccountInfo = () => ({
type: GET_ACCOUNT_INFO,
payload: window.safeAuthenticator.getAccountInfo()
});
|
'use strict';
var socialsInstagramModalAccount = angular.module('socialsInstagramModalAccount', []);
socialsInstagramModalAccount.controller('InstagramModalAccountController',
['$scope', '$element', 'username', 'InstagramApi', 'InstagramCredentials', 'close',
function ($scope, $element, username, InstagramApi, InstagramCredentials, close) {
InstagramApi.getAccountInfoPromise(username).then(function (accountInfo) {
$scope.instagramAccountInfo = accountInfo.data;
});
$scope.disconnectFromInstagram = function () {
InstagramCredentials.remove({username: username},
function success() {
$element.modal('hide');
close(true, 500);
},
function error() {
$element.modal('hide');
close(false, 500);
});
};
}]); |
require.ensure([], function(require) {
require("./79.async.js");
require("./159.async.js");
require("./318.async.js");
require("./636.async.js");
});
module.exports = 637; |
define({"oj-message":{fatal:"Vakava",error:"Virhe",warning:"Varoitus",info:"Tiedot",confirmation:"Vahvistus","compact-type-summary":"{0}: {1}"},"oj-converter":{summary:"Arvo ei ole odotetussa muodossa.",detail:"Syötä arvo odotetussa muodossa.","plural-separator":", ",hint:{summary:"Esimerkki: {exampleValue}",detail:"Syötä arvo tämän esimerkin mukaisessa muodossa: '{exampleValue}'","detail-plural":"Syötä arvo näiden esimerkkien mukaisessa muodossa: '{exampleValue}'"},optionHint:{detail:"Hyväksytty arvo valinnalle {propertyName} on {propertyValueValid}.",
"detail-plural":"Hyväksytyt arvot valinnalle {propertyName} ovat {propertyValueValid}."},optionTypesMismatch:{summary:"Arvo valinnalle {requiredPropertyName} on pakollinen, kun valinnaksi {propertyName} on määritetty {propertyValue}."},optionTypeInvalid:{summary:"Odotetun tyyppistä arvoa ei annettu valinnalle {propertyName}."},optionOutOfRange:{summary:"Arvo {propertyValue} ei ole valinnan {propertyName} alueella."},optionValueInvalid:{summary:"Virheellinen arvo {propertyValue} määritettiin valinnalle {propertyName}."},
number:{decimalFormatMismatch:{summary:"{value} ei ole odotetussa numeromuodossa."},decimalFormatUnsupportedParse:{summary:"decimalFormat: short ja long eivät ole tuettuja muunto-ohjelman jäsennyksessä.",detail:"Vaihda komponentiksi readOnly. readOnly-kentät eivät kutsu muunto-ohjelman jäsennystoimintoa."},currencyFormatMismatch:{summary:"{value} ei ole odotetussa valuuttamuodossa."},percentFormatMismatch:{summary:"{value} ei ole odotetussa prosenttimuodossa."}},datetime:{datetimeOutOfRange:{summary:"Arvo {value} ei ole kohteen {propertyName} alueella.",
detail:"Syötä arvo välillä {minValue} - {maxValue}."},dateFormatMismatch:{summary:"{value} ei ole odotetussa päivämäärämuodossa."},timeFormatMismatch:{summary:"{value} ei ole odotetussa aikamuodossa."},datetimeFormatMismatch:{summary:"{value} ei ole odotetussa päivämäärä- ja aikamuodossa."},dateToWeekdayMismatch:{summary:"Päivämäärä {date} ei ole {weekday}.",detail:"Syötä päivämäärää vastaava viikonpäivä."}}},"oj-validator":{length:{hint:{min:"Syötä vähintään {min} merkkiä.",max:"Syötä enintään {max} merkkiä",
inRange:"Syötä {min} - {max} merkkiä.",exact:"Syötä {length} merkkiä."},messageDetail:{tooShort:"Syötä vähintään {min} merkkiä, ei vähempää.",tooLong:"Syötä enintään {max} merkkiä, ei enempää."},messageSummary:{tooShort:"Merkkejä on liian vähän.",tooLong:"Merkkejä on liian monta."}},range:{number:{hint:{min:"Syötä luku, joka on suurempi tai yhtä suuri kuin {min}.",max:"Syötä luku, joka on pienempi tai yhtä suuri kuin {max}.",inRange:"Syötä luku välillä {min} - {max}."},messageDetail:{rangeUnderflow:"Luvun {value} on oltava suurempi tai yhtä suuri kuin {min}.",
rangeOverflow:"Luvun {value} on oltava pienempi tai yhtä suuri kuin {max}."},messageSummary:{rangeUnderflow:"Luku on liian pieni.",rangeOverflow:"Luku on liian iso."}},datetime:{hint:{min:"Syötä päivämäärä ja aika, joka on {min} tai sen jälkeen.",max:"Syötä päivämäärä ja aika, joka on {max} tai sitä ennen.",inRange:"Syötä päivämäärä välillä {min} - {max}."},messageDetail:{rangeUnderflow:"Päivämäärän ja ajan on oltava {min} tai sen jälkeen.",rangeOverflow:"Päivämäärän ja ajan on oltava {max} tai sitä ennen."},
messageSummary:{rangeUnderflow:"Päivämäärä ja aika on ennen vähimmäispäivämäärää.",rangeOverflow:"Päivämäärä ja aika on vähimmäispäivämäärän jälkeen."}}},restriction:{date:{messageSummary:"Päivämäärä {value} on käytöstä poistettu kirjaus.",messageDetail:"Päivämäärä {value} ei saa olla käytöstä poistettu kirjaus."}},regExp:{summary:"Muoto on virheellinen.",detail:"Arvon {value} on vastattava tätä mallia: {pattern}"},required:{summary:"Arvo vaaditaan.",detail:"Syötä arvo."}},"oj-editableValue":{required:{hint:"",
messageSummary:"",messageDetail:""}},"oj-ojInputDate":{prevText:"Edellinen",nextText:"Seuraava",currentText:"Tänään",weekHeader:"Viikko",tooltipCalendar:"Valitse päivämäärä",tooltipCalendarDisabled:"Valittu päivä poissa käytöstä",weekText:"Viikko",datePicker:"Päivämäärän valinta",inputHelp:"Avaa kalenteri painamalla ala- tai ylänuolta",inputHelpBoth:"Avaa kalenteri painamalla ala- tai ylänuolta ja avaa ajan avattava valikko painamalla vaihtonäppäintä sekä ala- tai ylänuolta",dateTimeRange:{hint:{min:"",
max:"",inRange:""},messageDetail:{rangeUnderflow:"",rangeOverflow:""},messageSummary:{rangeUnderflow:"",rangeOverflow:""}},dateRestriction:{hint:"",messageSummary:"",messageDetail:""}},"oj-ojInputTime":{tooltipTime:"Valitse aika",tooltipTimeDisabled:"Valittu aika poissa käytöstä",inputHelp:"Avaa ajan avattava valikko painamalla ala- tai ylänuolta",dateTimeRange:{hint:{min:"",max:"",inRange:""},messageDetail:{rangeUnderflow:"",rangeOverflow:""},messageSummary:{rangeUnderflow:"",rangeOverflow:""}}},
"oj-inputBase":{regexp:{messageSummary:"",messageDetail:""}},"oj-ojInputPassword":{regexp:{messageDetail:"Arvon on vastattava tätä mallia: {pattern}"}},"oj-ojFilmStrip":{labelAccArrowNextPage:"Seuraava sivu",labelAccArrowPreviousPage:"Edellinen sivu",tipArrowNextPage:"Seuraava",tipArrowPreviousPage:"Edellinen"},"oj-ojDataGrid":{accessibleSortAscending:"{id} lajiteltu nousevaan järjestykseen",accessibleSortDescending:"{id} lajiteltu laskevaan järjestykseen",accessibleActionableMode:"Siirry toiminnalliseen tilaan",
accessibleNavigationMode:"Siirry navigointitilaan",accessibleSummaryExact:"Tämä on tietoruudukko, jossa on {rownum} riviä ja {colnum} saraketta",accessibleSummaryEstimate:"Tämä on tietoruudukko, jonka rivien ja sarakkeiden määrää ei tiedetä",accessibleSummaryExpanded:"{num} riviä on laajennettu",accessibleRowExpanded:"Rivi laajennettu",accessibleRowCollapsed:"Rivi tiivistetty",accessibleRowSelected:"Rivi {row} valittu",accessibleColumnSelected:"Sarake {column} valittu",accessibleStateSelected:"valittu",
accessibleMultiCellSelected:"{num} solua valittu",accessibleRowContext:"Rivi {index}",accessibleColumnContext:"Sarake {index}",accessibleRowHeaderContext:"Riviotsikko {index}",accessibleColumnHeaderContext:"Sarakeotsikko {index}",accessibleLevelContext:"Taso {level}",accessibleRangeSelectModeOn:"Lisää valittu soluväli -tila käytössä",accessibleRangeSelectModeOff:"Lisää valittu soluväli -tila poissa käytöstä",accessibleFirstRow:"Olet ensimmäisellä rivillä",accessibleLastRow:"Olet viimeisellä rivillä",
accessibleFirstColumn:"Olet ensimmäisessä sarakkeessa",accessibleLastColumn:"Olet viimeisessä sarakkeessa",accessibleSelectionAffordanceTop:"Ylävalintakahva",accessibleSelectionAffordanceBottom:"Alavalintakahva",msgFetchingData:"Haetaan tietoja...",msgNoData:"Ei näytettäviä alkioita.",labelResize:"Muuta kokoa",labelResizeWidth:"Muuta leveyttä",labelResizeHeight:"Muuta korkeutta",labelSortRow:"Lajittele rivi",labelSortRowAsc:"Lajittele rivi nousevaan järjestykseen",labelSortRowDsc:"Lajittele rivi laskevaan järjestykseen",
labelSortCol:"Lajittele sarake",labelSortColAsc:"Lajittele sarake nousevaan järjestykseen",labelSortColDsc:"Lajittele sarake laskevaan järjestykseen",labelCut:"Leikkaa",labelPaste:"Liitä",labelEnableNonContiguous:"Ota käyttöön epäjatkuva valinta",labelDisableNonContiguous:"Poista käytöstä epäjatkuva valinta",labelResizeDialogSubmit:"OK"},"oj-ojRowExpander":{accessibleLevelDescription:"Taso {level}",accessibleRowDescription:"Taso {level}, rivi {num}/{total}",accessibleRowExpanded:"Rivi laajennettu",
accessibleRowCollapsed:"Rivi tiivistetty",accessibleStateExpanded:"laajennettu",accessibleStateCollapsed:"tiivistetty"},"oj-ojListView":{msgFetchingData:"Haetaan tietoja...",msgNoData:"Ei näytettäviä alkioita.",indexerCharacters:"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|Å|Ä|Ö"},"oj-_ojLabel":{tooltipHelp:"Ohje",tooltipRequired:"Pakollinen"},"oj-ojInputNumber":{numberRange:{hint:{min:"",max:"",inRange:""},messageDetail:{rangeUnderflow:"",rangeOverflow:""},messageSummary:{rangeUnderflow:"",
rangeOverflow:""}},tooltipDecrement:"Vähennys",tooltipIncrement:"Lisäys"},"oj-ojTable":{labelAccSelectionAffordanceTop:"Ylävalintakahva",labelAccSelectionAffordanceBottom:"Alavalintakahva",labelSelectRow:"Valitse rivi",labelSelectColumn:"Valitse sarake",labelSort:"Lajittele",labelSortAsc:"Nouseva järjestys",labelSortDsc:"Laskeva järjestys",msgFetchingData:"Haetaan tietoja...",msgNoData:"Näytettäviä tietoja ei ole."},"oj-ojTabs":{labelCut:"Leikkaa",labelPasteBefore:"Liitä eteen",labelPasteAfter:"Liitä jälkeen",
labelRemove:"Poista",labelReorder:"Järjestä uudelleen",removeCueText:"Poistettava"},"oj-ojSelect":{seachField:"Hakukenttä",noMatchesFound:"Vastineita ei löydy"},"oj-ojSwitch":{SwitchON:"Käytössä",SwitchOFF:"Ei käytössä"},"oj-ojCombobox":{noMatchesFound:"Vastineita ei löydy"},"oj-ojInputSearch":{noMatchesFound:"Vastineita ei löydy"},"oj-ojTree":{stateLoading:"Ladataan...",labelNewNode:"Uusi solmu",labelMultiSelection:"Useita valintoja",labelEdit:"Muokkaa",labelCreate:"Luo",labelCut:"Leikkaa",labelCopy:"Kopioi",
labelPaste:"Liitä",labelRemove:"Poista",labelRename:"Nimeä uudelleen",labelNoData:"Ei tietoja"},"oj-ojPagingControl":{labelAccPaging:"Sivutus",labelAccNavFirstPage:"Ensimmäinen sivu",labelAccNavLastPage:"Viimeinen sivu",labelAccNavNextPage:"Seuraava sivu",labelAccNavPreviousPage:"Edellinen sivu",labelAccNavPage:"Sivu",labelLoadMore:"Näytä lisää...",labelLoadMoreMaxRows:"Saavutettu {maxRows} riviä enimmäisrajasta",labelNavInputPage:"Sivu",labelNavInputPageMax:"/{pageMax}",msgItemRangeCurrent:"{pageFrom} - {pageTo}",
msgItemRangeCurrentSingle:"{pageFrom}",msgItemRangeOf:"/",msgItemRangeOfAtLeast:"vähintään",msgItemRangeOfApprox:"n.",msgItemRangeItems:"alkiota",tipNavInputPage:"Sivulle",tipNavPageLink:"Siirry sivulle {pageNum}",tipNavNextPage:"Seuraava",tipNavPreviousPage:"Edellinen",tipNavFirstPage:"Ensimmäinen",tipNavLastPage:"Viimeinen",pageInvalid:{summary:"Syötetty sivun arvo on virheellinen.",detail:"Syötä nollaa suurempi arvo."},maxPageLinksInvalid:{summary:"Kohteen maxPageLinks arvo on virheellinen.",detail:"Syötä neljää suurempi arvo."}},
"oj-ojMasonryLayout":{labelCut:"Leikkaa",labelPasteBefore:"Liitä eteen",labelPasteAfter:"Liitä jälkeen"},"oj-panel":{labelAccButtonExpand:"Laajenna",labelAccButtonCollapse:"Tiivistä",labelAccButtonRemove:"Poista"},"oj-ojChart":{labelDefaultGroupName:"Ryhmä {0}",labelSeries:"Sarja",labelGroup:"Ryhmä",labelDate:"Päivämäärä",labelValue:"Arvo",labelTargetValue:"Kohde",labelX:"X",labelY:"Y",labelZ:"Z",labelPercentage:"Prosenttiosuus",labelLow:"Pieni",labelHigh:"Suuri",labelOpen:"Avaa",labelClose:"Sulje",
labelVolume:"Määrä",labelMin:"Vähintään",labelMax:"Enintään",labelOther:"Muu",tooltipPan:"Panoroi",tooltipSelect:"Alueen valinta",tooltipZoom:"Zoomausvalinta",componentName:"Kaavio"},"oj-dvtBaseGauge":{componentName:"Mittari"},"oj-ojDiagram":{componentName:"Kaavio"},"oj-ojLegend":{componentName:"Selite"},"oj-ojNBox":{highlightedCount:"{0}/{1}",labelOther:"Muu",labelGroup:"Ryhmä",labelSize:"Koko",labelAdditionalData:"Lisätiedot",componentName:"9 ruudun kaavio"},"oj-ojPictoChart":{componentName:"Kuvakaavio"},
"oj-ojSparkChart":{componentName:"Kaavio"},"oj-ojSunburst":{labelColor:"Väri",labelSize:"Koko",componentName:"Aurinko"},"oj-ojTagCloud":{componentName:"Tunnistepilvi"},"oj-ojThematicMap":{componentName:"Teemakartta"},"oj-ojTimeline":{componentName:"Aikajana",labelSeries:"Sarja",tooltipZoomIn:"Lähennä",tooltipZoomOut:"Loitonna"},"oj-ojTreemap":{labelColor:"Väri",labelSize:"Koko",tooltipIsolate:"Eristä",tooltipRestore:"Palauta",componentName:"Puukartta"},"oj-dvtBaseComponent":{labelScalingSuffixThousand:"tuhat",
labelScalingSuffixMillion:"milj.",labelScalingSuffixBillion:"mrd.",labelScalingSuffixTrillion:"bilj.",labelScalingSuffixQuadrillion:"kvadr.",labelInvalidData:"Virheelliset tiedot",labelNoData:"Ei näytettäviä tietoja",labelClearSelection:"Tyhjennä valinnat",labelDataVisualization:"Tietojen visualisointi",stateSelected:"Valittu",stateUnselected:"Valitsematon",stateMaximized:"Suurennettu",stateMinimized:"Pienennetty",stateExpanded:"Laajennettu",stateCollapsed:"Tiivistetty",stateIsolated:"Eristetty",
stateHidden:"Piilotettu",stateVisible:"Näkyvä",stateDrillable:"Siirryttävä",labelAndValue:"{0}: {1}",labelCountWithTotal:"{0}/{1}"},"oj-ojNavigationList":{defaultRootLabel:"Navigointilista",hierMenuBtnLabel:"Hierarkkinen valikkopainike",selectedLabel:"valittu",previousIcon:"Edellinen",msgFetchingData:"Haetaan tietoja...",msgNoData:"Ei näytettäviä alkioita."},"oj-ojSlider":{noValue:"ojSlider ei sisällä arvoa",maxMin:"Enintään ei voi olla pienempi kuin vähintään",valueRange:"Arvon on oltava enintään-vähintään-alueella",
optionNum:"Valinta {option} ei ole luku",invalidStep:"Virheellinen vaihe. Vaiheen on oltava yli 0"},"oj-ojPopup":{ariaLiveRegionInitialFocusFirstFocusable:"Siirrytään kohovalikkoon. F6-näppäimellä voit vaihdella kohovalikon ja siihen liittyvän ohjaimen välillä.",ariaLiveRegionInitialFocusNone:"Kohovalikko avattu. F6-näppäimellä voit vaihdella kohovalikon ja siihen liittyvän ohjaimen välillä.",ariaLiveRegionInitialFocusFirstFocusableTouch:"Siirrytään kohovalikkoon. Voit sulkea kohovalikon siirtymällä sen viimeisimpään linkkiin.",
ariaLiveRegionInitialFocusNoneTouch:"Kohovalikko avattu. Kohdista kohovalikossa siirtymällä seuraavaan linkkiin.",ariaFocusSkipLink:"Siirry avoimeen kohovalikkoon kaksoisnapauttamalla.",ariaCloseSkipLink:"Sulje avoin kohovalikko kaksoisnapauttamalla."},"oj-ojMenu":{ariaLiveRegionInitialFocusMenuTouch:"Siirrytään valikkoon. Valikon voi sulkea valitsematta valikon vaihtoehtoa siirtymällä linkkiin.",ariaLiveRegionInitialFocusNoneTouch:"Valikko avattu. Kohdista valikossa siirtymällä seuraavaan linkkiin.",
"ariaPreceding Link":"Siirry avoimeen valikkoon siirtymällä eteenpäin.",ariaFocusSkipLink:"Siirry avoimeen valikkoon kaksoisnapauttamalla.",ariaCloseSkipLink:"Sulje avoin valikko kaksoisnapauttamalla."},"oj-pullToRefresh":{ariaRefreshLink:"Päivitä sisältö ottamalla käyttöön linkki",ariaRefreshingLink:"Päivitetään sisältöä",ariaRefreshCompleteLink:"Päivitys valmis"},"oj-ojIndexer":{indexerOthers:"#",ariaDisabledLabel:"Ei vastaavaa ryhmän otsikkoa",ariaOthersLabel:"luku",ariaInBetweenText:"Välillä {first} ja {second}",
ariaKeyboardInstructionText:"Valitse arvo painamalla Enter-näppäintä.",ariaTouchInstructionText:"Siirry eletilaan kaksoisnapauttamalla ja painamalla ja säädä sitten arvoa vetämällä ylös- tai alaspäin."}}); |
/* eslint-env node */
module.exports = {
browsers: [
'ie 11',
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions'
]
};
|
/* eslint-disable max-len */
import React from 'react';
import SvgIcon from '@material-ui/core/SvgIcon';
function JSLogo(props) {
return (
<SvgIcon viewBox="0 0 630 630" {...props}>
<g>
<rect width="630" height="630" fill="#f7df1e" />
<path d="m423.2 492.19c12.69 20.72 29.2 35.95 58.4 35.95 24.53 0 40.2-12.26 40.2-29.2 0-20.3-16.1-27.49-43.1-39.3l-14.8-6.35c-42.72-18.2-71.1-41-71.1-89.2 0-44.4 33.83-78.2 86.7-78.2 37.64 0 64.7 13.1 84.2 47.4l-46.1 29.6c-10.15-18.2-21.1-25.37-38.1-25.37-17.34 0-28.33 11-28.33 25.37 0 17.76 11 24.95 36.4 35.95l14.8 6.34c50.3 21.57 78.7 43.56 78.7 93 0 53.3-41.87 82.5-98.1 82.5-54.98 0-90.5-26.2-107.88-60.54zm-209.13 5.13c9.3 16.5 17.76 30.45 38.1 30.45 19.45 0 31.72-7.61 31.72-37.2v-201.3h59.2v202.1c0 61.3-35.94 89.2-88.4 89.2-47.4 0-74.85-24.53-88.81-54.075z" />
</g>
</SvgIcon>
);
}
JSLogo.muiName = 'SvgIcon';
export default JSLogo;
|
// Generated by CoffeeScript 1.6.3
var CoffeeScriptConsole, exports;
CoffeeScriptConsole = (function() {
CoffeeScriptConsole.prototype.outputContainer = '<pre class="outputResult"><i class="icon-cancel"></i><span class="data"></span></pre>';
CoffeeScriptConsole.prototype.echoEvalOutput = true;
CoffeeScriptConsole.prototype.storeInput = true;
CoffeeScriptConsole.prototype.storeOutput = true;
CoffeeScriptConsole.prototype.adjustInputHeightUnit = 'em';
CoffeeScriptConsole.prototype.storePrefix = 'CoffeeScriptConsole_';
function CoffeeScriptConsole(options) {
var $e, attr, i, o, _i, _len, _ref;
if (options == null) {
options = {};
}
if (typeof $ === "undefined" || $ === null) {
throw Error('jQuery is required to use CoffeeScriptConsole');
}
if (options.$input == null) {
options.$input = $('#consoleInput');
}
if (options.$output == null) {
options.$output = $('#consoleOutput');
}
if (store && this.storeInput) {
this.history = store.get('CoffeeScriptConsole_history') || [];
}
this.suggestions = [];
for (attr in options) {
this[attr] = options[attr];
}
this.store = window.store || null;
if (this.store && this.storeOutput) {
this.outputHistory = this.store.get(this.storePrefix + 'output') || [];
_ref = this.outputHistory;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
o = _ref[i];
if (typeof o === 'object' && o) {
$e = this.echo(o.output, {
classification: o.classification,
doStore: false,
data: {
position: i,
code: o.code,
outputString: o.outputString
}
});
}
}
}
this.init();
}
CoffeeScriptConsole.prototype.lastCommand = function() {
return history[history.length] || null;
};
CoffeeScriptConsole.prototype.history = null;
CoffeeScriptConsole.prototype.suggestions = null;
CoffeeScriptConsole.prototype._currentHistoryPosition = null;
CoffeeScriptConsole.prototype.lastPrompt = function() {
return this.history[this.history.length - 1];
};
CoffeeScriptConsole.prototype.addToHistory = function(command) {
command = command != null ? command.trim() : void 0;
if (command) {
if (this.history[this.history.length - 1] && this.history[this.history.length - 1] === command) {
return;
}
this.history.push(command);
}
if (this.store && this.storeInput) {
return this.store.set(this.storePrefix + 'history', this.history);
}
};
CoffeeScriptConsole.prototype.historySuggestionsFor = function(term) {
var command, history, s, suggestions, _i, _len;
term = String(term).trim();
suggestions = [];
history = [].concat(this.history).reverse().concat(this.suggestions);
if (term !== '') {
for (_i = 0, _len = history.length; _i < _len; _i++) {
command = history[_i];
s = String(command).trim();
if (s !== '' && s !== term && s.substring(0, term.length) === term && suggestions.indexOf(s) === -1) {
suggestions.push(s);
}
}
}
return suggestions;
};
CoffeeScriptConsole.prototype.clearHistory = function() {
this.clearOutputHistory();
return this.clearInputHistory();
};
CoffeeScriptConsole.prototype.clearInputHistory = function() {
var _ref;
this.history = [];
if (this.storeInput) {
if ((_ref = this.store) != null) {
_ref.set(this.storePrefix + 'history', this.history);
}
return true;
} else {
return false;
}
};
CoffeeScriptConsole.prototype.storeOutputHistory = function() {
var _ref;
if (this.storeOutput) {
return (_ref = this.store) != null ? _ref.set(this.storePrefix + 'output', this.outputHistory) : void 0;
}
};
CoffeeScriptConsole.prototype.removeFromOutputHistory = function(pos) {
if (this.store && this.storeOutput && this.outputHistory[pos]) {
delete this.outputHistory[pos];
return this.storeOutputHistory();
}
};
CoffeeScriptConsole.prototype.clearOutputHistory = function() {
this.outputHistory = [];
this.storeOutputHistory();
if (this.store && this.storeOutput) {
return true;
} else {
return false;
}
};
CoffeeScriptConsole.prototype._lastPrompt = '';
CoffeeScriptConsole.prototype._objectIsError = function(o) {
if (o && typeof o.message !== 'undefined') {
return true;
} else {
return false;
}
};
CoffeeScriptConsole.prototype.outputString = function(output) {
if (typeof output === 'object' && output !== null) {
return JSON.stringify(output, null, ' ');
} else {
return String(output);
}
};
CoffeeScriptConsole.prototype.outputStringFormatted = function(output) {
if (typeof output === 'object' && output !== null) {
if (output.constructor === Array) {
return json2html(output);
} else if (this._objectIsError(output)) {
return output.message;
} else {
return json2html(output);
}
} else if (output === void 0) {
return 'undefined';
} else if (typeof output === 'function') {
return output.toString();
} else if (String(output).trim() === '') {
return '';
} else {
return output;
}
};
CoffeeScriptConsole.prototype._setCursorToEnd = function(e, $e) {
e.preventDefault();
return $e.get(0).setSelectionRange($e.val().length, $e.val().length);
};
CoffeeScriptConsole.prototype._setCursorToStart = function(e, $e) {
var _ref, _ref1;
e.preventDefault();
return $e.get(0).setSelectionRange((_ref = $e.val().split('\n')) != null ? _ref[0].length : void 0, (_ref1 = $e.val().split('\n')) != null ? _ref1[0].length : void 0);
};
CoffeeScriptConsole.prototype._insertAtCursor = function($e, myValue) {
var endPos, myField, sel, startPos, temp;
myField = $e.get(0);
if (document.selection) {
temp = void 0;
myField.focus();
sel = document.selection.createRange();
temp = sel.text.length;
sel.text = myValue;
if (myValue.length === 0) {
sel.moveStart("character", myValue.length);
sel.moveEnd("character", myValue.length);
} else {
sel.moveStart("character", -myValue.length + temp);
}
return sel.select();
} else if (myField.selectionStart || myField.selectionStart === 0) {
startPos = myField.selectionStart;
endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
myField.selectionStart = startPos + myValue.length;
return myField.selectionEnd = startPos + myValue.length;
} else {
return myField.value += myValue;
}
};
CoffeeScriptConsole.prototype._adjustTextareaHeight = function($e, lines) {
if (lines == null) {
lines = null;
}
if (lines === null) {
lines = $e.val().split('\n').length;
}
if (this.adjustInputHeightUnit) {
return $e.css('height', (lines * 1.5) + this.adjustInputHeightUnit);
} else {
return $e.attr('rows', lines);
}
};
CoffeeScriptConsole.prototype._keyIsTriggeredManuallay = false;
CoffeeScriptConsole.prototype.echo = function(output, options) {
var $e, $output, attr, cssClass, history, historyData, outputAsString, _ref;
if (options == null) {
options = {};
}
if (typeof options.doStore !== 'boolean') {
options.doStore = this.storeOutput;
}
$e = $(this.outputContainer);
if (options.data) {
for (attr in options.data) {
$e.data(attr, options.data[attr]);
}
}
$output = this.$output;
cssClass = '';
if (typeof options.classification === 'string' && options.classification !== 'evalOutput') {
cssClass = options.classification;
$e.addClass(cssClass);
} else {
if (options.classification === 'evalOutput' && !this.echoEvalOutput) {
return $e;
}
if (typeof output === 'function') {
cssClass = 'function';
} else if (typeof output === 'number') {
cssClass = 'number';
} else if (typeof output === 'boolean') {
cssClass = 'boolean';
} else if (typeof output === 'string') {
cssClass = 'string';
} else if (output === void 0) {
cssClass = 'undefined';
} else if (typeof output === 'object') {
if (this._objectIsError(output)) {
cssClass = 'error';
} else if (output === null) {
cssClass = 'null';
} else if ((output != null ? output.constructor : void 0) === Array) {
cssClass = 'array';
} else {
cssClass = 'object';
}
}
}
if (cssClass) {
$e.addClass(cssClass);
}
if (!$e.data('outputString')) {
$e.data('outputString', this.outputString(output));
}
if (this.store && options.doStore) {
history = this.outputHistory;
historyData = {
output: this.outputStringFormatted(output),
classification: cssClass,
code: (_ref = options.data) != null ? _ref.code : void 0,
outputString: $e.data('outputString')
};
history.push(historyData);
store.set(this.storePrefix + 'output', history);
}
outputAsString = this.outputStringFormatted(output);
if (/^\<.+\>/.test(outputAsString)) {
$e.find('span.data').html(outputAsString);
} else {
$e.find('span.data').text(outputAsString);
}
$output.prepend($e);
setTimeout(function() {
return $e.addClass('visible');
}, 100);
return $e;
};
CoffeeScriptConsole.prototype.init = function() {
var $input, $output, self, suggestionFor, suggestionNr;
$output = this.$output;
$input = this.$input;
self = this;
$input.on('keyup', function(e) {
var code, cursorPosition, linesCount;
code = $(this).val();
cursorPosition = $input.get(0).selectionStart;
linesCount = code.split('\n').length;
self._adjustTextareaHeight($input);
if (e.keyCode === 9 && cursorPosition !== code.length) {
return self._insertAtCursor($input, ' ');
}
});
suggestionFor = null;
suggestionNr = 0;
$input.on('focus', function(e) {
return self._adjustTextareaHeight($(this));
});
return $input.on('keydown', function(e) {
var code, cursorPosition, linesCount, originalCode, suggestions, _ref, _ref1;
code = originalCode = $(this).val();
cursorPosition = $input.get(0).selectionStart;
linesCount = code.split('\n').length;
if (code.trim() !== self._lastPrompt) {
$(this).removeClass('error');
}
if (e.keyCode === 9) {
e.preventDefault();
if (cursorPosition === code.length) {
if (suggestionFor === null) {
suggestionFor = code;
}
suggestions = self.historySuggestionsFor(suggestionFor);
if (suggestions[suggestionNr]) {
$(this).val(suggestions[suggestionNr]);
if (suggestionNr + 1 <= suggestions.length) {
suggestionNr++;
} else {
suggestionNr = 0;
$(this).val('');
}
}
} else {
suggestionFor = null;
suggestionNr = 0;
}
} else {
suggestionFor = null;
suggestionNr = 0;
}
if (e.keyCode === 38) {
if (!(cursorPosition <= ((_ref = originalCode.split("\n")) != null ? (_ref1 = _ref[0]) != null ? _ref1.length : void 0 : void 0))) {
return;
}
if (self._currentHistoryPosition === 0) {
return;
}
if (self._currentHistoryPosition === null) {
self._currentHistoryPosition = self.history.length;
}
self._currentHistoryPosition--;
code = self.history[self._currentHistoryPosition];
$(this).val(code);
self._setCursorToStart(e, $(this));
} else if (e.keyCode === 40 && self._currentHistoryPosition >= 0) {
if (!(cursorPosition >= originalCode.split("\n").splice(0, linesCount).join(' ').length)) {
return;
}
if (self._currentHistoryPosition === null) {
self._currentHistoryPosition = self.history.length - 1;
} else if (self.history.length === (self._currentHistoryPosition + 1)) {
self._currentHistoryPosition = null;
$(this).val('');
return;
}
self._currentHistoryPosition++;
code = self.history[self._currentHistoryPosition] || '';
$(this).val(code);
self._setCursorToEnd(e, $(this));
if (!code) {
self._currentHistoryPosition = null;
return;
}
} else if (e.keyCode === 13 && !e.shiftKey) {
e.preventDefault();
self.executeCode();
}
if (typeof code === 'string') {
self._lastPrompt = code.trim();
}
return self._adjustTextareaHeight($(this));
});
};
CoffeeScriptConsole.prototype.compile = function(code) {
return CoffeeScript.compile(code, {
bare: true
});
};
CoffeeScriptConsole.prototype["eval"] = function(code, context) {
if (context == null) {
context = window;
}
return eval.call(window, code);
};
CoffeeScriptConsole.prototype.onBeforeExecutingCode = function(s) {
var codeEscaped, deferString, functionCall, functionParts, line, lines, match;
if (typeof s === 'string') {
s = s.replace(/^\n*(.*)\n*$/, '$1').split('\n').join('\n');
lines = (function() {
var _i, _len, _ref, _results;
_ref = s.split('\n');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
if (line && /^\s*\*[a-zA-Z_$]*[0-9a-zA-Z_$]*\s*\=\s*/.test(line)) {
codeEscaped = line.replace(/'/g, "\\'");
match = line.match(/^(\s*)\*([a-zA-Z_$]*[0-9a-zA-Z_$]*)\s*\=\s*(.+)\s*$/);
functionParts = match[3].match(/^(.*)\(([^\)]*)\)\s*$/);
deferString = "defer err, " + match[2];
if (functionParts) {
functionCall = functionParts[2] ? functionParts[1] + " " + functionParts[2] + ", " + deferString : functionParts[1] + " " + deferString;
} else {
functionCall = match[3] + ", " + deferString;
}
_results.push(("await " + functionCall + "\nif typeof echo is 'function'\n echo(err, { classification: \"\#{if err and not " + match[2] + " then \"error \" else \"\"}evalOutput\", data: { error: err?.message, code: '" + codeEscaped + "' } }) if err\n echo(" + match[2] + ", { classification: \"evalOutput\", data: { code: '" + codeEscaped + "' } })").split('\n').join("\n" + match[1]));
} else {
_results.push(line);
}
}
return _results;
})();
s = lines.join('\n');
}
return s;
};
CoffeeScriptConsole.prototype.executeCode = function(code, $input) {
var $e, e, js, originalCode, output, _ref;
if (code == null) {
code = (_ref = this.$input) != null ? _ref.val() : void 0;
}
if ($input == null) {
$input = this.$input;
}
code = this.onBeforeExecutingCode(originalCode = code);
try {
js = this.compile(code);
output = this["eval"](js);
$input.val('');
this._currentHistoryPosition = null;
this.addToHistory(originalCode);
$e = this.echo(output, {
classification: 'evalOutput',
data: {
code: originalCode,
position: this.outputHistory.length
}
});
if (this.outputStringFormatted(output) === '') {
return;
}
return this.onAfterEvaluate(output, $e);
} catch (_error) {
e = _error;
$input.addClass('error');
$e = this.echo((e != null ? e.message : void 0) || e, {
classification: 'error evalOutput',
data: {
code: originalCode,
error: e.message
}
});
return this.onCodeError(e, $e);
}
};
CoffeeScriptConsole.prototype.onAfterEvaluate = function(output, $e) {};
CoffeeScriptConsole.prototype.onCodeError = function(error, $e) {};
return CoffeeScriptConsole;
})();
if ((typeof require !== "undefined" && require !== null) && (typeof exports !== "undefined" && exports !== null)) {
module.exports = exports = CoffeeScriptConsole;
}
/*
//@ sourceMappingURL=csc.map
*/
|
var calc = function() {
var calc_all_timeout = setTimeout(null, 250);
var data = {
'skills-acquired': 0,
'skills-planned': 0,
'stats-acquired': 0,
'stats-planned': 0,
'profs-acquired': 0,
'profs-planned': 0
}
var recalculate_all = function() {
//if (dynaloader.has_delegations('initial_load')) { return; }
if (!dynaloader.get_gil('ok_to_update_gui')) return;
clearTimeout(calc_all_timeout);
calc_all_timeout = setTimeout(function() {
recalculate('skills-planned');
recalculate('skills-acquired');
recalculate_purchased_stats();
recalculate_planned_stats();
recalculate_purchased_profession();
recalculate_planned_profession();
recalculate_top_level('skills');
recalculate_top_level('stats');
recalculate_top_level('prof');
recalculate_tally();
}, 250);
}
var recalculate_skills = function() {
recalculate('skills-planned');
recalculate('skills-acquired');
recalculate_top_level('skills');
recalculate_tally();
}
var recalculate_purchased_stats = function() {
data['stats-acquired'] = parseInt($('#stat-purchased-hp').val())
+ parseInt($('#stat-purchased-mp').val());
//$('#xp-stats-acquired').text(data['stats-acquired']);
recalculate_top_level('stats');
recalculate_tally();
}
var recalculate_purchased_profession = function() {
var norm = Object.keys(profession_basic.selected()).length - 1;
var forgotten = Object.keys(profession_basic.forgotten()).length;
var conc = Object.keys(profession_conc.selected()).length;
var adv = Object.keys(profession_adv.selected()).length;
if (profile.get_current() != undefined) {
if (profile.get_current()['strain'] == 'Remnants') norm--;
}
norm = norm < 0 ? 0 : norm;
data['profs-acquired'] = 10 * (norm + forgotten * 2) + 30 * conc + 10 * adv;
$('#xp-prof-acquired').text(data['profs-acquired']);
recalculate_top_level('prof');
recalculate_tally();
}
var recalculate_planned_profession = function() {
var sum = 0;
$('#skills-planned').find('.tool-prof-xp').each(function() {
sum += parseInt($(this).text());
})
data['profs-planned'] = sum;
$('#xp-prof-planned').text(data['profs-planned'])
recalculate_top_level('prof');
recalculate_tally();
}
var recalculate_planned_stats = function() {
var sum = 0;
$('#skills-planned').find('.stat-cost').each(function() {
sum += parseInt($(this).text());
})
$('#skills-planned-stats').text(sum);
data['stats-planned'] = sum;
recalculate_top_level('stats');
recalculate_tally();
}
var recalculate_tally = function() {
$('#xp-total-acquired').text(data['skills-acquired'] + data['stats-acquired'] + data['profs-acquired']);
$('#xp-total-planned').text(data['skills-planned'] + data['stats-planned'] + data['profs-planned']);
}
var recalculate_top_level = function(id) {
$('#xp-' + id + '-acquired').text(data[id + '-acquired']);
$('#xp-' + id + '-planned').text(data[id + '-planned']);
}
var recalculate = function(id) {
var sum = 0;
$('#' + id).find('.skill-cost').each(function() {
sum += parseInt($(this).text());
})
$('#' + id + '-xp').text(sum);
data[id] = sum;
}
return {
recalculate_all: recalculate_all,
recalculate_skills: recalculate_skills,
recalculate_planned_stats: recalculate_planned_stats,
recalculate_purchased_stats: recalculate_purchased_stats,
recalculate_purchased_profession: recalculate_purchased_profession,
recalculate_planned_profession: recalculate_planned_profession
}
}() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.