code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
// Generated by CoffeeScript 1.9.3
(function() {
var iframe_template, utils;
utils = require('./utils');
iframe_template = "<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n <script src=\"{{ sockjs_url }}\"></script>\n <script>\n document.domain = document.domain;\n SockJS.bootstrap_iframe();\n </script>\n</head>\n<body>\n <h2>Don't panic!</h2>\n <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p>\n</body>\n</html>";
exports.app = {
iframe: function(req, res) {
var content, context, k, quoted_md5;
context = {
'{{ sockjs_url }}': this.options.sockjs_url
};
content = iframe_template;
for (k in context) {
content = content.replace(k, context[k]);
}
quoted_md5 = '"' + utils.md5_hex(content) + '"';
if ('if-none-match' in req.headers && req.headers['if-none-match'] === quoted_md5) {
res.statusCode = 304;
return '';
}
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
res.setHeader('ETag', quoted_md5);
return content;
}
};
}).call(this);
|
Jorginho211/TFG
|
web/node_modules/sockjs/lib/iframe.js
|
JavaScript
|
gpl-3.0
| 1,235 |
/**
* @param func
* @return {Observable<R>}
* @method let
* @owner Observable
*/
export function letProto(func) {
return func(this);
}
//# sourceMappingURL=let.js.map
|
rospilot/rospilot
|
share/web_assets/nodejs_deps/node_modules/rxjs/_esm2015/operator/let.js
|
JavaScript
|
apache-2.0
| 175 |
AT.prototype.atSepHelpers = {
sepText: function(){
return T9n.get(AccountsTemplates.texts.sep, markIfMissing=false);
},
};
|
foysalit/SpaceTalk
|
packages/useraccounts-core/lib/templates_helpers/at_sep.js
|
JavaScript
|
mit
| 138 |
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date;
if (isNaN(date)) throw SyntaxError("invalid date");
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};
|
j-mcnally/teenage_mutant_ninja_graphs
|
vendor/assets/javascripts/libs/date.format.js
|
JavaScript
|
mit
| 4,117 |
app.controller("LayersLayergroupSimpleController", [ "$scope", function($scope) {
angular.extend($scope, {
center: {
lat: 39,
lng: -100,
zoom: 3
},
layers: {
baselayers: {
xyz: {
name: 'OpenStreetMap (XYZ)',
url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
type: 'xyz'
}
},
overlays: {}
}
});
var tileLayer = {
name: 'Countries',
type: 'xyz',
url: 'http://{s}.tiles.mapbox.com/v3/milkator.press_freedom/{z}/{x}/{y}.png',
visible: true,
layerOptions: {
attribution: 'Map data © 2013 Natural Earth | Data © 2013 <a href="http://www.reporter-ohne-grenzen.de/ranglisten/rangliste-2013/">ROG/RSF</a>',
maxZoom: 5
}
};
var utfGrid = {
name: 'UtfGrid',
type: 'utfGrid',
url: 'http://{s}.tiles.mapbox.com/v3/milkator.press_freedom/{z}/{x}/{y}.grid.json?callback={cb}',
visible: true,
pluginOptions: {
maxZoom: 5,
resolution: 4
}
};
var group = {
name: 'Group Layer',
type: 'group',
visible: true,
layerOptions: {
layers: [ tileLayer, utfGrid],
maxZoom: 5
}
};
$scope.layers['overlays']['Group Layer'] = group;
$scope.$on('leafletDirectiveMap.utfgridMouseover', function(event, leafletEvent) {
$scope.country = leafletEvent.data.name;
});
}]);
|
ronnpang1/otocopy
|
www/lib/angular-leaflet-directive-master/examples/js/controllers/LayersLayergroupSimpleController.js
|
JavaScript
|
mit
| 1,967 |
import React from 'react/addons';
import ContainerListItem from './ContainerListItem.react';
var ContainerList = React.createClass({
componentWillMount: function () {
this.start = Date.now();
},
render: function () {
var containers = this.props.containers.map(container => {
return (
<ContainerListItem key={container.Id} container={container} start={this.start} />
);
});
return (
<ul>
{containers}
</ul>
);
}
});
module.exports = ContainerList;
|
moxiegirl/kitematic
|
src/components/ContainerList.react.js
|
JavaScript
|
apache-2.0
| 517 |
/*! jQuery UI - v1.8.24 - 2012-09-28
* https://github.com/jquery/jquery-ui
* Includes: jquery.ui.datepicker-ka.js
* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
jQuery(function(a){a.datepicker.regional.ka={closeText:"แแแฎแฃแ แแ",prevText:"< แฌแแแ",nextText:"แจแแแแแแ >",currentText:"แแฆแแก",monthNames:["แแแแแแ แ","แแแแแ แแแแ","แแแ แขแ","แแแ แแแ","แแแแกแ","แแแแแกแ","แแแแแกแ","แแแแแกแขแ","แกแแฅแขแแแแแ แ","แแฅแขแแแแแ แ","แแแแแแแ แ","แแแแแแแแ แ"],monthNamesShort:["แแแ","แแแ","แแแ ","แแแ ","แแแ","แแแ","แแแ","แแแ","แกแแฅ","แแฅแข","แแแ","แแแ"],dayNames:["แแแแ แ","แแ แจแแแแแ","แกแแแจแแแแแ","แแแฎแจแแแแแ","แฎแฃแแจแแแแแ","แแแ แแกแแแแ","แจแแแแแ"],dayNamesShort:["แแ","แแ แจ","แกแแ","แแแฎ","แฎแฃแ","แแแ ","แจแแ"],dayNamesMin:["แแ","แแ แจ","แกแแ","แแแฎ","แฎแฃแ","แแแ ","แจแแ"],weekHeader:"แแแแ แ",dateFormat:"dd-mm-yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},a.datepicker.setDefaults(a.datepicker.regional.ka)});
|
jolay/intelisis3
|
sites/all/modules/jquery_update/replace/ui/ui/minified/i18n/jquery.ui.datepicker-ka.min.js
|
JavaScript
|
gpl-2.0
| 1,368 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v5.0.0-alpha.5
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var csvCreator_1 = require("./csvCreator");
var rowRenderer_1 = require("./rendering/rowRenderer");
var headerRenderer_1 = require("./headerRendering/headerRenderer");
var filterManager_1 = require("./filter/filterManager");
var columnController_1 = require("./columnController/columnController");
var selectionController_1 = require("./selectionController");
var gridOptionsWrapper_1 = require("./gridOptionsWrapper");
var gridPanel_1 = require("./gridPanel/gridPanel");
var valueService_1 = require("./valueService");
var masterSlaveService_1 = require("./masterSlaveService");
var eventService_1 = require("./eventService");
var floatingRowModel_1 = require("./rowControllers/floatingRowModel");
var constants_1 = require("./constants");
var context_1 = require("./context/context");
var gridCore_1 = require("./gridCore");
var sortController_1 = require("./sortController");
var paginationController_1 = require("./rowControllers/paginationController");
var focusedCellController_1 = require("./focusedCellController");
var utils_1 = require("./utils");
var cellRendererFactory_1 = require("./rendering/cellRendererFactory");
var cellEditorFactory_1 = require("./rendering/cellEditorFactory");
var GridApi = (function () {
function GridApi() {
}
GridApi.prototype.init = function () {
if (this.rowModel.getType() === constants_1.Constants.ROW_MODEL_TYPE_NORMAL) {
this.inMemoryRowModel = this.rowModel;
}
};
/** Used internally by grid. Not intended to be used by the client. Interface may change between releases. */
GridApi.prototype.__getMasterSlaveService = function () {
return this.masterSlaveService;
};
GridApi.prototype.getFirstRenderedRow = function () {
return this.rowRenderer.getFirstVirtualRenderedRow();
};
GridApi.prototype.getLastRenderedRow = function () {
return this.rowRenderer.getLastVirtualRenderedRow();
};
GridApi.prototype.getDataAsCsv = function (params) {
return this.csvCreator.getDataAsCsv(params);
};
GridApi.prototype.exportDataAsCsv = function (params) {
this.csvCreator.exportDataAsCsv(params);
};
GridApi.prototype.setDatasource = function (datasource) {
if (this.gridOptionsWrapper.isRowModelPagination()) {
this.paginationController.setDatasource(datasource);
}
else if (this.gridOptionsWrapper.isRowModelVirtual()) {
this.rowModel.setDatasource(datasource);
}
else {
console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_VIRTUAL + "' or '" + constants_1.Constants.ROW_MODEL_TYPE_PAGINATION + "'");
}
};
GridApi.prototype.setViewportDatasource = function (viewportDatasource) {
if (this.gridOptionsWrapper.isRowModelViewport()) {
// this is bad coding, because it's using an interface that's exposed in the enterprise.
// really we should create an interface in the core for viewportDatasource and let
// the enterprise implement it, rather than casting to 'any' here
this.rowModel.setViewportDatasource(viewportDatasource);
}
else {
console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_VIEWPORT + "'");
}
};
GridApi.prototype.setRowData = function (rowData) {
if (this.gridOptionsWrapper.isRowModelDefault()) {
this.inMemoryRowModel.setRowData(rowData, true);
}
else {
console.log('cannot call setRowData unless using normal row model');
}
};
GridApi.prototype.setFloatingTopRowData = function (rows) {
this.floatingRowModel.setFloatingTopRowData(rows);
};
GridApi.prototype.setFloatingBottomRowData = function (rows) {
this.floatingRowModel.setFloatingBottomRowData(rows);
};
GridApi.prototype.setColumnDefs = function (colDefs) {
this.columnController.setColumnDefs(colDefs);
};
GridApi.prototype.refreshRows = function (rowNodes) {
this.rowRenderer.refreshRows(rowNodes);
};
GridApi.prototype.refreshCells = function (rowNodes, colIds, animate) {
if (animate === void 0) { animate = false; }
this.rowRenderer.refreshCells(rowNodes, colIds, animate);
};
GridApi.prototype.rowDataChanged = function (rows) {
this.rowRenderer.rowDataChanged(rows);
};
GridApi.prototype.refreshView = function () {
this.rowRenderer.refreshView();
};
GridApi.prototype.softRefreshView = function () {
this.rowRenderer.softRefreshView();
};
GridApi.prototype.refreshGroupRows = function () {
this.rowRenderer.refreshGroupRows();
};
GridApi.prototype.refreshHeader = function () {
// need to review this - the refreshHeader should also refresh all icons in the header
this.headerRenderer.refreshHeader();
};
GridApi.prototype.isAnyFilterPresent = function () {
return this.filterManager.isAnyFilterPresent();
};
GridApi.prototype.isAdvancedFilterPresent = function () {
return this.filterManager.isAdvancedFilterPresent();
};
GridApi.prototype.isQuickFilterPresent = function () {
return this.filterManager.isQuickFilterPresent();
};
GridApi.prototype.getModel = function () {
return this.rowModel;
};
GridApi.prototype.onGroupExpandedOrCollapsed = function (refreshFromIndex) {
if (utils_1.Utils.missing(this.inMemoryRowModel)) {
console.log('cannot call onGroupExpandedOrCollapsed unless using normal row model');
}
this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_MAP, refreshFromIndex);
};
GridApi.prototype.refreshInMemoryRowModel = function () {
if (utils_1.Utils.missing(this.inMemoryRowModel)) {
console.log('cannot call refreshInMemoryRowModel unless using normal row model');
}
this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_EVERYTHING);
};
GridApi.prototype.expandAll = function () {
if (utils_1.Utils.missing(this.inMemoryRowModel)) {
console.log('cannot call expandAll unless using normal row model');
}
this.inMemoryRowModel.expandOrCollapseAll(true);
};
GridApi.prototype.collapseAll = function () {
if (utils_1.Utils.missing(this.inMemoryRowModel)) {
console.log('cannot call collapseAll unless using normal row model');
}
this.inMemoryRowModel.expandOrCollapseAll(false);
};
GridApi.prototype.addVirtualRowListener = function (eventName, rowIndex, callback) {
if (typeof eventName !== 'string') {
console.log('ag-Grid: addVirtualRowListener is deprecated, please use addRenderedRowListener.');
}
this.addRenderedRowListener(eventName, rowIndex, callback);
};
GridApi.prototype.addRenderedRowListener = function (eventName, rowIndex, callback) {
if (eventName === 'virtualRowRemoved') {
console.log('ag-Grid: event virtualRowRemoved is deprecated, now called renderedRowRemoved');
eventName = '' +
'';
}
if (eventName === 'virtualRowSelected') {
console.log('ag-Grid: event virtualRowSelected is deprecated, to register for individual row ' +
'selection events, add a listener directly to the row node.');
}
this.rowRenderer.addRenderedRowListener(eventName, rowIndex, callback);
};
GridApi.prototype.setQuickFilter = function (newFilter) {
this.filterManager.setQuickFilter(newFilter);
};
GridApi.prototype.selectIndex = function (index, tryMulti, suppressEvents) {
console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead');
if (suppressEvents) {
console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it');
}
this.selectionController.selectIndex(index, tryMulti);
};
GridApi.prototype.deselectIndex = function (index, suppressEvents) {
if (suppressEvents === void 0) { suppressEvents = false; }
console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead');
if (suppressEvents) {
console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it');
}
this.selectionController.deselectIndex(index);
};
GridApi.prototype.selectNode = function (node, tryMulti, suppressEvents) {
if (tryMulti === void 0) { tryMulti = false; }
if (suppressEvents === void 0) { suppressEvents = false; }
console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead');
if (suppressEvents) {
console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it');
}
node.setSelectedParams({ newValue: true, clearSelection: !tryMulti });
};
GridApi.prototype.deselectNode = function (node, suppressEvents) {
if (suppressEvents === void 0) { suppressEvents = false; }
console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead');
if (suppressEvents) {
console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it');
}
node.setSelectedParams({ newValue: false });
};
GridApi.prototype.selectAll = function () {
this.selectionController.selectAllRowNodes();
};
GridApi.prototype.deselectAll = function () {
this.selectionController.deselectAllRowNodes();
};
GridApi.prototype.recomputeAggregates = function () {
if (utils_1.Utils.missing(this.inMemoryRowModel)) {
console.log('cannot call recomputeAggregates unless using normal row model');
}
this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_AGGREGATE);
};
GridApi.prototype.sizeColumnsToFit = function () {
if (this.gridOptionsWrapper.isForPrint()) {
console.warn('ag-grid: sizeColumnsToFit does not work when forPrint=true');
return;
}
this.gridPanel.sizeColumnsToFit();
};
GridApi.prototype.showLoadingOverlay = function () {
this.gridPanel.showLoadingOverlay();
};
GridApi.prototype.showNoRowsOverlay = function () {
this.gridPanel.showNoRowsOverlay();
};
GridApi.prototype.hideOverlay = function () {
this.gridPanel.hideOverlay();
};
GridApi.prototype.isNodeSelected = function (node) {
console.log('ag-Grid: no need to call api.isNodeSelected(), just call node.isSelected() instead');
return node.isSelected();
};
GridApi.prototype.getSelectedNodesById = function () {
console.error('ag-Grid: since version 3.4, getSelectedNodesById no longer exists, use getSelectedNodes() instead');
return null;
};
GridApi.prototype.getSelectedNodes = function () {
return this.selectionController.getSelectedNodes();
};
GridApi.prototype.getSelectedRows = function () {
return this.selectionController.getSelectedRows();
};
GridApi.prototype.getBestCostNodeSelection = function () {
return this.selectionController.getBestCostNodeSelection();
};
GridApi.prototype.getRenderedNodes = function () {
return this.rowRenderer.getRenderedNodes();
};
GridApi.prototype.ensureColIndexVisible = function (index) {
console.warn('ag-Grid: ensureColIndexVisible(index) no longer supported, use ensureColumnVisible(colKey) instead.');
};
GridApi.prototype.ensureColumnVisible = function (key) {
this.gridPanel.ensureColumnVisible(key);
};
GridApi.prototype.ensureIndexVisible = function (index) {
this.gridPanel.ensureIndexVisible(index);
};
GridApi.prototype.ensureNodeVisible = function (comparator) {
this.gridCore.ensureNodeVisible(comparator);
};
GridApi.prototype.forEachLeafNode = function (callback) {
if (utils_1.Utils.missing(this.inMemoryRowModel)) {
console.log('cannot call forEachNodeAfterFilter unless using normal row model');
}
this.inMemoryRowModel.forEachLeafNode(callback);
};
GridApi.prototype.forEachNode = function (callback) {
this.rowModel.forEachNode(callback);
};
GridApi.prototype.forEachNodeAfterFilter = function (callback) {
if (utils_1.Utils.missing(this.inMemoryRowModel)) {
console.log('cannot call forEachNodeAfterFilter unless using normal row model');
}
this.inMemoryRowModel.forEachNodeAfterFilter(callback);
};
GridApi.prototype.forEachNodeAfterFilterAndSort = function (callback) {
if (utils_1.Utils.missing(this.inMemoryRowModel)) {
console.log('cannot call forEachNodeAfterFilterAndSort unless using normal row model');
}
this.inMemoryRowModel.forEachNodeAfterFilterAndSort(callback);
};
GridApi.prototype.getFilterApiForColDef = function (colDef) {
console.warn('ag-grid API method getFilterApiForColDef deprecated, use getFilterApi instead');
return this.getFilterApi(colDef);
};
GridApi.prototype.getFilterApi = function (key) {
var column = this.columnController.getPrimaryColumn(key);
if (column) {
return this.filterManager.getFilterApi(column);
}
};
GridApi.prototype.destroyFilter = function (key) {
var column = this.columnController.getPrimaryColumn(key);
if (column) {
return this.filterManager.destroyFilter(column);
}
};
GridApi.prototype.getColumnDef = function (key) {
var column = this.columnController.getPrimaryColumn(key);
if (column) {
return column.getColDef();
}
else {
return null;
}
};
GridApi.prototype.onFilterChanged = function () {
this.filterManager.onFilterChanged();
};
GridApi.prototype.setSortModel = function (sortModel) {
this.sortController.setSortModel(sortModel);
};
GridApi.prototype.getSortModel = function () {
return this.sortController.getSortModel();
};
GridApi.prototype.setFilterModel = function (model) {
this.filterManager.setFilterModel(model);
};
GridApi.prototype.getFilterModel = function () {
return this.filterManager.getFilterModel();
};
GridApi.prototype.getFocusedCell = function () {
return this.focusedCellController.getFocusedCell();
};
GridApi.prototype.setFocusedCell = function (rowIndex, colKey, floating) {
this.focusedCellController.setFocusedCell(rowIndex, colKey, floating, true);
};
GridApi.prototype.setHeaderHeight = function (headerHeight) {
this.gridOptionsWrapper.setHeaderHeight(headerHeight);
};
GridApi.prototype.showToolPanel = function (show) {
this.gridCore.showToolPanel(show);
};
GridApi.prototype.isToolPanelShowing = function () {
return this.gridCore.isToolPanelShowing();
};
GridApi.prototype.doLayout = function () {
this.gridCore.doLayout();
};
GridApi.prototype.getValue = function (colKey, rowNode) {
var column = this.columnController.getPrimaryColumn(colKey);
return this.valueService.getValue(column, rowNode);
};
GridApi.prototype.addEventListener = function (eventType, listener) {
this.eventService.addEventListener(eventType, listener);
};
GridApi.prototype.addGlobalListener = function (listener) {
this.eventService.addGlobalListener(listener);
};
GridApi.prototype.removeEventListener = function (eventType, listener) {
this.eventService.removeEventListener(eventType, listener);
};
GridApi.prototype.removeGlobalListener = function (listener) {
this.eventService.removeGlobalListener(listener);
};
GridApi.prototype.dispatchEvent = function (eventType, event) {
this.eventService.dispatchEvent(eventType, event);
};
GridApi.prototype.destroy = function () {
this.context.destroy();
};
GridApi.prototype.resetQuickFilter = function () {
this.rowModel.forEachNode(function (node) { return node.quickFilterAggregateText = null; });
};
GridApi.prototype.getRangeSelections = function () {
if (this.rangeController) {
return this.rangeController.getCellRanges();
}
else {
console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise');
return null;
}
};
GridApi.prototype.addRangeSelection = function (rangeSelection) {
if (!this.rangeController) {
console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise');
}
this.rangeController.addRange(rangeSelection);
};
GridApi.prototype.clearRangeSelection = function () {
if (!this.rangeController) {
console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise');
}
this.rangeController.clearSelection();
};
GridApi.prototype.copySelectedRowsToClipboard = function () {
if (!this.clipboardService) {
console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise');
}
this.clipboardService.copySelectedRowsToClipboard();
};
GridApi.prototype.copySelectedRangeToClipboard = function () {
if (!this.clipboardService) {
console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise');
}
this.clipboardService.copySelectedRangeToClipboard();
};
GridApi.prototype.copySelectedRangeDown = function () {
if (!this.clipboardService) {
console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise');
}
this.clipboardService.copyRangeDown();
};
GridApi.prototype.showColumnMenuAfterButtonClick = function (colKey, buttonElement) {
var column = this.columnController.getPrimaryColumn(colKey);
this.menuFactory.showMenuAfterButtonClick(column, buttonElement);
};
GridApi.prototype.showColumnMenuAfterMouseClick = function (colKey, mouseEvent) {
var column = this.columnController.getPrimaryColumn(colKey);
this.menuFactory.showMenuAfterMouseEvent(column, mouseEvent);
};
GridApi.prototype.stopEditing = function (cancel) {
if (cancel === void 0) { cancel = false; }
this.rowRenderer.stopEditing(cancel);
};
GridApi.prototype.addAggFunc = function (key, aggFunc) {
if (this.aggFuncService) {
this.aggFuncService.addAggFunc(key, aggFunc);
}
};
GridApi.prototype.addAggFuncs = function (aggFuncs) {
if (this.aggFuncService) {
this.aggFuncService.addAggFuncs(aggFuncs);
}
};
GridApi.prototype.clearAggFuncs = function () {
if (this.aggFuncService) {
this.aggFuncService.clear();
}
};
__decorate([
context_1.Autowired('csvCreator'),
__metadata('design:type', csvCreator_1.CsvCreator)
], GridApi.prototype, "csvCreator", void 0);
__decorate([
context_1.Autowired('gridCore'),
__metadata('design:type', gridCore_1.GridCore)
], GridApi.prototype, "gridCore", void 0);
__decorate([
context_1.Autowired('rowRenderer'),
__metadata('design:type', rowRenderer_1.RowRenderer)
], GridApi.prototype, "rowRenderer", void 0);
__decorate([
context_1.Autowired('headerRenderer'),
__metadata('design:type', headerRenderer_1.HeaderRenderer)
], GridApi.prototype, "headerRenderer", void 0);
__decorate([
context_1.Autowired('filterManager'),
__metadata('design:type', filterManager_1.FilterManager)
], GridApi.prototype, "filterManager", void 0);
__decorate([
context_1.Autowired('columnController'),
__metadata('design:type', columnController_1.ColumnController)
], GridApi.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('selectionController'),
__metadata('design:type', selectionController_1.SelectionController)
], GridApi.prototype, "selectionController", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
], GridApi.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('gridPanel'),
__metadata('design:type', gridPanel_1.GridPanel)
], GridApi.prototype, "gridPanel", void 0);
__decorate([
context_1.Autowired('valueService'),
__metadata('design:type', valueService_1.ValueService)
], GridApi.prototype, "valueService", void 0);
__decorate([
context_1.Autowired('masterSlaveService'),
__metadata('design:type', masterSlaveService_1.MasterSlaveService)
], GridApi.prototype, "masterSlaveService", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata('design:type', eventService_1.EventService)
], GridApi.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('floatingRowModel'),
__metadata('design:type', floatingRowModel_1.FloatingRowModel)
], GridApi.prototype, "floatingRowModel", void 0);
__decorate([
context_1.Autowired('context'),
__metadata('design:type', context_1.Context)
], GridApi.prototype, "context", void 0);
__decorate([
context_1.Autowired('rowModel'),
__metadata('design:type', Object)
], GridApi.prototype, "rowModel", void 0);
__decorate([
context_1.Autowired('sortController'),
__metadata('design:type', sortController_1.SortController)
], GridApi.prototype, "sortController", void 0);
__decorate([
context_1.Autowired('paginationController'),
__metadata('design:type', paginationController_1.PaginationController)
], GridApi.prototype, "paginationController", void 0);
__decorate([
context_1.Autowired('focusedCellController'),
__metadata('design:type', focusedCellController_1.FocusedCellController)
], GridApi.prototype, "focusedCellController", void 0);
__decorate([
context_1.Optional('rangeController'),
__metadata('design:type', Object)
], GridApi.prototype, "rangeController", void 0);
__decorate([
context_1.Optional('clipboardService'),
__metadata('design:type', Object)
], GridApi.prototype, "clipboardService", void 0);
__decorate([
context_1.Optional('aggFuncService'),
__metadata('design:type', Object)
], GridApi.prototype, "aggFuncService", void 0);
__decorate([
context_1.Autowired('menuFactory'),
__metadata('design:type', Object)
], GridApi.prototype, "menuFactory", void 0);
__decorate([
context_1.Autowired('cellRendererFactory'),
__metadata('design:type', cellRendererFactory_1.CellRendererFactory)
], GridApi.prototype, "cellRendererFactory", void 0);
__decorate([
context_1.Autowired('cellEditorFactory'),
__metadata('design:type', cellEditorFactory_1.CellEditorFactory)
], GridApi.prototype, "cellEditorFactory", void 0);
__decorate([
context_1.PostConstruct,
__metadata('design:type', Function),
__metadata('design:paramtypes', []),
__metadata('design:returntype', void 0)
], GridApi.prototype, "init", null);
GridApi = __decorate([
context_1.Bean('gridApi'),
__metadata('design:paramtypes', [])
], GridApi);
return GridApi;
})();
exports.GridApi = GridApi;
|
dlueth/cdnjs
|
ajax/libs/ag-grid/5.0.0-alpha.5/lib/gridApi.js
|
JavaScript
|
mit
| 25,090 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDefault(_SvgIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ContentContentPaste = function ContentContentPaste(props) {
return _react2.default.createElement(
_SvgIcon2.default,
props,
_react2.default.createElement('path', { d: 'M19 2h-4.18C14.4.84 13.3 0 12 0c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm7 18H5V4h2v3h10V4h2v16z' })
);
};
ContentContentPaste = (0, _pure2.default)(ContentContentPaste);
ContentContentPaste.displayName = 'ContentContentPaste';
ContentContentPaste.muiName = 'SvgIcon';
exports.default = ContentContentPaste;
|
Jorginho211/TFG
|
web/node_modules/material-ui/svg-icons/content/content-paste.js
|
JavaScript
|
gpl-3.0
| 1,035 |
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*************************************************************
*
* MathJax/localization/vi/MathML.js
*
* Copyright (c) 2009-2015 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("vi","MathML",{
version: "2.5.0",
isLoaded: true,
strings: {
BadMglyph: "mglyph h\u1ECFng: %1",
BadMglyphFont: "Ph\u00F4ng ch\u1EEF h\u1ECFng: %1",
MathPlayer: "MathJax kh\u00F4ng th\u1EC3 thi\u1EBFt l\u1EADp MathPlayer.\n\nN\u1EBFu MathPlayer ch\u01B0a \u0111\u01B0\u1EE3c c\u00E0i \u0111\u1EB7t, b\u1EA1n c\u1EA7n ph\u1EA3i c\u00E0i \u0111\u1EB7t n\u00F3 tr\u01B0\u1EDBc ti\u00EAn.\nN\u1EBFu kh\u00F4ng, c\u00E1c t\u00F9y ch\u1ECDn b\u1EA3o m\u1EADt c\u1EE7a b\u1EA1n c\u00F3 th\u1EC3 ng\u0103n tr\u1EDF c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m c\u00E1c h\u1ED9p \u201CCh\u1EA1y \u0111i\u1EC1u khi\u1EC3n ActiveX\u201D v\u00E0 \u201CH\u00E0nh vi nh\u1ECB ph\u00E2n v\u00E0 k\u1ECBch b\u1EA3n\u201D.\n\nHi\u1EC7n t\u1EA1i b\u1EA1n s\u1EBD g\u1EB7p c\u00E1c th\u00F4ng b\u00E1o l\u1ED7i thay v\u00EC to\u00E1n h\u1ECDc \u0111\u01B0\u1EE3c k\u1EBFt xu\u1EA5t.",
CantCreateXMLParser: "MathJax kh\u00F4ng th\u1EC3 t\u1EA1o ra b\u1ED9 ph\u00E2n t\u00EDch XML cho MathML. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m h\u1ED9p \u201CScript c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX \u0111\u01B0\u1EE3c \u0111\u00E1nh d\u1EA5u l\u00E0 an to\u00E0n\u201D.\n\nMathJax s\u1EBD kh\u00F4ng th\u1EC3 x\u1EED l\u00FD c\u00E1c ph\u01B0\u01A1ng tr\u00ECnh MathML.",
UnknownNodeType: "Ki\u1EC3u n\u00FAt kh\u00F4ng r\u00F5: %1",
UnexpectedTextNode: "N\u00FAt v\u0103n b\u1EA3n b\u1EA5t ng\u1EEB: %1",
ErrorParsingMathML: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML",
ParsingError: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML: %1",
MathMLSingleElement: "MathML ph\u1EA3i ch\u1EC9 c\u00F3 m\u1ED9t ph\u1EA7n t\u1EED g\u1ED1c",
MathMLRootElement: "Ph\u1EA7n t\u1EED g\u1ED1c c\u1EE7a MathML ph\u1EA3i l\u00E0 \u003Cmath\u003E, ch\u1EE9 kh\u00F4ng ph\u1EA3i %1"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/vi/MathML.js");
|
dongli/mathjax-rails
|
vendor/mathjax/unpacked/localization/vi/MathML.js
|
JavaScript
|
mit
| 3,166 |
/* vtt.js - v0.12.1 (https://github.com/mozilla/vtt.js) built on 21-03-2015 */
/**
* Copyright 2013 vtt.js Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(root) {
var autoKeyword = "auto";
var directionSetting = {
"": true,
"lr": true,
"rl": true
};
var alignSetting = {
"start": true,
"middle": true,
"end": true,
"left": true,
"right": true
};
function findDirectionSetting(value) {
if (typeof value !== "string") {
return false;
}
var dir = directionSetting[value.toLowerCase()];
return dir ? value.toLowerCase() : false;
}
function findAlignSetting(value) {
if (typeof value !== "string") {
return false;
}
var align = alignSetting[value.toLowerCase()];
return align ? value.toLowerCase() : false;
}
function extend(obj) {
var i = 1;
for (; i < arguments.length; i++) {
var cobj = arguments[i];
for (var p in cobj) {
obj[p] = cobj[p];
}
}
return obj;
}
function VTTCue(startTime, endTime, text) {
var cue = this;
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
var baseObj = {};
if (isIE8) {
cue = document.createElement('custom');
} else {
baseObj.enumerable = true;
}
/**
* Shim implementation specific properties. These properties are not in
* the spec.
*/
// Lets us know when the VTTCue's data has changed in such a way that we need
// to recompute its display state. This lets us compute its display state
// lazily.
cue.hasBeenReset = false;
/**
* VTTCue and TextTrackCue properties
* http://dev.w3.org/html5/webvtt/#vttcue-interface
*/
var _id = "";
var _pauseOnExit = false;
var _startTime = startTime;
var _endTime = endTime;
var _text = text;
var _region = null;
var _vertical = "";
var _snapToLines = true;
var _line = "auto";
var _lineAlign = "start";
var _position = 50;
var _positionAlign = "middle";
var _size = 50;
var _align = "middle";
Object.defineProperty(cue,
"id", extend({}, baseObj, {
get: function() {
return _id;
},
set: function(value) {
_id = "" + value;
}
}));
Object.defineProperty(cue,
"pauseOnExit", extend({}, baseObj, {
get: function() {
return _pauseOnExit;
},
set: function(value) {
_pauseOnExit = !!value;
}
}));
Object.defineProperty(cue,
"startTime", extend({}, baseObj, {
get: function() {
return _startTime;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("Start time must be set to a number.");
}
_startTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"endTime", extend({}, baseObj, {
get: function() {
return _endTime;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("End time must be set to a number.");
}
_endTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"text", extend({}, baseObj, {
get: function() {
return _text;
},
set: function(value) {
_text = "" + value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"region", extend({}, baseObj, {
get: function() {
return _region;
},
set: function(value) {
_region = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"vertical", extend({}, baseObj, {
get: function() {
return _vertical;
},
set: function(value) {
var setting = findDirectionSetting(value);
// Have to check for false because the setting an be an empty string.
if (setting === false) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_vertical = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"snapToLines", extend({}, baseObj, {
get: function() {
return _snapToLines;
},
set: function(value) {
_snapToLines = !!value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"line", extend({}, baseObj, {
get: function() {
return _line;
},
set: function(value) {
if (typeof value !== "number" && value !== autoKeyword) {
throw new SyntaxError("An invalid number or illegal string was specified.");
}
_line = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"lineAlign", extend({}, baseObj, {
get: function() {
return _lineAlign;
},
set: function(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_lineAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"position", extend({}, baseObj, {
get: function() {
return _position;
},
set: function(value) {
if (value < 0 || value > 100) {
throw new Error("Position must be between 0 and 100.");
}
_position = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"positionAlign", extend({}, baseObj, {
get: function() {
return _positionAlign;
},
set: function(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_positionAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"size", extend({}, baseObj, {
get: function() {
return _size;
},
set: function(value) {
if (value < 0 || value > 100) {
throw new Error("Size must be between 0 and 100.");
}
_size = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue,
"align", extend({}, baseObj, {
get: function() {
return _align;
},
set: function(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_align = setting;
this.hasBeenReset = true;
}
}));
/**
* Other <track> spec defined properties
*/
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
cue.displayState = undefined;
if (isIE8) {
return cue;
}
}
/**
* VTTCue methods
*/
VTTCue.prototype.getCueAsHTML = function() {
// Assume WebVTT.convertCueToDOMTree is on the global.
return WebVTT.convertCueToDOMTree(window, this.text);
};
root.VTTCue = VTTCue || root.VTTCue;
}(this));
/**
* Copyright 2013 vtt.js Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(root) {
var scrollSetting = {
"": true,
"up": true
};
function findScrollSetting(value) {
if (typeof value !== "string") {
return false;
}
var scroll = scrollSetting[value.toLowerCase()];
return scroll ? value.toLowerCase() : false;
}
function isValidPercentValue(value) {
return typeof value === "number" && (value >= 0 && value <= 100);
}
// VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
function VTTRegion() {
var _width = 100;
var _lines = 3;
var _regionAnchorX = 0;
var _regionAnchorY = 100;
var _viewportAnchorX = 0;
var _viewportAnchorY = 100;
var _scroll = "";
Object.defineProperties(this, {
"width": {
enumerable: true,
get: function() {
return _width;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("Width must be between 0 and 100.");
}
_width = value;
}
},
"lines": {
enumerable: true,
get: function() {
return _lines;
},
set: function(value) {
if (typeof value !== "number") {
throw new TypeError("Lines must be set to a number.");
}
_lines = value;
}
},
"regionAnchorY": {
enumerable: true,
get: function() {
return _regionAnchorY;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("RegionAnchorX must be between 0 and 100.");
}
_regionAnchorY = value;
}
},
"regionAnchorX": {
enumerable: true,
get: function() {
return _regionAnchorX;
},
set: function(value) {
if(!isValidPercentValue(value)) {
throw new Error("RegionAnchorY must be between 0 and 100.");
}
_regionAnchorX = value;
}
},
"viewportAnchorY": {
enumerable: true,
get: function() {
return _viewportAnchorY;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("ViewportAnchorY must be between 0 and 100.");
}
_viewportAnchorY = value;
}
},
"viewportAnchorX": {
enumerable: true,
get: function() {
return _viewportAnchorX;
},
set: function(value) {
if (!isValidPercentValue(value)) {
throw new Error("ViewportAnchorX must be between 0 and 100.");
}
_viewportAnchorX = value;
}
},
"scroll": {
enumerable: true,
get: function() {
return _scroll;
},
set: function(value) {
var setting = findScrollSetting(value);
// Have to check for false as an empty string is a legal value.
if (setting === false) {
throw new SyntaxError("An invalid or illegal string was specified.");
}
_scroll = setting;
}
}
});
}
root.VTTRegion = root.VTTRegion || VTTRegion;
}(this));
/**
* Copyright 2013 vtt.js Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
(function(global) {
var _objCreate = Object.create || (function() {
function F() {}
return function(o) {
if (arguments.length !== 1) {
throw new Error('Object.create shim only accepts one parameter.');
}
F.prototype = o;
return new F();
};
})();
// Creates a new ParserError object from an errorData object. The errorData
// object should have default code and message properties. The default message
// property can be overriden by passing in a message parameter.
// See ParsingError.Errors below for acceptable errors.
function ParsingError(errorData, message) {
this.name = "ParsingError";
this.code = errorData.code;
this.message = message || errorData.message;
}
ParsingError.prototype = _objCreate(Error.prototype);
ParsingError.prototype.constructor = ParsingError;
// ParsingError metadata for acceptable ParsingErrors.
ParsingError.Errors = {
BadSignature: {
code: 0,
message: "Malformed WebVTT signature."
},
BadTimeStamp: {
code: 1,
message: "Malformed time stamp."
}
};
// Try to parse input as a time stamp.
function parseTimeStamp(input) {
function computeSeconds(h, m, s, f) {
return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
}
var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
if (!m) {
return null;
}
if (m[3]) {
// Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
} else if (m[1] > 59) {
// Timestamp takes the form of [hours]:[minutes].[milliseconds]
// First position is hours as it's over 59.
return computeSeconds(m[1], m[2], 0, m[4]);
} else {
// Timestamp takes the form of [minutes]:[seconds].[milliseconds]
return computeSeconds(0, m[1], m[2], m[4]);
}
}
// A settings object holds key/value pairs and will ignore anything but the first
// assignment to a specific key.
function Settings() {
this.values = _objCreate(null);
}
Settings.prototype = {
// Only accept the first assignment to any key.
set: function(k, v) {
if (!this.get(k) && v !== "") {
this.values[k] = v;
}
},
// Return the value for a key, or a default value.
// If 'defaultKey' is passed then 'dflt' is assumed to be an object with
// a number of possible default values as properties where 'defaultKey' is
// the key of the property that will be chosen; otherwise it's assumed to be
// a single value.
get: function(k, dflt, defaultKey) {
if (defaultKey) {
return this.has(k) ? this.values[k] : dflt[defaultKey];
}
return this.has(k) ? this.values[k] : dflt;
},
// Check whether we have a value for a key.
has: function(k) {
return k in this.values;
},
// Accept a setting if its one of the given alternatives.
alt: function(k, v, a) {
for (var n = 0; n < a.length; ++n) {
if (v === a[n]) {
this.set(k, v);
break;
}
}
},
// Accept a setting if its a valid (signed) integer.
integer: function(k, v) {
if (/^-?\d+$/.test(v)) { // integer
this.set(k, parseInt(v, 10));
}
},
// Accept a setting if its a valid percentage.
percent: function(k, v) {
var m;
if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) {
v = parseFloat(v);
if (v >= 0 && v <= 100) {
this.set(k, v);
return true;
}
}
return false;
}
};
// Helper function to parse input into groups separated by 'groupDelim', and
// interprete each group as a key/value pair separated by 'keyValueDelim'.
function parseOptions(input, callback, keyValueDelim, groupDelim) {
var groups = groupDelim ? input.split(groupDelim) : [input];
for (var i in groups) {
if (typeof groups[i] !== "string") {
continue;
}
var kv = groups[i].split(keyValueDelim);
if (kv.length !== 2) {
continue;
}
var k = kv[0];
var v = kv[1];
callback(k, v);
}
}
function parseCue(input, cue, regionList) {
// Remember the original input if we need to throw an error.
var oInput = input;
// 4.1 WebVTT timestamp
function consumeTimeStamp() {
var ts = parseTimeStamp(input);
if (ts === null) {
throw new ParsingError(ParsingError.Errors.BadTimeStamp,
"Malformed timestamp: " + oInput);
}
// Remove time stamp from input.
input = input.replace(/^[^\sa-zA-Z-]+/, "");
return ts;
}
// 4.4.2 WebVTT cue settings
function consumeCueSettings(input, cue) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "region":
// Find the last region we parsed with the same region id.
for (var i = regionList.length - 1; i >= 0; i--) {
if (regionList[i].id === v) {
settings.set(k, regionList[i].region);
break;
}
}
break;
case "vertical":
settings.alt(k, v, ["rl", "lr"]);
break;
case "line":
var vals = v.split(","),
vals0 = vals[0];
settings.integer(k, vals0);
settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
settings.alt(k, vals0, ["auto"]);
if (vals.length === 2) {
settings.alt("lineAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "position":
vals = v.split(",");
settings.percent(k, vals[0]);
if (vals.length === 2) {
settings.alt("positionAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "size":
settings.percent(k, v);
break;
case "align":
settings.alt(k, v, ["start", "middle", "end", "left", "right"]);
break;
}
}, /:/, /\s/);
// Apply default values for any missing fields.
cue.region = settings.get("region", null);
cue.vertical = settings.get("vertical", "");
cue.line = settings.get("line", "auto");
cue.lineAlign = settings.get("lineAlign", "start");
cue.snapToLines = settings.get("snapToLines", true);
cue.size = settings.get("size", 100);
cue.align = settings.get("align", "middle");
cue.position = settings.get("position", {
start: 0,
left: 0,
middle: 50,
end: 100,
right: 100
}, cue.align);
cue.positionAlign = settings.get("positionAlign", {
start: "start",
left: "start",
middle: "middle",
end: "end",
right: "end"
}, cue.align);
}
function skipWhitespace() {
input = input.replace(/^\s+/, "");
}
// 4.1 WebVTT cue timings.
skipWhitespace();
cue.startTime = consumeTimeStamp(); // (1) collect cue start time
skipWhitespace();
if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->"
throw new ParsingError(ParsingError.Errors.BadTimeStamp,
"Malformed time stamp (time stamps must be separated by '-->'): " +
oInput);
}
input = input.substr(3);
skipWhitespace();
cue.endTime = consumeTimeStamp(); // (5) collect cue end time
// 4.1 WebVTT cue settings list.
skipWhitespace();
consumeCueSettings(input, cue);
}
var ESCAPE = {
"&": "&",
"<": "<",
">": ">",
"‎": "\u200e",
"‏": "\u200f",
" ": "\u00a0"
};
var TAG_NAME = {
c: "span",
i: "i",
b: "b",
u: "u",
ruby: "ruby",
rt: "rt",
v: "span",
lang: "span"
};
var TAG_ANNOTATION = {
v: "title",
lang: "lang"
};
var NEEDS_PARENT = {
rt: "ruby"
};
// Parse content into a document fragment.
function parseContent(window, input) {
function nextToken() {
// Check for end-of-string.
if (!input) {
return null;
}
// Consume 'n' characters from the input.
function consume(result) {
input = input.substr(result.length);
return result;
}
var m = input.match(/^([^<]*)(<[^>]+>?)?/);
// If there is some text before the next tag, return it, otherwise return
// the tag.
return consume(m[1] ? m[1] : m[2]);
}
// Unescape a string 's'.
function unescape1(e) {
return ESCAPE[e];
}
function unescape(s) {
while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {
s = s.replace(m[0], unescape1);
}
return s;
}
function shouldAdd(current, element) {
return !NEEDS_PARENT[element.localName] ||
NEEDS_PARENT[element.localName] === current.localName;
}
// Create an element for this tag.
function createElement(type, annotation) {
var tagName = TAG_NAME[type];
if (!tagName) {
return null;
}
var element = window.document.createElement(tagName);
element.localName = tagName;
var name = TAG_ANNOTATION[type];
if (name && annotation) {
element[name] = annotation.trim();
}
return element;
}
var rootDiv = window.document.createElement("div"),
current = rootDiv,
t,
tagStack = [];
while ((t = nextToken()) !== null) {
if (t[0] === '<') {
if (t[1] === "/") {
// If the closing tag matches, move back up to the parent node.
if (tagStack.length &&
tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
tagStack.pop();
current = current.parentNode;
}
// Otherwise just ignore the end tag.
continue;
}
var ts = parseTimeStamp(t.substr(1, t.length - 2));
var node;
if (ts) {
// Timestamps are lead nodes as well.
node = window.document.createProcessingInstruction("timestamp", ts);
current.appendChild(node);
continue;
}
var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
// If we can't parse the tag, skip to the next tag.
if (!m) {
continue;
}
// Try to construct an element, and ignore the tag if we couldn't.
node = createElement(m[1], m[3]);
if (!node) {
continue;
}
// Determine if the tag should be added based on the context of where it
// is placed in the cuetext.
if (!shouldAdd(current, node)) {
continue;
}
// Set the class list (as a list of classes, separated by space).
if (m[2]) {
node.className = m[2].substr(1).replace('.', ' ');
}
// Append the node to the current node, and enter the scope of the new
// node.
tagStack.push(m[1]);
current.appendChild(node);
current = node;
continue;
}
// Text nodes are leaf nodes.
current.appendChild(window.document.createTextNode(unescape(t)));
}
return rootDiv;
}
// This is a list of all the Unicode characters that have a strong
// right-to-left category. What this means is that these characters are
// written right-to-left for sure. It was generated by pulling all the strong
// right-to-left characters out of the Unicode data table. That table can
// found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1,
0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA,
0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3,
0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1,
0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F,
0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628,
0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631,
0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A,
0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643,
0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E,
0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678,
0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681,
0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A,
0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693,
0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C,
0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5,
0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE,
0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7,
0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0,
0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9,
0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2,
0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB,
0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704,
0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D,
0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718,
0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721,
0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A,
0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750,
0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759,
0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762,
0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B,
0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774,
0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D,
0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786,
0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F,
0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798,
0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1,
0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3,
0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC,
0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5,
0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE,
0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7,
0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802,
0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B,
0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814,
0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834,
0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D,
0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847,
0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850,
0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E,
0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9,
0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22,
0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C,
0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35,
0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41,
0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C,
0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55,
0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E,
0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67,
0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70,
0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79,
0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82,
0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B,
0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94,
0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D,
0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6,
0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF,
0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8,
0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1,
0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB,
0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4,
0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED,
0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6,
0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF,
0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08,
0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11,
0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A,
0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23,
0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C,
0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35,
0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E,
0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47,
0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50,
0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59,
0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62,
0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B,
0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74,
0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D,
0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86,
0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F,
0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98,
0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1,
0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA,
0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3,
0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC,
0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5,
0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE,
0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7,
0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0,
0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9,
0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2,
0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB,
0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04,
0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D,
0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16,
0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F,
0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28,
0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31,
0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A,
0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55,
0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E,
0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67,
0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70,
0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79,
0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82,
0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B,
0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96,
0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F,
0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8,
0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1,
0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA,
0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3,
0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4,
0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70,
0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A,
0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83,
0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C,
0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95,
0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E,
0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7,
0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0,
0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9,
0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2,
0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB,
0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4,
0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD,
0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6,
0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF,
0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8,
0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803,
0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E,
0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816,
0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E,
0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826,
0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E,
0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837,
0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844,
0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C,
0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854,
0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D,
0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905,
0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D,
0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915,
0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921,
0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929,
0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931,
0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939,
0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986,
0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E,
0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996,
0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E,
0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6,
0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE,
0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6,
0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13,
0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D,
0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25,
0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D,
0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41,
0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51,
0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60,
0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68,
0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70,
0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78,
0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00,
0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08,
0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10,
0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18,
0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20,
0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28,
0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30,
0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42,
0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A,
0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52,
0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C,
0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64,
0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C,
0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79,
0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01,
0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09,
0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11,
0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19,
0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21,
0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29,
0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31,
0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39,
0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41,
0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00,
0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09,
0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11,
0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19,
0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22,
0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E,
0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37,
0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E,
0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D,
0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A,
0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74,
0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E,
0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87,
0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90,
0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98,
0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6,
0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF,
0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7,
0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD];
function determineBidi(cueDiv) {
var nodeStack = [],
text = "",
charCode;
if (!cueDiv || !cueDiv.childNodes) {
return "ltr";
}
function pushNodes(nodeStack, node) {
for (var i = node.childNodes.length - 1; i >= 0; i--) {
nodeStack.push(node.childNodes[i]);
}
}
function nextTextNode(nodeStack) {
if (!nodeStack || !nodeStack.length) {
return null;
}
var node = nodeStack.pop(),
text = node.textContent || node.innerText;
if (text) {
// TODO: This should match all unicode type B characters (paragraph
// separator characters). See issue #115.
var m = text.match(/^.*(\n|\r)/);
if (m) {
nodeStack.length = 0;
return m[0];
}
return text;
}
if (node.tagName === "ruby") {
return nextTextNode(nodeStack);
}
if (node.childNodes) {
pushNodes(nodeStack, node);
return nextTextNode(nodeStack);
}
}
pushNodes(nodeStack, cueDiv);
while ((text = nextTextNode(nodeStack))) {
for (var i = 0; i < text.length; i++) {
charCode = text.charCodeAt(i);
for (var j = 0; j < strongRTLChars.length; j++) {
if (strongRTLChars[j] === charCode) {
return "rtl";
}
}
}
}
return "ltr";
}
function computeLinePos(cue) {
if (typeof cue.line === "number" &&
(cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) {
return cue.line;
}
if (!cue.track || !cue.track.textTrackList ||
!cue.track.textTrackList.mediaElement) {
return -1;
}
var track = cue.track,
trackList = track.textTrackList,
count = 0;
for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
if (trackList[i].mode === "showing") {
count++;
}
}
return ++count * -1;
}
function StyleBox() {
}
// Apply styles to a div. If there is no div passed then it defaults to the
// div on 'this'.
StyleBox.prototype.applyStyles = function(styles, div) {
div = div || this.div;
for (var prop in styles) {
if (styles.hasOwnProperty(prop)) {
div.style[prop] = styles[prop];
}
}
};
StyleBox.prototype.formatStyle = function(val, unit) {
return val === 0 ? 0 : val + unit;
};
// Constructs the computed display state of the cue (a div). Places the div
// into the overlay which should be a block level element (usually a div).
function CueStyleBox(window, cue, styleOptions) {
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
var color = "rgba(255, 255, 255, 1)";
var backgroundColor = "rgba(0, 0, 0, 0.8)";
if (isIE8) {
color = "rgb(255, 255, 255)";
backgroundColor = "rgb(0, 0, 0)";
}
StyleBox.call(this);
this.cue = cue;
// Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
// have inline positioning and will function as the cue background box.
this.cueDiv = parseContent(window, cue.text);
var styles = {
color: color,
backgroundColor: backgroundColor,
position: "relative",
left: 0,
right: 0,
top: 0,
bottom: 0,
display: "inline"
};
if (!isIE8) {
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl";
styles.unicodeBidi = "plaintext";
}
this.applyStyles(styles, this.cueDiv);
// Create an absolutely positioned div that will be used to position the cue
// div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
// mirrors of them except "middle" which is "center" in CSS.
this.div = window.document.createElement("div");
styles = {
textAlign: cue.align === "middle" ? "center" : cue.align,
font: styleOptions.font,
whiteSpace: "pre-line",
position: "absolute"
};
if (!isIE8) {
styles.direction = determineBidi(this.cueDiv);
styles.writingMode = cue.vertical === "" ? "horizontal-tb"
: cue.vertical === "lr" ? "vertical-lr"
: "vertical-rl".
stylesunicodeBidi = "plaintext";
}
this.applyStyles(styles);
this.div.appendChild(this.cueDiv);
// Calculate the distance from the reference edge of the viewport to the text
// position of the cue box. The reference edge will be resolved later when
// the box orientation styles are applied.
var textPos = 0;
switch (cue.positionAlign) {
case "start":
textPos = cue.position;
break;
case "middle":
textPos = cue.position - (cue.size / 2);
break;
case "end":
textPos = cue.position - cue.size;
break;
}
// Horizontal box orientation; textPos is the distance from the left edge of the
// area to the left edge of the box and cue.size is the distance extending to
// the right from there.
if (cue.vertical === "") {
this.applyStyles({
left: this.formatStyle(textPos, "%"),
width: this.formatStyle(cue.size, "%")
});
// Vertical box orientation; textPos is the distance from the top edge of the
// area to the top edge of the box and cue.size is the height extending
// downwards from there.
} else {
this.applyStyles({
top: this.formatStyle(textPos, "%"),
height: this.formatStyle(cue.size, "%")
});
}
this.move = function(box) {
this.applyStyles({
top: this.formatStyle(box.top, "px"),
bottom: this.formatStyle(box.bottom, "px"),
left: this.formatStyle(box.left, "px"),
right: this.formatStyle(box.right, "px"),
height: this.formatStyle(box.height, "px"),
width: this.formatStyle(box.width, "px")
});
};
}
CueStyleBox.prototype = _objCreate(StyleBox.prototype);
CueStyleBox.prototype.constructor = CueStyleBox;
// Represents the co-ordinates of an Element in a way that we can easily
// compute things with such as if it overlaps or intersects with another Element.
// Can initialize it with either a StyleBox or another BoxPosition.
function BoxPosition(obj) {
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
// Either a BoxPosition was passed in and we need to copy it, or a StyleBox
// was passed in and we need to copy the results of 'getBoundingClientRect'
// as the object returned is readonly. All co-ordinate values are in reference
// to the viewport origin (top left).
var lh, height, width, top;
if (obj.div) {
height = obj.div.offsetHeight;
width = obj.div.offsetWidth;
top = obj.div.offsetTop;
var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
rects.getClientRects && rects.getClientRects();
obj = obj.div.getBoundingClientRect();
// In certain cases the outter div will be slightly larger then the sum of
// the inner div's lines. This could be due to bold text, etc, on some platforms.
// In this case we should get the average line height and use that. This will
// result in the desired behaviour.
lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
: 0;
}
this.left = obj.left;
this.right = obj.right;
this.top = obj.top || top;
this.height = obj.height || height;
this.bottom = obj.bottom || (top + (obj.height || height));
this.width = obj.width || width;
this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
if (isIE8 && !this.lineHeight) {
this.lineHeight = 13;
}
}
// Move the box along a particular axis. Optionally pass in an amount to move
// the box. If no amount is passed then the default is the line height of the
// box.
BoxPosition.prototype.move = function(axis, toMove) {
toMove = toMove !== undefined ? toMove : this.lineHeight;
switch (axis) {
case "+x":
this.left += toMove;
this.right += toMove;
break;
case "-x":
this.left -= toMove;
this.right -= toMove;
break;
case "+y":
this.top += toMove;
this.bottom += toMove;
break;
case "-y":
this.top -= toMove;
this.bottom -= toMove;
break;
}
};
// Check if this box overlaps another box, b2.
BoxPosition.prototype.overlaps = function(b2) {
return this.left < b2.right &&
this.right > b2.left &&
this.top < b2.bottom &&
this.bottom > b2.top;
};
// Check if this box overlaps any other boxes in boxes.
BoxPosition.prototype.overlapsAny = function(boxes) {
for (var i = 0; i < boxes.length; i++) {
if (this.overlaps(boxes[i])) {
return true;
}
}
return false;
};
// Check if this box is within another box.
BoxPosition.prototype.within = function(container) {
return this.top >= container.top &&
this.bottom <= container.bottom &&
this.left >= container.left &&
this.right <= container.right;
};
// Check if this box is entirely within the container or it is overlapping
// on the edge opposite of the axis direction passed. For example, if "+x" is
// passed and the box is overlapping on the left edge of the container, then
// return true.
BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) {
switch (axis) {
case "+x":
return this.left < container.left;
case "-x":
return this.right > container.right;
case "+y":
return this.top < container.top;
case "-y":
return this.bottom > container.bottom;
}
};
// Find the percentage of the area that this box is overlapping with another
// box.
BoxPosition.prototype.intersectPercentage = function(b2) {
var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
intersectArea = x * y;
return intersectArea / (this.height * this.width);
};
// Convert the positions from this box to CSS compatible positions using
// the reference container's positions. This has to be done because this
// box's positions are in reference to the viewport origin, whereas, CSS
// values are in referecne to their respective edges.
BoxPosition.prototype.toCSSCompatValues = function(reference) {
return {
top: this.top - reference.top,
bottom: reference.bottom - this.bottom,
left: this.left - reference.left,
right: reference.right - this.right,
height: this.height,
width: this.width
};
};
// Get an object that represents the box's position without anything extra.
// Can pass a StyleBox, HTMLElement, or another BoxPositon.
BoxPosition.getSimpleBoxPosition = function(obj) {
var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
obj = obj.div ? obj.div.getBoundingClientRect() :
obj.tagName ? obj.getBoundingClientRect() : obj;
var ret = {
left: obj.left,
right: obj.right,
top: obj.top || top,
height: obj.height || height,
bottom: obj.bottom || (top + (obj.height || height)),
width: obj.width || width
};
return ret;
};
// Move a StyleBox to its specified, or next best, position. The containerBox
// is the box that contains the StyleBox, such as a div. boxPositions are
// a list of other boxes that the styleBox can't overlap with.
function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
// Find the best position for a cue box, b, on the video. The axis parameter
// is a list of axis, the order of which, it will move the box along. For example:
// Passing ["+x", "-x"] will move the box first along the x axis in the positive
// direction. If it doesn't find a good position for it there it will then move
// it along the x axis in the negative direction.
function findBestPosition(b, axis) {
var bestPosition,
specifiedPosition = new BoxPosition(b),
percentage = 1; // Highest possible so the first thing we get is better.
for (var i = 0; i < axis.length; i++) {
while (b.overlapsOppositeAxis(containerBox, axis[i]) ||
(b.within(containerBox) && b.overlapsAny(boxPositions))) {
b.move(axis[i]);
}
// We found a spot where we aren't overlapping anything. This is our
// best position.
if (b.within(containerBox)) {
return b;
}
var p = b.intersectPercentage(containerBox);
// If we're outside the container box less then we were on our last try
// then remember this position as the best position.
if (percentage > p) {
bestPosition = new BoxPosition(b);
percentage = p;
}
// Reset the box position to the specified position.
b = new BoxPosition(specifiedPosition);
}
return bestPosition || specifiedPosition;
}
var boxPosition = new BoxPosition(styleBox),
cue = styleBox.cue,
linePos = computeLinePos(cue),
axis = [];
// If we have a line number to align the cue to.
if (cue.snapToLines) {
var size;
switch (cue.vertical) {
case "":
axis = [ "+y", "-y" ];
size = "height";
break;
case "rl":
axis = [ "+x", "-x" ];
size = "width";
break;
case "lr":
axis = [ "-x", "+x" ];
size = "width";
break;
}
var step = boxPosition.lineHeight,
position = step * Math.round(linePos),
maxPosition = containerBox[size] + step,
initialAxis = axis[0];
// If the specified intial position is greater then the max position then
// clamp the box to the amount of steps it would take for the box to
// reach the max position.
if (Math.abs(position) > maxPosition) {
position = position < 0 ? -1 : 1;
position *= Math.ceil(maxPosition / step) * step;
}
// If computed line position returns negative then line numbers are
// relative to the bottom of the video instead of the top. Therefore, we
// need to increase our initial position by the length or width of the
// video, depending on the writing direction, and reverse our axis directions.
if (linePos < 0) {
position += cue.vertical === "" ? containerBox.height : containerBox.width;
axis = axis.reverse();
}
// Move the box to the specified position. This may not be its best
// position.
boxPosition.move(initialAxis, position);
} else {
// If we have a percentage line value for the cue.
var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100;
switch (cue.lineAlign) {
case "middle":
linePos -= (calculatedPercentage / 2);
break;
case "end":
linePos -= calculatedPercentage;
break;
}
// Apply initial line position to the cue box.
switch (cue.vertical) {
case "":
styleBox.applyStyles({
top: styleBox.formatStyle(linePos, "%")
});
break;
case "rl":
styleBox.applyStyles({
left: styleBox.formatStyle(linePos, "%")
});
break;
case "lr":
styleBox.applyStyles({
right: styleBox.formatStyle(linePos, "%")
});
break;
}
axis = [ "+y", "-x", "+x", "-y" ];
// Get the box position again after we've applied the specified positioning
// to it.
boxPosition = new BoxPosition(styleBox);
}
var bestPosition = findBestPosition(boxPosition, axis);
styleBox.move(bestPosition.toCSSCompatValues(containerBox));
}
function WebVTT() {
// Nothing
}
// Helper to allow strings to be decoded instead of the default binary utf8 data.
WebVTT.StringDecoder = function() {
return {
decode: function(data) {
if (!data) {
return "";
}
if (typeof data !== "string") {
throw new Error("Error - expected string data.");
}
return decodeURIComponent(encodeURIComponent(data));
}
};
};
WebVTT.convertCueToDOMTree = function(window, cuetext) {
if (!window || !cuetext) {
return null;
}
return parseContent(window, cuetext);
};
var FONT_SIZE_PERCENT = 0.05;
var FONT_STYLE = "sans-serif";
var CUE_BACKGROUND_PADDING = "1.5%";
// Runs the processing model over the cues and regions passed to it.
// @param overlay A block level element (usually a div) that the computed cues
// and regions will be placed into.
WebVTT.processCues = function(window, cues, overlay) {
if (!window || !cues || !overlay) {
return null;
}
// Remove all previous children.
while (overlay.firstChild) {
overlay.removeChild(overlay.firstChild);
}
var paddedOverlay = window.document.createElement("div");
paddedOverlay.style.position = "absolute";
paddedOverlay.style.left = "0";
paddedOverlay.style.right = "0";
paddedOverlay.style.top = "0";
paddedOverlay.style.bottom = "0";
paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
overlay.appendChild(paddedOverlay);
// Determine if we need to compute the display states of the cues. This could
// be the case if a cue's state has been changed since the last computation or
// if it has not been computed yet.
function shouldCompute(cues) {
for (var i = 0; i < cues.length; i++) {
if (cues[i].hasBeenReset || !cues[i].displayState) {
return true;
}
}
return false;
}
// We don't need to recompute the cues' display states. Just reuse them.
if (!shouldCompute(cues)) {
for (var i = 0; i < cues.length; i++) {
paddedOverlay.appendChild(cues[i].displayState);
}
return;
}
var boxPositions = [],
containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
var styleOptions = {
font: fontSize + "px " + FONT_STYLE
};
(function() {
var styleBox, cue;
for (var i = 0; i < cues.length; i++) {
cue = cues[i];
// Compute the intial position and styles of the cue div.
styleBox = new CueStyleBox(window, cue, styleOptions);
paddedOverlay.appendChild(styleBox.div);
// Move the cue div to it's correct line position.
moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
// Remember the computed div so that we don't have to recompute it later
// if we don't have too.
cue.displayState = styleBox.div;
boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
}
})();
};
WebVTT.Parser = function(window, decoder) {
this.window = window;
this.state = "INITIAL";
this.buffer = "";
this.decoder = decoder || new TextDecoder("utf8");
this.regionList = [];
};
WebVTT.Parser.prototype = {
// If the error is a ParsingError then report it to the consumer if
// possible. If it's not a ParsingError then throw it like normal.
reportOrThrowError: function(e) {
if (e instanceof ParsingError) {
this.onparsingerror && this.onparsingerror(e);
} else {
throw e;
}
},
parse: function (data) {
var self = this;
// If there is no data then we won't decode it, but will just try to parse
// whatever is in buffer already. This may occur in circumstances, for
// example when flush() is called.
if (data) {
// Try to decode the data that we received.
self.buffer += self.decoder.decode(data, {stream: true});
}
function collectNextLine() {
var buffer = self.buffer;
var pos = 0;
while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
++pos;
}
var line = buffer.substr(0, pos);
// Advance the buffer early in case we fail below.
if (buffer[pos] === '\r') {
++pos;
}
if (buffer[pos] === '\n') {
++pos;
}
self.buffer = buffer.substr(pos);
return line;
}
// 3.4 WebVTT region and WebVTT region settings syntax
function parseRegion(input) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "id":
settings.set(k, v);
break;
case "width":
settings.percent(k, v);
break;
case "lines":
settings.integer(k, v);
break;
case "regionanchor":
case "viewportanchor":
var xy = v.split(',');
if (xy.length !== 2) {
break;
}
// We have to make sure both x and y parse, so use a temporary
// settings object here.
var anchor = new Settings();
anchor.percent("x", xy[0]);
anchor.percent("y", xy[1]);
if (!anchor.has("x") || !anchor.has("y")) {
break;
}
settings.set(k + "X", anchor.get("x"));
settings.set(k + "Y", anchor.get("y"));
break;
case "scroll":
settings.alt(k, v, ["up"]);
break;
}
}, /=/, /\s/);
// Create the region, using default values for any values that were not
// specified.
if (settings.has("id")) {
var region = new self.window.VTTRegion();
region.width = settings.get("width", 100);
region.lines = settings.get("lines", 3);
region.regionAnchorX = settings.get("regionanchorX", 0);
region.regionAnchorY = settings.get("regionanchorY", 100);
region.viewportAnchorX = settings.get("viewportanchorX", 0);
region.viewportAnchorY = settings.get("viewportanchorY", 100);
region.scroll = settings.get("scroll", "");
// Register the region.
self.onregion && self.onregion(region);
// Remember the VTTRegion for later in case we parse any VTTCues that
// reference it.
self.regionList.push({
id: settings.get("id"),
region: region
});
}
}
// 3.2 WebVTT metadata header syntax
function parseHeader(input) {
parseOptions(input, function (k, v) {
switch (k) {
case "Region":
// 3.3 WebVTT region metadata header syntax
parseRegion(v);
break;
}
}, /:/);
}
// 5.1 WebVTT file parsing.
try {
var line;
if (self.state === "INITIAL") {
// We can't start parsing until we have the first line.
if (!/\r\n|\n/.test(self.buffer)) {
return this;
}
line = collectNextLine();
var m = line.match(/^WEBVTT([ \t].*)?$/);
if (!m || !m[0]) {
throw new ParsingError(ParsingError.Errors.BadSignature);
}
self.state = "HEADER";
}
var alreadyCollectedLine = false;
while (self.buffer) {
// We can't parse a line until we have the full line.
if (!/\r\n|\n/.test(self.buffer)) {
return this;
}
if (!alreadyCollectedLine) {
line = collectNextLine();
} else {
alreadyCollectedLine = false;
}
switch (self.state) {
case "HEADER":
// 13-18 - Allow a header (metadata) under the WEBVTT line.
if (/:/.test(line)) {
parseHeader(line);
} else if (!line) {
// An empty line terminates the header and starts the body (cues).
self.state = "ID";
}
continue;
case "NOTE":
// Ignore NOTE blocks.
if (!line) {
self.state = "ID";
}
continue;
case "ID":
// Check for the start of NOTE blocks.
if (/^NOTE($|[ \t])/.test(line)) {
self.state = "NOTE";
break;
}
// 19-29 - Allow any number of line terminators, then initialize new cue values.
if (!line) {
continue;
}
self.cue = new self.window.VTTCue(0, 0, "");
self.state = "CUE";
// 30-39 - Check if self line contains an optional identifier or timing data.
if (line.indexOf("-->") === -1) {
self.cue.id = line;
continue;
}
// Process line as start of a cue.
/*falls through*/
case "CUE":
// 40 - Collect cue timings and settings.
try {
parseCue(line, self.cue, self.regionList);
} catch (e) {
self.reportOrThrowError(e);
// In case of an error ignore rest of the cue.
self.cue = null;
self.state = "BADCUE";
continue;
}
self.state = "CUETEXT";
continue;
case "CUETEXT":
var hasSubstring = line.indexOf("-->") !== -1;
// 34 - If we have an empty line then report the cue.
// 35 - If we have the special substring '-->' then report the cue,
// but do not collect the line as we need to process the current
// one as a new cue.
if (!line || hasSubstring && (alreadyCollectedLine = true)) {
// We are done parsing self cue.
self.oncue && self.oncue(self.cue);
self.cue = null;
self.state = "ID";
continue;
}
if (self.cue.text) {
self.cue.text += "\n";
}
self.cue.text += line;
continue;
case "BADCUE": // BADCUE
// 54-62 - Collect and discard the remaining cue.
if (!line) {
self.state = "ID";
}
continue;
}
}
} catch (e) {
self.reportOrThrowError(e);
// If we are currently parsing a cue, report what we have.
if (self.state === "CUETEXT" && self.cue && self.oncue) {
self.oncue(self.cue);
}
self.cue = null;
// Enter BADWEBVTT state if header was not parsed correctly otherwise
// another exception occurred so enter BADCUE state.
self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
}
return this;
},
flush: function () {
var self = this;
try {
// Finish decoding the stream.
self.buffer += self.decoder.decode();
// Synthesize the end of the current cue or region.
if (self.cue || self.state === "HEADER") {
self.buffer += "\n\n";
self.parse();
}
// If we've flushed, parsed, and we're still on the INITIAL state then
// that means we don't have enough of the stream to parse the first
// line.
if (self.state === "INITIAL") {
throw new ParsingError(ParsingError.Errors.BadSignature);
}
} catch(e) {
self.reportOrThrowError(e);
}
self.onflush && self.onflush();
return this;
}
};
global.WebVTT = WebVTT;
}(this));
// If we're in node require encoding-indexes and attach it to the global.
if (typeof module !== "undefined" && module.exports) {
this["encoding-indexes"] = require("./encoding-indexes.js")["encoding-indexes"];
}
(function(global) {
'use strict';
//
// Utilities
//
/**
* @param {number} a The number to test.
* @param {number} min The minimum value in the range, inclusive.
* @param {number} max The maximum value in the range, inclusive.
* @return {boolean} True if a >= min and a <= max.
*/
function inRange(a, min, max) {
return min <= a && a <= max;
}
/**
* @param {number} n The numerator.
* @param {number} d The denominator.
* @return {number} The result of the integer division of n by d.
*/
function div(n, d) {
return Math.floor(n / d);
}
//
// Implementation of Encoding specification
// http://dvcs.w3.org/hg/encoding/raw-file/tip/Overview.html
//
//
// 3. Terminology
//
//
// 4. Encodings
//
/** @const */ var EOF_byte = -1;
/** @const */ var EOF_code_point = -1;
/**
* @constructor
* @param {Uint8Array} bytes Array of bytes that provide the stream.
*/
function ByteInputStream(bytes) {
/** @type {number} */
var pos = 0;
/**
* @this {ByteInputStream}
* @return {number} Get the next byte from the stream.
*/
this.get = function() {
return (pos >= bytes.length) ? EOF_byte : Number(bytes[pos]);
};
/** @param {number} n Number (positive or negative) by which to
* offset the byte pointer. */
this.offset = function(n) {
pos += n;
if (pos < 0) {
throw new Error('Seeking past start of the buffer');
}
if (pos > bytes.length) {
throw new Error('Seeking past EOF');
}
};
/**
* @param {Array.<number>} test Array of bytes to compare against.
* @return {boolean} True if the start of the stream matches the test
* bytes.
*/
this.match = function(test) {
if (test.length > pos + bytes.length) {
return false;
}
var i;
for (i = 0; i < test.length; i += 1) {
if (Number(bytes[pos + i]) !== test[i]) {
return false;
}
}
return true;
};
}
/**
* @constructor
* @param {Array.<number>} bytes The array to write bytes into.
*/
function ByteOutputStream(bytes) {
/** @type {number} */
var pos = 0;
/**
* @param {...number} var_args The byte or bytes to emit into the stream.
* @return {number} The last byte emitted.
*/
this.emit = function(var_args) {
/** @type {number} */
var last = EOF_byte;
var i;
for (i = 0; i < arguments.length; ++i) {
last = Number(arguments[i]);
bytes[pos++] = last;
}
return last;
};
}
/**
* @constructor
* @param {string} string The source of code units for the stream.
*/
function CodePointInputStream(string) {
/**
* @param {string} string Input string of UTF-16 code units.
* @return {Array.<number>} Code points.
*/
function stringToCodePoints(string) {
/** @type {Array.<number>} */
var cps = [];
// Based on http://www.w3.org/TR/WebIDL/#idl-DOMString
var i = 0, n = string.length;
while (i < string.length) {
var c = string.charCodeAt(i);
if (!inRange(c, 0xD800, 0xDFFF)) {
cps.push(c);
} else if (inRange(c, 0xDC00, 0xDFFF)) {
cps.push(0xFFFD);
} else { // (inRange(cu, 0xD800, 0xDBFF))
if (i === n - 1) {
cps.push(0xFFFD);
} else {
var d = string.charCodeAt(i + 1);
if (inRange(d, 0xDC00, 0xDFFF)) {
var a = c & 0x3FF;
var b = d & 0x3FF;
i += 1;
cps.push(0x10000 + (a << 10) + b);
} else {
cps.push(0xFFFD);
}
}
}
i += 1;
}
return cps;
}
/** @type {number} */
var pos = 0;
/** @type {Array.<number>} */
var cps = stringToCodePoints(string);
/** @param {number} n The number of bytes (positive or negative)
* to advance the code point pointer by.*/
this.offset = function(n) {
pos += n;
if (pos < 0) {
throw new Error('Seeking past start of the buffer');
}
if (pos > cps.length) {
throw new Error('Seeking past EOF');
}
};
/** @return {number} Get the next code point from the stream. */
this.get = function() {
if (pos >= cps.length) {
return EOF_code_point;
}
return cps[pos];
};
}
/**
* @constructor
*/
function CodePointOutputStream() {
/** @type {string} */
var string = '';
/** @return {string} The accumulated string. */
this.string = function() {
return string;
};
/** @param {number} c The code point to encode into the stream. */
this.emit = function(c) {
if (c <= 0xFFFF) {
string += String.fromCharCode(c);
} else {
c -= 0x10000;
string += String.fromCharCode(0xD800 + ((c >> 10) & 0x3ff));
string += String.fromCharCode(0xDC00 + (c & 0x3ff));
}
};
}
/**
* @constructor
* @param {string} message Description of the error.
*/
function EncodingError(message) {
this.name = 'EncodingError';
this.message = message;
this.code = 0;
}
EncodingError.prototype = Error.prototype;
/**
* @param {boolean} fatal If true, decoding errors raise an exception.
* @param {number=} opt_code_point Override the standard fallback code point.
* @return {number} The code point to insert on a decoding error.
*/
function decoderError(fatal, opt_code_point) {
if (fatal) {
throw new EncodingError('Decoder error');
}
return opt_code_point || 0xFFFD;
}
/**
* @param {number} code_point The code point that could not be encoded.
* @return {number} Always throws, no value is actually returned.
*/
function encoderError(code_point) {
throw new EncodingError('The code point ' + code_point +
' could not be encoded.');
}
/**
* @param {string} label The encoding label.
* @return {?{name:string,labels:Array.<string>}}
*/
function getEncoding(label) {
label = String(label).trim().toLowerCase();
if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) {
return label_to_encoding[label];
}
return null;
}
/** @type {Array.<{encodings: Array.<{name:string,labels:Array.<string>}>,
* heading: string}>} */
var encodings = [
{
"encodings": [
{
"labels": [
"unicode-1-1-utf-8",
"utf-8",
"utf8"
],
"name": "utf-8"
}
],
"heading": "The Encoding"
},
{
"encodings": [
{
"labels": [
"866",
"cp866",
"csibm866",
"ibm866"
],
"name": "ibm866"
},
{
"labels": [
"csisolatin2",
"iso-8859-2",
"iso-ir-101",
"iso8859-2",
"iso88592",
"iso_8859-2",
"iso_8859-2:1987",
"l2",
"latin2"
],
"name": "iso-8859-2"
},
{
"labels": [
"csisolatin3",
"iso-8859-3",
"iso-ir-109",
"iso8859-3",
"iso88593",
"iso_8859-3",
"iso_8859-3:1988",
"l3",
"latin3"
],
"name": "iso-8859-3"
},
{
"labels": [
"csisolatin4",
"iso-8859-4",
"iso-ir-110",
"iso8859-4",
"iso88594",
"iso_8859-4",
"iso_8859-4:1988",
"l4",
"latin4"
],
"name": "iso-8859-4"
},
{
"labels": [
"csisolatincyrillic",
"cyrillic",
"iso-8859-5",
"iso-ir-144",
"iso8859-5",
"iso88595",
"iso_8859-5",
"iso_8859-5:1988"
],
"name": "iso-8859-5"
},
{
"labels": [
"arabic",
"asmo-708",
"csiso88596e",
"csiso88596i",
"csisolatinarabic",
"ecma-114",
"iso-8859-6",
"iso-8859-6-e",
"iso-8859-6-i",
"iso-ir-127",
"iso8859-6",
"iso88596",
"iso_8859-6",
"iso_8859-6:1987"
],
"name": "iso-8859-6"
},
{
"labels": [
"csisolatingreek",
"ecma-118",
"elot_928",
"greek",
"greek8",
"iso-8859-7",
"iso-ir-126",
"iso8859-7",
"iso88597",
"iso_8859-7",
"iso_8859-7:1987",
"sun_eu_greek"
],
"name": "iso-8859-7"
},
{
"labels": [
"csiso88598e",
"csisolatinhebrew",
"hebrew",
"iso-8859-8",
"iso-8859-8-e",
"iso-ir-138",
"iso8859-8",
"iso88598",
"iso_8859-8",
"iso_8859-8:1988",
"visual"
],
"name": "iso-8859-8"
},
{
"labels": [
"csiso88598i",
"iso-8859-8-i",
"logical"
],
"name": "iso-8859-8-i"
},
{
"labels": [
"csisolatin6",
"iso-8859-10",
"iso-ir-157",
"iso8859-10",
"iso885910",
"l6",
"latin6"
],
"name": "iso-8859-10"
},
{
"labels": [
"iso-8859-13",
"iso8859-13",
"iso885913"
],
"name": "iso-8859-13"
},
{
"labels": [
"iso-8859-14",
"iso8859-14",
"iso885914"
],
"name": "iso-8859-14"
},
{
"labels": [
"csisolatin9",
"iso-8859-15",
"iso8859-15",
"iso885915",
"iso_8859-15",
"l9"
],
"name": "iso-8859-15"
},
{
"labels": [
"iso-8859-16"
],
"name": "iso-8859-16"
},
{
"labels": [
"cskoi8r",
"koi",
"koi8",
"koi8-r",
"koi8_r"
],
"name": "koi8-r"
},
{
"labels": [
"koi8-u"
],
"name": "koi8-u"
},
{
"labels": [
"csmacintosh",
"mac",
"macintosh",
"x-mac-roman"
],
"name": "macintosh"
},
{
"labels": [
"dos-874",
"iso-8859-11",
"iso8859-11",
"iso885911",
"tis-620",
"windows-874"
],
"name": "windows-874"
},
{
"labels": [
"cp1250",
"windows-1250",
"x-cp1250"
],
"name": "windows-1250"
},
{
"labels": [
"cp1251",
"windows-1251",
"x-cp1251"
],
"name": "windows-1251"
},
{
"labels": [
"ansi_x3.4-1968",
"ascii",
"cp1252",
"cp819",
"csisolatin1",
"ibm819",
"iso-8859-1",
"iso-ir-100",
"iso8859-1",
"iso88591",
"iso_8859-1",
"iso_8859-1:1987",
"l1",
"latin1",
"us-ascii",
"windows-1252",
"x-cp1252"
],
"name": "windows-1252"
},
{
"labels": [
"cp1253",
"windows-1253",
"x-cp1253"
],
"name": "windows-1253"
},
{
"labels": [
"cp1254",
"csisolatin5",
"iso-8859-9",
"iso-ir-148",
"iso8859-9",
"iso88599",
"iso_8859-9",
"iso_8859-9:1989",
"l5",
"latin5",
"windows-1254",
"x-cp1254"
],
"name": "windows-1254"
},
{
"labels": [
"cp1255",
"windows-1255",
"x-cp1255"
],
"name": "windows-1255"
},
{
"labels": [
"cp1256",
"windows-1256",
"x-cp1256"
],
"name": "windows-1256"
},
{
"labels": [
"cp1257",
"windows-1257",
"x-cp1257"
],
"name": "windows-1257"
},
{
"labels": [
"cp1258",
"windows-1258",
"x-cp1258"
],
"name": "windows-1258"
},
{
"labels": [
"x-mac-cyrillic",
"x-mac-ukrainian"
],
"name": "x-mac-cyrillic"
}
],
"heading": "Legacy single-byte encodings"
},
{
"encodings": [
{
"labels": [
"chinese",
"csgb2312",
"csiso58gb231280",
"gb18030",
"gb2312",
"gb_2312",
"gb_2312-80",
"gbk",
"iso-ir-58",
"x-gbk"
],
"name": "gb18030"
},
{
"labels": [
"hz-gb-2312"
],
"name": "hz-gb-2312"
}
],
"heading": "Legacy multi-byte Chinese (simplified) encodings"
},
{
"encodings": [
{
"labels": [
"big5",
"big5-hkscs",
"cn-big5",
"csbig5",
"x-x-big5"
],
"name": "big5"
}
],
"heading": "Legacy multi-byte Chinese (traditional) encodings"
},
{
"encodings": [
{
"labels": [
"cseucpkdfmtjapanese",
"euc-jp",
"x-euc-jp"
],
"name": "euc-jp"
},
{
"labels": [
"csiso2022jp",
"iso-2022-jp"
],
"name": "iso-2022-jp"
},
{
"labels": [
"csshiftjis",
"ms_kanji",
"shift-jis",
"shift_jis",
"sjis",
"windows-31j",
"x-sjis"
],
"name": "shift_jis"
}
],
"heading": "Legacy multi-byte Japanese encodings"
},
{
"encodings": [
{
"labels": [
"cseuckr",
"csksc56011987",
"euc-kr",
"iso-ir-149",
"korean",
"ks_c_5601-1987",
"ks_c_5601-1989",
"ksc5601",
"ksc_5601",
"windows-949"
],
"name": "euc-kr"
}
],
"heading": "Legacy multi-byte Korean encodings"
},
{
"encodings": [
{
"labels": [
"csiso2022kr",
"iso-2022-cn",
"iso-2022-cn-ext",
"iso-2022-kr"
],
"name": "replacement"
},
{
"labels": [
"utf-16be"
],
"name": "utf-16be"
},
{
"labels": [
"utf-16",
"utf-16le"
],
"name": "utf-16le"
},
{
"labels": [
"x-user-defined"
],
"name": "x-user-defined"
}
],
"heading": "Legacy miscellaneous encodings"
}
];
var name_to_encoding = {};
var label_to_encoding = {};
encodings.forEach(function(category) {
category['encodings'].forEach(function(encoding) {
name_to_encoding[encoding['name']] = encoding;
encoding['labels'].forEach(function(label) {
label_to_encoding[label] = encoding;
});
});
});
//
// 5. Indexes
//
/**
* @param {number} pointer The |pointer| to search for.
* @param {Array.<?number>|undefined} index The |index| to search within.
* @return {?number} The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in |index|.
*/
function indexCodePointFor(pointer, index) {
if (!index) return null;
return index[pointer] || null;
}
/**
* @param {number} code_point The |code point| to search for.
* @param {Array.<?number>} index The |index| to search within.
* @return {?number} The first pointer corresponding to |code point| in
* |index|, or null if |code point| is not in |index|.
*/
function indexPointerFor(code_point, index) {
var pointer = index.indexOf(code_point);
return pointer === -1 ? null : pointer;
}
/**
* @param {string} name Name of the index.
* @return {(Array.<number>|Array.<Array.<number>>)}
* */
function index(name) {
if (!('encoding-indexes' in global))
throw new Error("Indexes missing. Did you forget to include encoding-indexes.js?");
return global['encoding-indexes'][name];
}
/**
* @param {number} pointer The |pointer| to search for in the gb18030 index.
* @return {?number} The code point corresponding to |pointer| in |index|,
* or null if |code point| is not in the gb18030 index.
*/
function indexGB18030CodePointFor(pointer) {
if ((pointer > 39419 && pointer < 189000) || (pointer > 1237575)) {
return null;
}
var /** @type {number} */ offset = 0,
/** @type {number} */ code_point_offset = 0,
/** @type {Array.<Array.<number>>} */ idx = index('gb18030');
var i;
for (i = 0; i < idx.length; ++i) {
var entry = idx[i];
if (entry[0] <= pointer) {
offset = entry[0];
code_point_offset = entry[1];
} else {
break;
}
}
return code_point_offset + pointer - offset;
}
/**
* @param {number} code_point The |code point| to locate in the gb18030 index.
* @return {number} The first pointer corresponding to |code point| in the
* gb18030 index.
*/
function indexGB18030PointerFor(code_point) {
var /** @type {number} */ offset = 0,
/** @type {number} */ pointer_offset = 0,
/** @type {Array.<Array.<number>>} */ idx = index('gb18030');
var i;
for (i = 0; i < idx.length; ++i) {
var entry = idx[i];
if (entry[1] <= code_point) {
offset = entry[1];
pointer_offset = entry[0];
} else {
break;
}
}
return pointer_offset + code_point - offset;
}
//
// 7. API
//
/** @const */ var DEFAULT_ENCODING = 'utf-8';
// 7.1 Interface TextDecoder
/**
* @constructor
* @param {string=} opt_encoding The label of the encoding;
* defaults to 'utf-8'.
* @param {{fatal: boolean}=} options
*/
function TextDecoder(opt_encoding, options) {
if (!(this instanceof TextDecoder)) {
return new TextDecoder(opt_encoding, options);
}
opt_encoding = opt_encoding ? String(opt_encoding) : DEFAULT_ENCODING;
options = Object(options);
/** @private */
this._encoding = getEncoding(opt_encoding);
if (this._encoding === null || this._encoding.name === 'replacement')
throw new TypeError('Unknown encoding: ' + opt_encoding);
if (!this._encoding.getDecoder)
throw new Error('Decoder not present. Did you forget to include encoding-indexes.js?');
/** @private @type {boolean} */
this._streaming = false;
/** @private @type {boolean} */
this._BOMseen = false;
/** @private */
this._decoder = null;
/** @private @type {{fatal: boolean}=} */
this._options = { fatal: Boolean(options.fatal) };
if (Object.defineProperty) {
Object.defineProperty(
this, 'encoding',
{ get: function() { return this._encoding.name; } });
} else {
this.encoding = this._encoding.name;
}
return this;
}
// TODO: Issue if input byte stream is offset by decoder
// TODO: BOM detection will not work if stream header spans multiple calls
// (last N bytes of previous stream may need to be retained?)
TextDecoder.prototype = {
/**
* @param {ArrayBufferView=} opt_view The buffer of bytes to decode.
* @param {{stream: boolean}=} options
*/
decode: function decode(opt_view, options) {
if (opt_view && !('buffer' in opt_view && 'byteOffset' in opt_view &&
'byteLength' in opt_view)) {
throw new TypeError('Expected ArrayBufferView');
} else if (!opt_view) {
opt_view = new Uint8Array(0);
}
options = Object(options);
if (!this._streaming) {
this._decoder = this._encoding.getDecoder(this._options);
this._BOMseen = false;
}
this._streaming = Boolean(options.stream);
var bytes = new Uint8Array(opt_view.buffer,
opt_view.byteOffset,
opt_view.byteLength);
var input_stream = new ByteInputStream(bytes);
var output_stream = new CodePointOutputStream();
/** @type {number} */
var code_point;
while (input_stream.get() !== EOF_byte) {
code_point = this._decoder.decode(input_stream);
if (code_point !== null && code_point !== EOF_code_point) {
output_stream.emit(code_point);
}
}
if (!this._streaming) {
do {
code_point = this._decoder.decode(input_stream);
if (code_point !== null && code_point !== EOF_code_point) {
output_stream.emit(code_point);
}
} while (code_point !== EOF_code_point &&
input_stream.get() != EOF_byte);
this._decoder = null;
}
var result = output_stream.string();
if (!this._BOMseen && result.length) {
this._BOMseen = true;
if (['utf-8', 'utf-16le', 'utf-16be'].indexOf(this.encoding) !== -1 &&
result.charCodeAt(0) === 0xFEFF) {
result = result.substring(1);
}
}
return result;
}
};
// 7.2 Interface TextEncoder
/**
* @constructor
* @param {string=} opt_encoding The label of the encoding;
* defaults to 'utf-8'.
* @param {{fatal: boolean}=} options
*/
function TextEncoder(opt_encoding, options) {
if (!(this instanceof TextEncoder)) {
return new TextEncoder(opt_encoding, options);
}
opt_encoding = opt_encoding ? String(opt_encoding) : DEFAULT_ENCODING;
options = Object(options);
/** @private */
this._encoding = getEncoding(opt_encoding);
var allowLegacyEncoding = options.NONSTANDARD_allowLegacyEncoding;
var isLegacyEncoding = (this._encoding.name !== 'utf-8' &&
this._encoding.name !== 'utf-16le' &&
this._encoding.name !== 'utf-16be');
if (this._encoding === null || (isLegacyEncoding && !allowLegacyEncoding))
throw new TypeError('Unknown encoding: ' + opt_encoding);
if (!this._encoding.getEncoder)
throw new Error('Encoder not present. Did you forget to include encoding-indexes.js?');
/** @private @type {boolean} */
this._streaming = false;
/** @private */
this._encoder = null;
/** @private @type {{fatal: boolean}=} */
this._options = { fatal: Boolean(options.fatal) };
if (Object.defineProperty) {
Object.defineProperty(
this, 'encoding',
{ get: function() { return this._encoding.name; } });
} else {
this.encoding = this._encoding.name;
}
return this;
}
TextEncoder.prototype = {
/**
* @param {string=} opt_string The string to encode.
* @param {{stream: boolean}=} options
*/
encode: function encode(opt_string, options) {
opt_string = opt_string ? String(opt_string) : '';
options = Object(options);
// TODO: any options?
if (!this._streaming) {
this._encoder = this._encoding.getEncoder(this._options);
}
this._streaming = Boolean(options.stream);
var bytes = [];
var output_stream = new ByteOutputStream(bytes);
var input_stream = new CodePointInputStream(opt_string);
while (input_stream.get() !== EOF_code_point) {
this._encoder.encode(output_stream, input_stream);
}
if (!this._streaming) {
/** @type {number} */
var last_byte;
do {
last_byte = this._encoder.encode(output_stream, input_stream);
} while (last_byte !== EOF_byte);
this._encoder = null;
}
return new Uint8Array(bytes);
}
};
//
// 8. The encoding
//
// 8.1 utf-8
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function UTF8Decoder(options) {
var fatal = options.fatal;
var /** @type {number} */ utf8_code_point = 0,
/** @type {number} */ utf8_bytes_needed = 0,
/** @type {number} */ utf8_bytes_seen = 0,
/** @type {number} */ utf8_lower_boundary = 0;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte) {
if (utf8_bytes_needed !== 0) {
return decoderError(fatal);
}
return EOF_code_point;
}
byte_pointer.offset(1);
if (utf8_bytes_needed === 0) {
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (inRange(bite, 0xC2, 0xDF)) {
utf8_bytes_needed = 1;
utf8_lower_boundary = 0x80;
utf8_code_point = bite - 0xC0;
} else if (inRange(bite, 0xE0, 0xEF)) {
utf8_bytes_needed = 2;
utf8_lower_boundary = 0x800;
utf8_code_point = bite - 0xE0;
} else if (inRange(bite, 0xF0, 0xF4)) {
utf8_bytes_needed = 3;
utf8_lower_boundary = 0x10000;
utf8_code_point = bite - 0xF0;
} else {
return decoderError(fatal);
}
utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed);
return null;
}
if (!inRange(bite, 0x80, 0xBF)) {
utf8_code_point = 0;
utf8_bytes_needed = 0;
utf8_bytes_seen = 0;
utf8_lower_boundary = 0;
byte_pointer.offset(-1);
return decoderError(fatal);
}
utf8_bytes_seen += 1;
utf8_code_point = utf8_code_point + (bite - 0x80) *
Math.pow(64, utf8_bytes_needed - utf8_bytes_seen);
if (utf8_bytes_seen !== utf8_bytes_needed) {
return null;
}
var code_point = utf8_code_point;
var lower_boundary = utf8_lower_boundary;
utf8_code_point = 0;
utf8_bytes_needed = 0;
utf8_bytes_seen = 0;
utf8_lower_boundary = 0;
if (inRange(code_point, lower_boundary, 0x10FFFF) &&
!inRange(code_point, 0xD800, 0xDFFF)) {
return code_point;
}
return decoderError(fatal);
};
}
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function UTF8Encoder(options) {
var fatal = options.fatal;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
/** @type {number} */
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0xD800, 0xDFFF)) {
return encoderError(code_point);
}
if (inRange(code_point, 0x0000, 0x007f)) {
return output_byte_stream.emit(code_point);
}
var count, offset;
if (inRange(code_point, 0x0080, 0x07FF)) {
count = 1;
offset = 0xC0;
} else if (inRange(code_point, 0x0800, 0xFFFF)) {
count = 2;
offset = 0xE0;
} else if (inRange(code_point, 0x10000, 0x10FFFF)) {
count = 3;
offset = 0xF0;
}
var result = output_byte_stream.emit(
div(code_point, Math.pow(64, count)) + offset);
while (count > 0) {
var temp = div(code_point, Math.pow(64, count - 1));
result = output_byte_stream.emit(0x80 + (temp % 64));
count -= 1;
}
return result;
};
}
/** @param {{fatal: boolean}} options */
name_to_encoding['utf-8'].getEncoder = function(options) {
return new UTF8Encoder(options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['utf-8'].getDecoder = function(options) {
return new UTF8Decoder(options);
};
//
// 9. Legacy single-byte encodings
//
/**
* @constructor
* @param {Array.<number>} index The encoding index.
* @param {{fatal: boolean}} options
*/
function SingleByteDecoder(index, options) {
var fatal = options.fatal;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte) {
return EOF_code_point;
}
byte_pointer.offset(1);
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
var code_point = index[bite - 0x80];
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
};
}
/**
* @constructor
* @param {Array.<?number>} index The encoding index.
* @param {{fatal: boolean}} options
*/
function SingleByteEncoder(index, options) {
var fatal = options.fatal;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0x0000, 0x007F)) {
return output_byte_stream.emit(code_point);
}
var pointer = indexPointerFor(code_point, index);
if (pointer === null) {
encoderError(code_point);
}
return output_byte_stream.emit(pointer + 0x80);
};
}
(function() {
if (!('encoding-indexes' in global))
return;
encodings.forEach(function(category) {
if (category['heading'] !== 'Legacy single-byte encodings')
return;
category['encodings'].forEach(function(encoding) {
var idx = index(encoding['name']);
/** @param {{fatal: boolean}} options */
encoding.getDecoder = function(options) {
return new SingleByteDecoder(idx, options);
};
/** @param {{fatal: boolean}} options */
encoding.getEncoder = function(options) {
return new SingleByteEncoder(idx, options);
};
});
});
}());
//
// 10. Legacy multi-byte Chinese (simplified) encodings
//
// 9.1 gb18030
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function GB18030Decoder(options) {
var fatal = options.fatal;
var /** @type {number} */ gb18030_first = 0x00,
/** @type {number} */ gb18030_second = 0x00,
/** @type {number} */ gb18030_third = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && gb18030_first === 0x00 &&
gb18030_second === 0x00 && gb18030_third === 0x00) {
return EOF_code_point;
}
if (bite === EOF_byte &&
(gb18030_first !== 0x00 || gb18030_second !== 0x00 || gb18030_third !== 0x00)) {
gb18030_first = 0x00;
gb18030_second = 0x00;
gb18030_third = 0x00;
decoderError(fatal);
}
byte_pointer.offset(1);
var code_point;
if (gb18030_third !== 0x00) {
code_point = null;
if (inRange(bite, 0x30, 0x39)) {
code_point = indexGB18030CodePointFor(
(((gb18030_first - 0x81) * 10 + (gb18030_second - 0x30)) * 126 +
(gb18030_third - 0x81)) * 10 + bite - 0x30);
}
gb18030_first = 0x00;
gb18030_second = 0x00;
gb18030_third = 0x00;
if (code_point === null) {
byte_pointer.offset(-3);
return decoderError(fatal);
}
return code_point;
}
if (gb18030_second !== 0x00) {
if (inRange(bite, 0x81, 0xFE)) {
gb18030_third = bite;
return null;
}
byte_pointer.offset(-2);
gb18030_first = 0x00;
gb18030_second = 0x00;
return decoderError(fatal);
}
if (gb18030_first !== 0x00) {
if (inRange(bite, 0x30, 0x39)) {
gb18030_second = bite;
return null;
}
var lead = gb18030_first;
var pointer = null;
gb18030_first = 0x00;
var offset = bite < 0x7F ? 0x40 : 0x41;
if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFE)) {
pointer = (lead - 0x81) * 190 + (bite - offset);
}
code_point = pointer === null ? null :
indexCodePointFor(pointer, index('gb18030'));
if (pointer === null) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (bite === 0x80) {
return 0x20AC;
}
if (inRange(bite, 0x81, 0xFE)) {
gb18030_first = bite;
return null;
}
return decoderError(fatal);
};
}
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function GB18030Encoder(options) {
var fatal = options.fatal;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0x0000, 0x007F)) {
return output_byte_stream.emit(code_point);
}
var pointer = indexPointerFor(code_point, index('gb18030'));
if (pointer !== null) {
var lead = div(pointer, 190) + 0x81;
var trail = pointer % 190;
var offset = trail < 0x3F ? 0x40 : 0x41;
return output_byte_stream.emit(lead, trail + offset);
}
pointer = indexGB18030PointerFor(code_point);
var byte1 = div(div(div(pointer, 10), 126), 10);
pointer = pointer - byte1 * 10 * 126 * 10;
var byte2 = div(div(pointer, 10), 126);
pointer = pointer - byte2 * 10 * 126;
var byte3 = div(pointer, 10);
var byte4 = pointer - byte3 * 10;
return output_byte_stream.emit(byte1 + 0x81,
byte2 + 0x30,
byte3 + 0x81,
byte4 + 0x30);
};
}
/** @param {{fatal: boolean}} options */
name_to_encoding['gb18030'].getEncoder = function(options) {
return new GB18030Encoder(options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['gb18030'].getDecoder = function(options) {
return new GB18030Decoder(options);
};
// 10.2 hz-gb-2312
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function HZGB2312Decoder(options) {
var fatal = options.fatal;
var /** @type {boolean} */ hzgb2312 = false,
/** @type {number} */ hzgb2312_lead = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && hzgb2312_lead === 0x00) {
return EOF_code_point;
}
if (bite === EOF_byte && hzgb2312_lead !== 0x00) {
hzgb2312_lead = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
if (hzgb2312_lead === 0x7E) {
hzgb2312_lead = 0x00;
if (bite === 0x7B) {
hzgb2312 = true;
return null;
}
if (bite === 0x7D) {
hzgb2312 = false;
return null;
}
if (bite === 0x7E) {
return 0x007E;
}
if (bite === 0x0A) {
return null;
}
byte_pointer.offset(-1);
return decoderError(fatal);
}
if (hzgb2312_lead !== 0x00) {
var lead = hzgb2312_lead;
hzgb2312_lead = 0x00;
var code_point = null;
if (inRange(bite, 0x21, 0x7E)) {
code_point = indexCodePointFor((lead - 1) * 190 +
(bite + 0x3F), index('gb18030'));
}
if (bite === 0x0A) {
hzgb2312 = false;
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (bite === 0x7E) {
hzgb2312_lead = 0x7E;
return null;
}
if (hzgb2312) {
if (inRange(bite, 0x20, 0x7F)) {
hzgb2312_lead = bite;
return null;
}
if (bite === 0x0A) {
hzgb2312 = false;
}
return decoderError(fatal);
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
return decoderError(fatal);
};
}
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function HZGB2312Encoder(options) {
var fatal = options.fatal;
/** @type {boolean} */
var hzgb2312 = false;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0x0000, 0x007F) && hzgb2312) {
code_point_pointer.offset(-1);
hzgb2312 = false;
return output_byte_stream.emit(0x7E, 0x7D);
}
if (code_point === 0x007E) {
return output_byte_stream.emit(0x7E, 0x7E);
}
if (inRange(code_point, 0x0000, 0x007F)) {
return output_byte_stream.emit(code_point);
}
if (!hzgb2312) {
code_point_pointer.offset(-1);
hzgb2312 = true;
return output_byte_stream.emit(0x7E, 0x7B);
}
var pointer = indexPointerFor(code_point, index('gb18030'));
if (pointer === null) {
return encoderError(code_point);
}
var lead = div(pointer, 190) + 1;
var trail = pointer % 190 - 0x3F;
if (!inRange(lead, 0x21, 0x7E) || !inRange(trail, 0x21, 0x7E)) {
return encoderError(code_point);
}
return output_byte_stream.emit(lead, trail);
};
}
/** @param {{fatal: boolean}} options */
name_to_encoding['hz-gb-2312'].getEncoder = function(options) {
return new HZGB2312Encoder(options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['hz-gb-2312'].getDecoder = function(options) {
return new HZGB2312Decoder(options);
};
//
// 11. Legacy multi-byte Chinese (traditional) encodings
//
// 11.1 big5
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function Big5Decoder(options) {
var fatal = options.fatal;
var /** @type {number} */ big5_lead = 0x00,
/** @type {?number} */ big5_pending = null;
/**
* @param {ByteInputStream} byte_pointer The byte steram to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
// NOTE: Hack to support emitting two code points
if (big5_pending !== null) {
var pending = big5_pending;
big5_pending = null;
return pending;
}
var bite = byte_pointer.get();
if (bite === EOF_byte && big5_lead === 0x00) {
return EOF_code_point;
}
if (bite === EOF_byte && big5_lead !== 0x00) {
big5_lead = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
if (big5_lead !== 0x00) {
var lead = big5_lead;
var pointer = null;
big5_lead = 0x00;
var offset = bite < 0x7F ? 0x40 : 0x62;
if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0xA1, 0xFE)) {
pointer = (lead - 0x81) * 157 + (bite - offset);
}
if (pointer === 1133) {
big5_pending = 0x0304;
return 0x00CA;
}
if (pointer === 1135) {
big5_pending = 0x030C;
return 0x00CA;
}
if (pointer === 1164) {
big5_pending = 0x0304;
return 0x00EA;
}
if (pointer === 1166) {
big5_pending = 0x030C;
return 0x00EA;
}
var code_point = (pointer === null) ? null :
indexCodePointFor(pointer, index('big5'));
if (pointer === null) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (inRange(bite, 0x81, 0xFE)) {
big5_lead = bite;
return null;
}
return decoderError(fatal);
};
}
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function Big5Encoder(options) {
var fatal = options.fatal;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0x0000, 0x007F)) {
return output_byte_stream.emit(code_point);
}
var pointer = indexPointerFor(code_point, index('big5'));
if (pointer === null) {
return encoderError(code_point);
}
var lead = div(pointer, 157) + 0x81;
//if (lead < 0xA1) {
// return encoderError(code_point);
//}
var trail = pointer % 157;
var offset = trail < 0x3F ? 0x40 : 0x62;
return output_byte_stream.emit(lead, trail + offset);
};
}
/** @param {{fatal: boolean}} options */
name_to_encoding['big5'].getEncoder = function(options) {
return new Big5Encoder(options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['big5'].getDecoder = function(options) {
return new Big5Decoder(options);
};
//
// 12. Legacy multi-byte Japanese encodings
//
// 12.1 euc.jp
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function EUCJPDecoder(options) {
var fatal = options.fatal;
var /** @type {number} */ eucjp_first = 0x00,
/** @type {number} */ eucjp_second = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte) {
if (eucjp_first === 0x00 && eucjp_second === 0x00) {
return EOF_code_point;
}
eucjp_first = 0x00;
eucjp_second = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
var lead, code_point;
if (eucjp_second !== 0x00) {
lead = eucjp_second;
eucjp_second = 0x00;
code_point = null;
if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) {
code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1,
index('jis0212'));
}
if (!inRange(bite, 0xA1, 0xFE)) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (eucjp_first === 0x8E && inRange(bite, 0xA1, 0xDF)) {
eucjp_first = 0x00;
return 0xFF61 + bite - 0xA1;
}
if (eucjp_first === 0x8F && inRange(bite, 0xA1, 0xFE)) {
eucjp_first = 0x00;
eucjp_second = bite;
return null;
}
if (eucjp_first !== 0x00) {
lead = eucjp_first;
eucjp_first = 0x00;
code_point = null;
if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) {
code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1,
index('jis0208'));
}
if (!inRange(bite, 0xA1, 0xFE)) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (bite === 0x8E || bite === 0x8F || (inRange(bite, 0xA1, 0xFE))) {
eucjp_first = bite;
return null;
}
return decoderError(fatal);
};
}
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function EUCJPEncoder(options) {
var fatal = options.fatal;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0x0000, 0x007F)) {
return output_byte_stream.emit(code_point);
}
if (code_point === 0x00A5) {
return output_byte_stream.emit(0x5C);
}
if (code_point === 0x203E) {
return output_byte_stream.emit(0x7E);
}
if (inRange(code_point, 0xFF61, 0xFF9F)) {
return output_byte_stream.emit(0x8E, code_point - 0xFF61 + 0xA1);
}
var pointer = indexPointerFor(code_point, index('jis0208'));
if (pointer === null) {
return encoderError(code_point);
}
var lead = div(pointer, 94) + 0xA1;
var trail = pointer % 94 + 0xA1;
return output_byte_stream.emit(lead, trail);
};
}
/** @param {{fatal: boolean}} options */
name_to_encoding['euc-jp'].getEncoder = function(options) {
return new EUCJPEncoder(options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['euc-jp'].getDecoder = function(options) {
return new EUCJPDecoder(options);
};
// 12.2 iso-2022-jp
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function ISO2022JPDecoder(options) {
var fatal = options.fatal;
/** @enum */
var state = {
ASCII: 0,
escape_start: 1,
escape_middle: 2,
escape_final: 3,
lead: 4,
trail: 5,
Katakana: 6
};
var /** @type {number} */ iso2022jp_state = state.ASCII,
/** @type {boolean} */ iso2022jp_jis0212 = false,
/** @type {number} */ iso2022jp_lead = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite !== EOF_byte) {
byte_pointer.offset(1);
}
switch (iso2022jp_state) {
default:
case state.ASCII:
if (bite === 0x1B) {
iso2022jp_state = state.escape_start;
return null;
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (bite === EOF_byte) {
return EOF_code_point;
}
return decoderError(fatal);
case state.escape_start:
if (bite === 0x24 || bite === 0x28) {
iso2022jp_lead = bite;
iso2022jp_state = state.escape_middle;
return null;
}
if (bite !== EOF_byte) {
byte_pointer.offset(-1);
}
iso2022jp_state = state.ASCII;
return decoderError(fatal);
case state.escape_middle:
var lead = iso2022jp_lead;
iso2022jp_lead = 0x00;
if (lead === 0x24 && (bite === 0x40 || bite === 0x42)) {
iso2022jp_jis0212 = false;
iso2022jp_state = state.lead;
return null;
}
if (lead === 0x24 && bite === 0x28) {
iso2022jp_state = state.escape_final;
return null;
}
if (lead === 0x28 && (bite === 0x42 || bite === 0x4A)) {
iso2022jp_state = state.ASCII;
return null;
}
if (lead === 0x28 && bite === 0x49) {
iso2022jp_state = state.Katakana;
return null;
}
if (bite === EOF_byte) {
byte_pointer.offset(-1);
} else {
byte_pointer.offset(-2);
}
iso2022jp_state = state.ASCII;
return decoderError(fatal);
case state.escape_final:
if (bite === 0x44) {
iso2022jp_jis0212 = true;
iso2022jp_state = state.lead;
return null;
}
if (bite === EOF_byte) {
byte_pointer.offset(-2);
} else {
byte_pointer.offset(-3);
}
iso2022jp_state = state.ASCII;
return decoderError(fatal);
case state.lead:
if (bite === 0x0A) {
iso2022jp_state = state.ASCII;
return decoderError(fatal, 0x000A);
}
if (bite === 0x1B) {
iso2022jp_state = state.escape_start;
return null;
}
if (bite === EOF_byte) {
return EOF_code_point;
}
iso2022jp_lead = bite;
iso2022jp_state = state.trail;
return null;
case state.trail:
iso2022jp_state = state.lead;
if (bite === EOF_byte) {
return decoderError(fatal);
}
var code_point = null;
var pointer = (iso2022jp_lead - 0x21) * 94 + bite - 0x21;
if (inRange(iso2022jp_lead, 0x21, 0x7E) &&
inRange(bite, 0x21, 0x7E)) {
code_point = (iso2022jp_jis0212 === false) ?
indexCodePointFor(pointer, index('jis0208')) :
indexCodePointFor(pointer, index('jis0212'));
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
case state.Katakana:
if (bite === 0x1B) {
iso2022jp_state = state.escape_start;
return null;
}
if (inRange(bite, 0x21, 0x5F)) {
return 0xFF61 + bite - 0x21;
}
if (bite === EOF_byte) {
return EOF_code_point;
}
return decoderError(fatal);
}
};
}
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function ISO2022JPEncoder(options) {
var fatal = options.fatal;
/** @enum */
var state = {
ASCII: 0,
lead: 1,
Katakana: 2
};
var /** @type {number} */ iso2022jp_state = state.ASCII;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if ((inRange(code_point, 0x0000, 0x007F) ||
code_point === 0x00A5 || code_point === 0x203E) &&
iso2022jp_state !== state.ASCII) {
code_point_pointer.offset(-1);
iso2022jp_state = state.ASCII;
return output_byte_stream.emit(0x1B, 0x28, 0x42);
}
if (inRange(code_point, 0x0000, 0x007F)) {
return output_byte_stream.emit(code_point);
}
if (code_point === 0x00A5) {
return output_byte_stream.emit(0x5C);
}
if (code_point === 0x203E) {
return output_byte_stream.emit(0x7E);
}
if (inRange(code_point, 0xFF61, 0xFF9F) &&
iso2022jp_state !== state.Katakana) {
code_point_pointer.offset(-1);
iso2022jp_state = state.Katakana;
return output_byte_stream.emit(0x1B, 0x28, 0x49);
}
if (inRange(code_point, 0xFF61, 0xFF9F)) {
return output_byte_stream.emit(code_point - 0xFF61 - 0x21);
}
if (iso2022jp_state !== state.lead) {
code_point_pointer.offset(-1);
iso2022jp_state = state.lead;
return output_byte_stream.emit(0x1B, 0x24, 0x42);
}
var pointer = indexPointerFor(code_point, index('jis0208'));
if (pointer === null) {
return encoderError(code_point);
}
var lead = div(pointer, 94) + 0x21;
var trail = pointer % 94 + 0x21;
return output_byte_stream.emit(lead, trail);
};
}
/** @param {{fatal: boolean}} options */
name_to_encoding['iso-2022-jp'].getEncoder = function(options) {
return new ISO2022JPEncoder(options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['iso-2022-jp'].getDecoder = function(options) {
return new ISO2022JPDecoder(options);
};
// 12.3 shift_jis
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function ShiftJISDecoder(options) {
var fatal = options.fatal;
var /** @type {number} */ shiftjis_lead = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && shiftjis_lead === 0x00) {
return EOF_code_point;
}
if (bite === EOF_byte && shiftjis_lead !== 0x00) {
shiftjis_lead = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
if (shiftjis_lead !== 0x00) {
var lead = shiftjis_lead;
shiftjis_lead = 0x00;
if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFC)) {
var offset = (bite < 0x7F) ? 0x40 : 0x41;
var lead_offset = (lead < 0xA0) ? 0x81 : 0xC1;
var code_point = indexCodePointFor((lead - lead_offset) * 188 +
bite - offset, index('jis0208'));
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
byte_pointer.offset(-1);
return decoderError(fatal);
}
if (inRange(bite, 0x00, 0x80)) {
return bite;
}
if (inRange(bite, 0xA1, 0xDF)) {
return 0xFF61 + bite - 0xA1;
}
if (inRange(bite, 0x81, 0x9F) || inRange(bite, 0xE0, 0xFC)) {
shiftjis_lead = bite;
return null;
}
return decoderError(fatal);
};
}
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function ShiftJISEncoder(options) {
var fatal = options.fatal;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0x0000, 0x0080)) {
return output_byte_stream.emit(code_point);
}
if (code_point === 0x00A5) {
return output_byte_stream.emit(0x5C);
}
if (code_point === 0x203E) {
return output_byte_stream.emit(0x7E);
}
if (inRange(code_point, 0xFF61, 0xFF9F)) {
return output_byte_stream.emit(code_point - 0xFF61 + 0xA1);
}
var pointer = indexPointerFor(code_point, index('jis0208'));
if (pointer === null) {
return encoderError(code_point);
}
var lead = div(pointer, 188);
var lead_offset = lead < 0x1F ? 0x81 : 0xC1;
var trail = pointer % 188;
var offset = trail < 0x3F ? 0x40 : 0x41;
return output_byte_stream.emit(lead + lead_offset, trail + offset);
};
}
/** @param {{fatal: boolean}} options */
name_to_encoding['shift_jis'].getEncoder = function(options) {
return new ShiftJISEncoder(options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['shift_jis'].getDecoder = function(options) {
return new ShiftJISDecoder(options);
};
//
// 13. Legacy multi-byte Korean encodings
//
// 13.1 euc-kr
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function EUCKRDecoder(options) {
var fatal = options.fatal;
var /** @type {number} */ euckr_lead = 0x00;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && euckr_lead === 0) {
return EOF_code_point;
}
if (bite === EOF_byte && euckr_lead !== 0) {
euckr_lead = 0x00;
return decoderError(fatal);
}
byte_pointer.offset(1);
if (euckr_lead !== 0x00) {
var lead = euckr_lead;
var pointer = null;
euckr_lead = 0x00;
if (inRange(lead, 0x81, 0xC6)) {
var temp = (26 + 26 + 126) * (lead - 0x81);
if (inRange(bite, 0x41, 0x5A)) {
pointer = temp + bite - 0x41;
} else if (inRange(bite, 0x61, 0x7A)) {
pointer = temp + 26 + bite - 0x61;
} else if (inRange(bite, 0x81, 0xFE)) {
pointer = temp + 26 + 26 + bite - 0x81;
}
}
if (inRange(lead, 0xC7, 0xFD) && inRange(bite, 0xA1, 0xFE)) {
pointer = (26 + 26 + 126) * (0xC7 - 0x81) + (lead - 0xC7) * 94 +
(bite - 0xA1);
}
var code_point = (pointer === null) ? null :
indexCodePointFor(pointer, index('euc-kr'));
if (pointer === null) {
byte_pointer.offset(-1);
}
if (code_point === null) {
return decoderError(fatal);
}
return code_point;
}
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
if (inRange(bite, 0x81, 0xFD)) {
euckr_lead = bite;
return null;
}
return decoderError(fatal);
};
}
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function EUCKREncoder(options) {
var fatal = options.fatal;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0x0000, 0x007F)) {
return output_byte_stream.emit(code_point);
}
var pointer = indexPointerFor(code_point, index('euc-kr'));
if (pointer === null) {
return encoderError(code_point);
}
var lead, trail;
if (pointer < ((26 + 26 + 126) * (0xC7 - 0x81))) {
lead = div(pointer, (26 + 26 + 126)) + 0x81;
trail = pointer % (26 + 26 + 126);
var offset = trail < 26 ? 0x41 : trail < 26 + 26 ? 0x47 : 0x4D;
return output_byte_stream.emit(lead, trail + offset);
}
pointer = pointer - (26 + 26 + 126) * (0xC7 - 0x81);
lead = div(pointer, 94) + 0xC7;
trail = pointer % 94 + 0xA1;
return output_byte_stream.emit(lead, trail);
};
}
/** @param {{fatal: boolean}} options */
name_to_encoding['euc-kr'].getEncoder = function(options) {
return new EUCKREncoder(options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['euc-kr'].getDecoder = function(options) {
return new EUCKRDecoder(options);
};
//
// 14. Legacy miscellaneous encodings
//
// 14.1 replacement
// Not needed - API throws TypeError
// 14.2 utf-16
/**
* @constructor
* @param {boolean} utf16_be True if big-endian, false if little-endian.
* @param {{fatal: boolean}} options
*/
function UTF16Decoder(utf16_be, options) {
var fatal = options.fatal;
var /** @type {?number} */ utf16_lead_byte = null,
/** @type {?number} */ utf16_lead_surrogate = null;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte && utf16_lead_byte === null &&
utf16_lead_surrogate === null) {
return EOF_code_point;
}
if (bite === EOF_byte && (utf16_lead_byte !== null ||
utf16_lead_surrogate !== null)) {
return decoderError(fatal);
}
byte_pointer.offset(1);
if (utf16_lead_byte === null) {
utf16_lead_byte = bite;
return null;
}
var code_point;
if (utf16_be) {
code_point = (utf16_lead_byte << 8) + bite;
} else {
code_point = (bite << 8) + utf16_lead_byte;
}
utf16_lead_byte = null;
if (utf16_lead_surrogate !== null) {
var lead_surrogate = utf16_lead_surrogate;
utf16_lead_surrogate = null;
if (inRange(code_point, 0xDC00, 0xDFFF)) {
return 0x10000 + (lead_surrogate - 0xD800) * 0x400 +
(code_point - 0xDC00);
}
byte_pointer.offset(-2);
return decoderError(fatal);
}
if (inRange(code_point, 0xD800, 0xDBFF)) {
utf16_lead_surrogate = code_point;
return null;
}
if (inRange(code_point, 0xDC00, 0xDFFF)) {
return decoderError(fatal);
}
return code_point;
};
}
/**
* @constructor
* @param {boolean} utf16_be True if big-endian, false if little-endian.
* @param {{fatal: boolean}} options
*/
function UTF16Encoder(utf16_be, options) {
var fatal = options.fatal;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
/**
* @param {number} code_unit
* @return {number} last byte emitted
*/
function convert_to_bytes(code_unit) {
var byte1 = code_unit >> 8;
var byte2 = code_unit & 0x00FF;
if (utf16_be) {
return output_byte_stream.emit(byte1, byte2);
}
return output_byte_stream.emit(byte2, byte1);
}
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0xD800, 0xDFFF)) {
encoderError(code_point);
}
if (code_point <= 0xFFFF) {
return convert_to_bytes(code_point);
}
var lead = div((code_point - 0x10000), 0x400) + 0xD800;
var trail = ((code_point - 0x10000) % 0x400) + 0xDC00;
convert_to_bytes(lead);
return convert_to_bytes(trail);
};
}
// 14.3 utf-16be
/** @param {{fatal: boolean}} options */
name_to_encoding['utf-16be'].getEncoder = function(options) {
return new UTF16Encoder(true, options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['utf-16be'].getDecoder = function(options) {
return new UTF16Decoder(true, options);
};
// 14.4 utf-16le
/** @param {{fatal: boolean}} options */
name_to_encoding['utf-16le'].getEncoder = function(options) {
return new UTF16Encoder(false, options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['utf-16le'].getDecoder = function(options) {
return new UTF16Decoder(false, options);
};
// 14.5 x-user-defined
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function XUserDefinedDecoder(options) {
var fatal = options.fatal;
/**
* @param {ByteInputStream} byte_pointer The byte stream to decode.
* @return {?number} The next code point decoded, or null if not enough
* data exists in the input stream to decode a complete code point.
*/
this.decode = function(byte_pointer) {
var bite = byte_pointer.get();
if (bite === EOF_byte) {
return EOF_code_point;
}
byte_pointer.offset(1);
if (inRange(bite, 0x00, 0x7F)) {
return bite;
}
return 0xF780 + bite - 0x80;
};
}
/**
* @constructor
* @param {{fatal: boolean}} options
*/
function XUserDefinedEncoder(index, options) {
var fatal = options.fatal;
/**
* @param {ByteOutputStream} output_byte_stream Output byte stream.
* @param {CodePointInputStream} code_point_pointer Input stream.
* @return {number} The last byte emitted.
*/
this.encode = function(output_byte_stream, code_point_pointer) {
var code_point = code_point_pointer.get();
if (code_point === EOF_code_point) {
return EOF_byte;
}
code_point_pointer.offset(1);
if (inRange(code_point, 0x0000, 0x007F)) {
return output_byte_stream.emit(code_point);
}
if (inRange(code_point, 0xF780, 0xF7FF)) {
return output_byte_stream.emit(code_point - 0xF780 + 0x80);
}
encoderError(code_point);
};
}
/** @param {{fatal: boolean}} options */
name_to_encoding['x-user-defined'].getEncoder = function(options) {
return new XUserDefinedEncoder(false, options);
};
/** @param {{fatal: boolean}} options */
name_to_encoding['x-user-defined'].getDecoder = function(options) {
return new XUserDefinedDecoder(false, options);
};
// NOTE: currently unused
/**
* @param {string} label The encoding label.
* @param {ByteInputStream} input_stream The byte stream to test.
*/
function detectEncoding(label, input_stream) {
if (input_stream.match([0xFF, 0xFE])) {
input_stream.offset(2);
return 'utf-16le';
}
if (input_stream.match([0xFE, 0xFF])) {
input_stream.offset(2);
return 'utf-16be';
}
if (input_stream.match([0xEF, 0xBB, 0xBF])) {
input_stream.offset(3);
return 'utf-8';
}
return label;
}
if (!('TextEncoder' in global)) global['TextEncoder'] = TextEncoder;
if (!('TextDecoder' in global)) global['TextDecoder'] = TextDecoder;
}(this));
|
RickEyre/vtt.js-dist
|
vtt.js
|
JavaScript
|
mpl-2.0
| 138,701 |
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*
* @category Shopware
* @package CanceledOrder
* @subpackage Store
* @version $Id$
* @author shopware AG
*/
/**
* Shopware Store - canceled baskets' articles
*/
//{block name="backend/canceled_order/store/articles"}
Ext.define('Shopware.apps.CanceledOrder.store.Articles', {
extend: 'Ext.data.Store',
// Do not load data, when not explicitly requested
autoLoad: false,
model : 'Shopware.apps.CanceledOrder.model.Articles',
remoteFilter: true,
remoteSort: true,
/**
* Configure the data communication
* @object
*/
proxy: {
type: 'ajax',
/**
* Configure the url mapping
* @object
*/
api: {
read: '{url controller=CanceledOrder action="getArticle"}'
},
/**
* Configure the data reader
* @object
*/
reader: {
type: 'json',
root: 'data',
totalProperty:'total'
}
}
});
//{/block}
|
ShopwareHackathon/shopware_search_optimization
|
themes/Backend/ExtJs/backend/canceled_order/store/articles.js
|
JavaScript
|
agpl-3.0
| 1,931 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks['$' + event] = this._callbacks['$' + event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
function on() {
this.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
var callbacks = this._callbacks['$' + event];
if (!callbacks) return this;
if (1 == arguments.length) {
delete this._callbacks['$' + event];
return this;
}
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks['$' + event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks['$' + event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
},{}],2:[function(require,module,exports){
/*!
* domready (c) Dustin Diaz 2012 - License MIT
*/
!function (name, definition) {
if (typeof module != 'undefined') module.exports = definition()
else if (typeof define == 'function' && typeof define.amd == 'object') {}
else this[name] = definition()
}('domready', function (ready) {
var fns = [], fn, f = false
, doc = document
, testEl = doc.documentElement
, hack = testEl.doScroll
, domContentLoaded = 'DOMContentLoaded'
, addEventListener = 'addEventListener'
, onreadystatechange = 'onreadystatechange'
, readyState = 'readyState'
, loadedRgx = hack ? /^loaded|^c/ : /^loaded|c/
, loaded = loadedRgx.test(doc[readyState])
function flush(f) {
loaded = 1
while (f = fns.shift()) f()
}
doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () {
doc.removeEventListener(domContentLoaded, fn, f)
flush()
}, f)
hack && doc.attachEvent(onreadystatechange, fn = function () {
if (/^c/.test(doc[readyState])) {
doc.detachEvent(onreadystatechange, fn)
flush()
}
})
return (ready = hack ?
function (fn) {
self != top ?
loaded ? fn() : fns.push(fn) :
function () {
try {
testEl.doScroll('left')
} catch (e) {
return setTimeout(function() { ready(fn) }, 50)
}
fn()
}()
} :
function (fn) {
loaded ? fn() : fns.push(fn)
})
})
},{}],3:[function(require,module,exports){
(function (global){
/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
;(function () {
var isLoader = typeof define === "function" && define.amd;
var objectTypes = {
"function": true,
"object": true
};
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
var root = objectTypes[typeof window] && window || this,
freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
root = freeGlobal;
}
function runInContext(context, exports) {
context || (context = root["Object"]());
exports || (exports = root["Object"]());
var Number = context["Number"] || root["Number"],
String = context["String"] || root["String"],
Object = context["Object"] || root["Object"],
Date = context["Date"] || root["Date"],
SyntaxError = context["SyntaxError"] || root["SyntaxError"],
TypeError = context["TypeError"] || root["TypeError"],
Math = context["Math"] || root["Math"],
nativeJSON = context["JSON"] || root["JSON"];
if (typeof nativeJSON == "object" && nativeJSON) {
exports.stringify = nativeJSON.stringify;
exports.parse = nativeJSON.parse;
}
var objectProto = Object.prototype,
getClass = objectProto.toString,
isProperty, forEach, undef;
var isExtended = new Date(-3509827334573292);
try {
isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
} catch (exception) {}
function has(name) {
if (has[name] !== undef) {
return has[name];
}
var isSupported;
if (name == "bug-string-char-index") {
isSupported = "a"[0] != "a";
} else if (name == "json") {
isSupported = has("json-stringify") && has("json-parse");
} else {
var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
if (name == "json-stringify") {
var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
if (stringifySupported) {
(value = function () {
return 1;
}).toJSON = value;
try {
stringifySupported =
stringify(0) === "0" &&
stringify(new Number()) === "0" &&
stringify(new String()) == '""' &&
stringify(getClass) === undef &&
stringify(undef) === undef &&
stringify() === undef &&
stringify(value) === "1" &&
stringify([value]) == "[1]" &&
stringify([undef]) == "[null]" &&
stringify(null) == "null" &&
stringify([undef, getClass, null]) == "[null,null,null]" &&
stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
stringify(null, value) === "1" &&
stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
} catch (exception) {
stringifySupported = false;
}
}
isSupported = stringifySupported;
}
if (name == "json-parse") {
var parse = exports.parse;
if (typeof parse == "function") {
try {
if (parse("0") === 0 && !parse(false)) {
value = parse(serialized);
var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
if (parseSupported) {
try {
parseSupported = !parse('"\t"');
} catch (exception) {}
if (parseSupported) {
try {
parseSupported = parse("01") !== 1;
} catch (exception) {}
}
if (parseSupported) {
try {
parseSupported = parse("1.") !== 1;
} catch (exception) {}
}
}
}
} catch (exception) {
parseSupported = false;
}
}
isSupported = parseSupported;
}
}
return has[name] = !!isSupported;
}
if (!has("json")) {
var functionClass = "[object Function]",
dateClass = "[object Date]",
numberClass = "[object Number]",
stringClass = "[object String]",
arrayClass = "[object Array]",
booleanClass = "[object Boolean]";
var charIndexBuggy = has("bug-string-char-index");
if (!isExtended) {
var floor = Math.floor;
var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var getDay = function (year, month) {
return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
};
}
if (!(isProperty = objectProto.hasOwnProperty)) {
isProperty = function (property) {
var members = {}, constructor;
if ((members.__proto__ = null, members.__proto__ = {
"toString": 1
}, members).toString != getClass) {
isProperty = function (property) {
var original = this.__proto__, result = property in (this.__proto__ = null, this);
this.__proto__ = original;
return result;
};
} else {
constructor = members.constructor;
isProperty = function (property) {
var parent = (this.constructor || constructor).prototype;
return property in this && !(property in parent && this[property] === parent[property]);
};
}
members = null;
return isProperty.call(this, property);
};
}
forEach = function (object, callback) {
var size = 0, Properties, members, property;
(Properties = function () {
this.valueOf = 0;
}).prototype.valueOf = 0;
members = new Properties();
for (property in members) {
if (isProperty.call(members, property)) {
size++;
}
}
Properties = members = null;
if (!size) {
members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
forEach = function (object, callback) {
var isFunction = getClass.call(object) == functionClass, property, length;
var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
for (property in object) {
if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
callback(property);
}
}
for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
};
} else if (size == 2) {
forEach = function (object, callback) {
var members = {}, isFunction = getClass.call(object) == functionClass, property;
for (property in object) {
if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
callback(property);
}
}
};
} else {
forEach = function (object, callback) {
var isFunction = getClass.call(object) == functionClass, property, isConstructor;
for (property in object) {
if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
callback(property);
}
}
if (isConstructor || isProperty.call(object, (property = "constructor"))) {
callback(property);
}
};
}
return forEach(object, callback);
};
if (!has("json-stringify")) {
var Escapes = {
92: "\\\\",
34: '\\"',
8: "\\b",
12: "\\f",
10: "\\n",
13: "\\r",
9: "\\t"
};
var leadingZeroes = "000000";
var toPaddedString = function (width, value) {
return (leadingZeroes + (value || 0)).slice(-width);
};
var unicodePrefix = "\\u00";
var quote = function (value) {
var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
for (; index < length; index++) {
var charCode = value.charCodeAt(index);
switch (charCode) {
case 8: case 9: case 10: case 12: case 13: case 34: case 92:
result += Escapes[charCode];
break;
default:
if (charCode < 32) {
result += unicodePrefix + toPaddedString(2, charCode.toString(16));
break;
}
result += useCharIndex ? symbols[index] : value.charAt(index);
}
}
return result + '"';
};
var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
try {
value = object[property];
} catch (exception) {}
if (typeof value == "object" && value) {
className = getClass.call(value);
if (className == dateClass && !isProperty.call(value, "toJSON")) {
if (value > -1 / 0 && value < 1 / 0) {
if (getDay) {
date = floor(value / 864e5);
for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
date = 1 + date - getDay(year, month);
time = (value % 864e5 + 864e5) % 864e5;
hours = floor(time / 36e5) % 24;
minutes = floor(time / 6e4) % 60;
seconds = floor(time / 1e3) % 60;
milliseconds = time % 1e3;
} else {
year = value.getUTCFullYear();
month = value.getUTCMonth();
date = value.getUTCDate();
hours = value.getUTCHours();
minutes = value.getUTCMinutes();
seconds = value.getUTCSeconds();
milliseconds = value.getUTCMilliseconds();
}
value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
"-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
"T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
"." + toPaddedString(3, milliseconds) + "Z";
} else {
value = null;
}
} else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
value = value.toJSON(property);
}
}
if (callback) {
value = callback.call(object, property, value);
}
if (value === null) {
return "null";
}
className = getClass.call(value);
if (className == booleanClass) {
return "" + value;
} else if (className == numberClass) {
return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
} else if (className == stringClass) {
return quote("" + value);
}
if (typeof value == "object") {
for (length = stack.length; length--;) {
if (stack[length] === value) {
throw TypeError();
}
}
stack.push(value);
results = [];
prefix = indentation;
indentation += whitespace;
if (className == arrayClass) {
for (index = 0, length = value.length; index < length; index++) {
element = serialize(index, value, callback, properties, whitespace, indentation, stack);
results.push(element === undef ? "null" : element);
}
result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
} else {
forEach(properties || value, function (property) {
var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
if (element !== undef) {
results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
}
});
result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
}
stack.pop();
return result;
}
};
exports.stringify = function (source, filter, width) {
var whitespace, callback, properties, className;
if (objectTypes[typeof filter] && filter) {
if ((className = getClass.call(filter)) == functionClass) {
callback = filter;
} else if (className == arrayClass) {
properties = {};
for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
}
}
if (width) {
if ((className = getClass.call(width)) == numberClass) {
if ((width -= width % 1) > 0) {
for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
}
} else if (className == stringClass) {
whitespace = width.length <= 10 ? width : width.slice(0, 10);
}
}
return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
};
}
if (!has("json-parse")) {
var fromCharCode = String.fromCharCode;
var Unescapes = {
92: "\\",
34: '"',
47: "/",
98: "\b",
116: "\t",
110: "\n",
102: "\f",
114: "\r"
};
var Index, Source;
var abort = function () {
Index = Source = null;
throw SyntaxError();
};
var lex = function () {
var source = Source, length = source.length, value, begin, position, isSigned, charCode;
while (Index < length) {
charCode = source.charCodeAt(Index);
switch (charCode) {
case 9: case 10: case 13: case 32:
Index++;
break;
case 123: case 125: case 91: case 93: case 58: case 44:
value = charIndexBuggy ? source.charAt(Index) : source[Index];
Index++;
return value;
case 34:
for (value = "@", Index++; Index < length;) {
charCode = source.charCodeAt(Index);
if (charCode < 32) {
abort();
} else if (charCode == 92) {
charCode = source.charCodeAt(++Index);
switch (charCode) {
case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
value += Unescapes[charCode];
Index++;
break;
case 117:
begin = ++Index;
for (position = Index + 4; Index < position; Index++) {
charCode = source.charCodeAt(Index);
if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
abort();
}
}
value += fromCharCode("0x" + source.slice(begin, Index));
break;
default:
abort();
}
} else {
if (charCode == 34) {
break;
}
charCode = source.charCodeAt(Index);
begin = Index;
while (charCode >= 32 && charCode != 92 && charCode != 34) {
charCode = source.charCodeAt(++Index);
}
value += source.slice(begin, Index);
}
}
if (source.charCodeAt(Index) == 34) {
Index++;
return value;
}
abort();
default:
begin = Index;
if (charCode == 45) {
isSigned = true;
charCode = source.charCodeAt(++Index);
}
if (charCode >= 48 && charCode <= 57) {
if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
abort();
}
isSigned = false;
for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
if (source.charCodeAt(Index) == 46) {
position = ++Index;
for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
if (position == Index) {
abort();
}
Index = position;
}
charCode = source.charCodeAt(Index);
if (charCode == 101 || charCode == 69) {
charCode = source.charCodeAt(++Index);
if (charCode == 43 || charCode == 45) {
Index++;
}
for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
if (position == Index) {
abort();
}
Index = position;
}
return +source.slice(begin, Index);
}
if (isSigned) {
abort();
}
if (source.slice(Index, Index + 4) == "true") {
Index += 4;
return true;
} else if (source.slice(Index, Index + 5) == "false") {
Index += 5;
return false;
} else if (source.slice(Index, Index + 4) == "null") {
Index += 4;
return null;
}
abort();
}
}
return "$";
};
var get = function (value) {
var results, hasMembers;
if (value == "$") {
abort();
}
if (typeof value == "string") {
if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
return value.slice(1);
}
if (value == "[") {
results = [];
for (;; hasMembers || (hasMembers = true)) {
value = lex();
if (value == "]") {
break;
}
if (hasMembers) {
if (value == ",") {
value = lex();
if (value == "]") {
abort();
}
} else {
abort();
}
}
if (value == ",") {
abort();
}
results.push(get(value));
}
return results;
} else if (value == "{") {
results = {};
for (;; hasMembers || (hasMembers = true)) {
value = lex();
if (value == "}") {
break;
}
if (hasMembers) {
if (value == ",") {
value = lex();
if (value == "}") {
abort();
}
} else {
abort();
}
}
if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
abort();
}
results[value.slice(1)] = get(lex());
}
return results;
}
abort();
}
return value;
};
var update = function (source, property, callback) {
var element = walk(source, property, callback);
if (element === undef) {
delete source[property];
} else {
source[property] = element;
}
};
var walk = function (source, property, callback) {
var value = source[property], length;
if (typeof value == "object" && value) {
if (getClass.call(value) == arrayClass) {
for (length = value.length; length--;) {
update(value, length, callback);
}
} else {
forEach(value, function (property) {
update(value, property, callback);
});
}
}
return callback.call(source, property, value);
};
exports.parse = function (source, callback) {
var result, value;
Index = 0;
Source = "" + source;
result = get(lex());
if (lex() != "$") {
abort();
}
Index = Source = null;
return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
};
}
}
exports["runInContext"] = runInContext;
return exports;
}
if (freeExports && !isLoader) {
runInContext(root, freeExports);
} else {
var nativeJSON = root.JSON,
previousJSON = root["JSON3"],
isRestored = false;
var JSON3 = runInContext(root, (root["JSON3"] = {
"noConflict": function () {
if (!isRestored) {
isRestored = true;
root.JSON = nativeJSON;
root["JSON3"] = previousJSON;
nativeJSON = previousJSON = null;
}
return JSON3;
}
}));
root.JSON = {
"parse": JSON3.parse,
"stringify": JSON3.stringify
};
}
if (false) {
(function(){
return JSON3;
});
}
}).call(this);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],4:[function(require,module,exports){
/**
* Reduce `arr` with `fn`.
*
* @param {Array} arr
* @param {Function} fn
* @param {Mixed} initial
*
* TODO: combatible error handling?
*/
module.exports = function(arr, fn, initial){
var idx = 0;
var len = arr.length;
var curr = arguments.length == 3
? initial
: arr[idx++];
while (idx < len) {
curr = fn.call(null, curr, arr[idx], ++idx, arr);
}
return curr;
};
},{}],5:[function(require,module,exports){
/**
* Copyright (c) 2011-2014 Felix Gnass
* Licensed under the MIT license
* http://spin.js.org/
*
* Example:
var opts = {
lines: 12
, length: 7
, width: 5
, radius: 10
, scale: 1.0
, corners: 1
, color: '#000'
, opacity: 1/4
, rotate: 0
, direction: 1
, speed: 1
, trail: 100
, fps: 20
, zIndex: 2e9
, className: 'spinner'
, top: '50%'
, left: '50%'
, shadow: false
, hwaccel: false
, position: 'absolute'
}
var target = document.getElementById('foo')
var spinner = new Spinner(opts).spin(target)
*/
;(function (root, factory) {
/* CommonJS */
if (typeof module == 'object' && module.exports) module.exports = factory()
/* AMD module */
else if (typeof define == 'function' && define.amd) {}
/* Browser global */
else root.Spinner = factory()
}(this, function () {
"use strict"
var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */
, animations = {} /* Animation rules keyed by their name */
, useCssAnimations /* Whether to use CSS animations or setTimeout */
, sheet /* A stylesheet to hold the @keyframe or VML rules. */
/**
* Utility function to create elements. If no tag name is given,
* a DIV is created. Optionally properties can be passed.
*/
function createEl (tag, prop) {
var el = document.createElement(tag || 'div')
, n
for (n in prop) el[n] = prop[n]
return el
}
/**
* Appends children and returns the parent.
*/
function ins (parent /* child1, child2, ...*/) {
for (var i = 1, n = arguments.length; i < n; i++) {
parent.appendChild(arguments[i])
}
return parent
}
/**
* Creates an opacity keyframe animation rule and returns its name.
* Since most mobile Webkits have timing issues with animation-delay,
* we create separate rules for each line/segment.
*/
function addAnimation (alpha, trail, i, lines) {
var name = ['opacity', trail, ~~(alpha * 100), i, lines].join('-')
, start = 0.01 + i/lines * 100
, z = Math.max(1 - (1-alpha) / trail * (100-start), alpha)
, prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase()
, pre = prefix && '-' + prefix + '-' || ''
if (!animations[name]) {
sheet.insertRule(
'@' + pre + 'keyframes ' + name + '{' +
'0%{opacity:' + z + '}' +
start + '%{opacity:' + alpha + '}' +
(start+0.01) + '%{opacity:1}' +
(start+trail) % 100 + '%{opacity:' + alpha + '}' +
'100%{opacity:' + z + '}' +
'}', sheet.cssRules.length)
animations[name] = 1
}
return name
}
/**
* Tries various vendor prefixes and returns the first supported property.
*/
function vendor (el, prop) {
var s = el.style
, pp
, i
prop = prop.charAt(0).toUpperCase() + prop.slice(1)
if (s[prop] !== undefined) return prop
for (i = 0; i < prefixes.length; i++) {
pp = prefixes[i]+prop
if (s[pp] !== undefined) return pp
}
}
/**
* Sets multiple style properties at once.
*/
function css (el, prop) {
for (var n in prop) {
el.style[vendor(el, n) || n] = prop[n]
}
return el
}
/**
* Fills in default values.
*/
function merge (obj) {
for (var i = 1; i < arguments.length; i++) {
var def = arguments[i]
for (var n in def) {
if (obj[n] === undefined) obj[n] = def[n]
}
}
return obj
}
/**
* Returns the line color from the given string or array.
*/
function getColor (color, idx) {
return typeof color == 'string' ? color : color[idx % color.length]
}
var defaults = {
lines: 12
, length: 7
, width: 5
, radius: 10
, scale: 1.0
, corners: 1
, color: '#000'
, opacity: 1/4
, rotate: 0
, direction: 1
, speed: 1
, trail: 100
, fps: 20
, zIndex: 2e9
, className: 'spinner'
, top: '50%'
, left: '50%'
, shadow: false
, hwaccel: false
, position: 'absolute'
}
/** The constructor */
function Spinner (o) {
this.opts = merge(o || {}, Spinner.defaults, defaults)
}
Spinner.defaults = {}
merge(Spinner.prototype, {
/**
* Adds the spinner to the given target element. If this instance is already
* spinning, it is automatically removed from its previous target b calling
* stop() internally.
*/
spin: function (target) {
this.stop()
var self = this
, o = self.opts
, el = self.el = createEl(null, {className: o.className})
css(el, {
position: o.position
, width: 0
, zIndex: o.zIndex
, left: o.left
, top: o.top
})
if (target) {
target.insertBefore(el, target.firstChild || null)
}
el.setAttribute('role', 'progressbar')
self.lines(el, self.opts)
if (!useCssAnimations) {
var i = 0
, start = (o.lines - 1) * (1 - o.direction) / 2
, alpha
, fps = o.fps
, f = fps / o.speed
, ostep = (1 - o.opacity) / (f * o.trail / 100)
, astep = f / o.lines
;(function anim () {
i++
for (var j = 0; j < o.lines; j++) {
alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity)
self.opacity(el, j * o.direction + start, alpha, o)
}
self.timeout = self.el && setTimeout(anim, ~~(1000 / fps))
})()
}
return self
}
/**
* Stops and removes the Spinner.
*/
, stop: function () {
var el = this.el
if (el) {
clearTimeout(this.timeout)
if (el.parentNode) el.parentNode.removeChild(el)
this.el = undefined
}
return this
}
/**
* Internal method that draws the individual lines. Will be overwritten
* in VML fallback mode below.
*/
, lines: function (el, o) {
var i = 0
, start = (o.lines - 1) * (1 - o.direction) / 2
, seg
function fill (color, shadow) {
return css(createEl(), {
position: 'absolute'
, width: o.scale * (o.length + o.width) + 'px'
, height: o.scale * o.width + 'px'
, background: color
, boxShadow: shadow
, transformOrigin: 'left'
, transform: 'rotate(' + ~~(360/o.lines*i + o.rotate) + 'deg) translate(' + o.scale*o.radius + 'px' + ',0)'
, borderRadius: (o.corners * o.scale * o.width >> 1) + 'px'
})
}
for (; i < o.lines; i++) {
seg = css(createEl(), {
position: 'absolute'
, top: 1 + ~(o.scale * o.width / 2) + 'px'
, transform: o.hwaccel ? 'translate3d(0,0,0)' : ''
, opacity: o.opacity
, animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1 / o.speed + 's linear infinite'
})
if (o.shadow) ins(seg, css(fill('#000', '0 0 4px #000'), {top: '2px'}))
ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)')))
}
return el
}
/**
* Internal method that adjusts the opacity of a single line.
* Will be overwritten in VML fallback mode below.
*/
, opacity: function (el, i, val) {
if (i < el.childNodes.length) el.childNodes[i].style.opacity = val
}
})
function initVML () {
/* Utility function to create a VML tag */
function vml (tag, attr) {
return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr)
}
sheet.addRule('.spin-vml', 'behavior:url(#default#VML)')
Spinner.prototype.lines = function (el, o) {
var r = o.scale * (o.length + o.width)
, s = o.scale * 2 * r
function grp () {
return css(
vml('group', {
coordsize: s + ' ' + s
, coordorigin: -r + ' ' + -r
})
, { width: s, height: s }
)
}
var margin = -(o.width + o.length) * o.scale * 2 + 'px'
, g = css(grp(), {position: 'absolute', top: margin, left: margin})
, i
function seg (i, dx, filter) {
ins(
g
, ins(
css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx})
, ins(
css(
vml('roundrect', {arcsize: o.corners})
, { width: r
, height: o.scale * o.width
, left: o.scale * o.radius
, top: -o.scale * o.width >> 1
, filter: filter
}
)
, vml('fill', {color: getColor(o.color, i), opacity: o.opacity})
, vml('stroke', {opacity: 0})
)
)
)
}
if (o.shadow)
for (i = 1; i <= o.lines; i++) {
seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)')
}
for (i = 1; i <= o.lines; i++) seg(i)
return ins(el, g)
}
Spinner.prototype.opacity = function (el, i, val, o) {
var c = el.firstChild
o = o.shadow && o.lines || 0
if (c && i + o < c.childNodes.length) {
c = c.childNodes[i + o]; c = c && c.firstChild; c = c && c.firstChild
if (c) c.opacity = val
}
}
}
if (typeof document !== 'undefined') {
sheet = (function () {
var el = createEl('style', {type : 'text/css'})
ins(document.getElementsByTagName('head')[0], el)
return el.sheet || el.styleSheet
}())
var probe = css(createEl('group'), {behavior: 'url(#default#VML)'})
if (!vendor(probe, 'transform') && probe.adj) initVML()
else useCssAnimations = vendor(probe, 'animation')
}
return Spinner
}));
},{}],6:[function(require,module,exports){
/**
* Module dependencies.
*/
var Emitter = require('emitter');
var reduce = require('reduce');
var requestBase = require('./request-base');
var isObject = require('./is-object');
/**
* Root reference for iframes.
*/
var root;
if (typeof window !== 'undefined') {
root = window;
} else if (typeof self !== 'undefined') {
root = self;
} else {
root = this;
}
/**
* Noop.
*/
function noop(){};
/**
* Check if `obj` is a host object,
* we don't want to serialize these :)
*
* TODO: future proof, move to compoent land
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isHost(obj) {
var str = {}.toString.call(obj);
switch (str) {
case '[object File]':
case '[object Blob]':
case '[object FormData]':
return true;
default:
return false;
}
}
/**
* Expose `request`.
*/
var request = module.exports = require('./request').bind(null, Request);
/**
* Determine XHR.
*/
request.getXHR = function () {
if (root.XMLHttpRequest
&& (!root.location || 'file:' != root.location.protocol
|| !root.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
}
return false;
};
/**
* Removes leading and trailing whitespace, added to support IE.
*
* @param {String} s
* @return {String}
* @api private
*/
var trim = ''.trim
? function(s) { return s.trim(); }
: function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
/**
* Serialize the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
function serialize(obj) {
if (!isObject(obj)) return obj;
var pairs = [];
for (var key in obj) {
if (null != obj[key]) {
pushEncodedKeyValuePair(pairs, key, obj[key]);
}
}
return pairs.join('&');
}
/**
* Helps 'serialize' with serializing arrays.
* Mutates the pairs array.
*
* @param {Array} pairs
* @param {String} key
* @param {Mixed} val
*/
function pushEncodedKeyValuePair(pairs, key, val) {
if (Array.isArray(val)) {
return val.forEach(function(v) {
pushEncodedKeyValuePair(pairs, key, v);
});
}
pairs.push(encodeURIComponent(key)
+ '=' + encodeURIComponent(val));
}
/**
* Expose serialization method.
*/
request.serializeObject = serialize;
/**
* Parse the given x-www-form-urlencoded `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseString(str) {
var obj = {};
var pairs = str.split('&');
var parts;
var pair;
for (var i = 0, len = pairs.length; i < len; ++i) {
pair = pairs[i];
parts = pair.split('=');
obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
return obj;
}
/**
* Expose parser.
*/
request.parseString = parseString;
/**
* Default MIME type map.
*
* superagent.types.xml = 'application/xml';
*
*/
request.types = {
html: 'text/html',
json: 'application/json',
xml: 'application/xml',
urlencoded: 'application/x-www-form-urlencoded',
'form': 'application/x-www-form-urlencoded',
'form-data': 'application/x-www-form-urlencoded'
};
/**
* Default serialization map.
*
* superagent.serialize['application/xml'] = function(obj){
* return 'generated xml here';
* };
*
*/
request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify
};
/**
* Default parsers.
*
* superagent.parse['application/xml'] = function(str){
* return { object parsed from str };
* };
*
*/
request.parse = {
'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
};
/**
* Parse the given header `str` into
* an object containing the mapped fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseHeader(str) {
var lines = str.split(/\r?\n/);
var fields = {};
var index;
var line;
var field;
var val;
lines.pop();
for (var i = 0, len = lines.length; i < len; ++i) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
return fields;
}
/**
* Check if `mime` is json or has +json structured syntax suffix.
*
* @param {String} mime
* @return {Boolean}
* @api private
*/
function isJSON(mime) {
return /[\/+]json\b/.test(mime);
}
/**
* Return the mime type for the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
function type(str){
return str.split(/ *; */).shift();
};
/**
* Return header field parameters.
*
* @param {String} str
* @return {Object}
* @api private
*/
function params(str){
return reduce(str.split(/ *; */), function(obj, str){
var parts = str.split(/ *= */)
, key = parts.shift()
, val = parts.shift();
if (key && val) obj[key] = val;
return obj;
}, {});
};
/**
* Initialize a new `Response` with the given `xhr`.
*
* - set flags (.ok, .error, etc)
* - parse header
*
* Examples:
*
* Aliasing `superagent` as `request` is nice:
*
* request = superagent;
*
* We can use the promise-like API, or pass callbacks:
*
* request.get('/').end(function(res){});
* request.get('/', function(res){});
*
* Sending data can be chained:
*
* request
* .post('/user')
* .send({ name: 'tj' })
* .end(function(res){});
*
* Or passed to `.send()`:
*
* request
* .post('/user')
* .send({ name: 'tj' }, function(res){});
*
* Or passed to `.post()`:
*
* request
* .post('/user', { name: 'tj' })
* .end(function(res){});
*
* Or further reduced to a single call for simple cases:
*
* request
* .post('/user', { name: 'tj' }, function(res){});
*
* @param {XMLHTTPRequest} xhr
* @param {Object} options
* @api private
*/
function Response(req, options) {
options = options || {};
this.req = req;
this.xhr = this.req.xhr;
this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')
? this.xhr.responseText
: null;
this.statusText = this.req.xhr.statusText;
this.setStatusProperties(this.xhr.status);
this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
this.header['content-type'] = this.xhr.getResponseHeader('content-type');
this.setHeaderProperties(this.header);
this.body = this.req.method != 'HEAD'
? this.parseBody(this.text ? this.text : this.xhr.response)
: null;
}
/**
* Get case-insensitive `field` value.
*
* @param {String} field
* @return {String}
* @api public
*/
Response.prototype.get = function(field){
return this.header[field.toLowerCase()];
};
/**
* Set header related properties:
*
* - `.type` the content type without params
*
* A response of "Content-Type: text/plain; charset=utf-8"
* will provide you with a `.type` of "text/plain".
*
* @param {Object} header
* @api private
*/
Response.prototype.setHeaderProperties = function(header){
var ct = this.header['content-type'] || '';
this.type = type(ct);
var obj = params(ct);
for (var key in obj) this[key] = obj[key];
};
/**
* Parse the given body `str`.
*
* Used for auto-parsing of bodies. Parsers
* are defined on the `superagent.parse` object.
*
* @param {String} str
* @return {Mixed}
* @api private
*/
Response.prototype.parseBody = function(str){
var parse = request.parse[this.type];
if (!parse && isJSON(this.type)) {
parse = request.parse['application/json'];
}
return parse && str && (str.length || str instanceof Object)
? parse(str)
: null;
};
/**
* Set flags such as `.ok` based on `status`.
*
* For example a 2xx response will give you a `.ok` of __true__
* whereas 5xx will be __false__ and `.error` will be __true__. The
* `.clientError` and `.serverError` are also available to be more
* specific, and `.statusType` is the class of error ranging from 1..5
* sometimes useful for mapping respond colors etc.
*
* "sugar" properties are also defined for common cases. Currently providing:
*
* - .noContent
* - .badRequest
* - .unauthorized
* - .notAcceptable
* - .notFound
*
* @param {Number} status
* @api private
*/
Response.prototype.setStatusProperties = function(status){
if (status === 1223) {
status = 204;
}
var type = status / 100 | 0;
this.status = this.statusCode = status;
this.statusType = type;
this.info = 1 == type;
this.ok = 2 == type;
this.clientError = 4 == type;
this.serverError = 5 == type;
this.error = (4 == type || 5 == type)
? this.toError()
: false;
this.accepted = 202 == status;
this.noContent = 204 == status;
this.badRequest = 400 == status;
this.unauthorized = 401 == status;
this.notAcceptable = 406 == status;
this.notFound = 404 == status;
this.forbidden = 403 == status;
};
/**
* Return an `Error` representative of this response.
*
* @return {Error}
* @api public
*/
Response.prototype.toError = function(){
var req = this.req;
var method = req.method;
var url = req.url;
var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
var err = new Error(msg);
err.status = this.status;
err.method = method;
err.url = url;
return err;
};
/**
* Expose `Response`.
*/
request.Response = Response;
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {String} method
* @param {String} url
* @api public
*/
function Request(method, url) {
var self = this;
this._query = this._query || [];
this.method = method;
this.url = url;
this.header = {};
this._header = {};
this.on('end', function(){
var err = null;
var res = null;
try {
res = new Response(self);
} catch(e) {
err = new Error('Parser is unable to parse the response');
err.parse = true;
err.original = e;
err.rawResponse = self.xhr && self.xhr.responseText ? self.xhr.responseText : null;
err.statusCode = self.xhr && self.xhr.status ? self.xhr.status : null;
return self.callback(err);
}
self.emit('response', res);
if (err) {
return self.callback(err, res);
}
if (res.status >= 200 && res.status < 300) {
return self.callback(err, res);
}
var new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
new_err.original = err;
new_err.response = res;
new_err.status = res.status;
self.callback(new_err, res);
});
}
/**
* Mixin `Emitter` and `requestBase`.
*/
Emitter(Request.prototype);
for (var key in requestBase) {
Request.prototype[key] = requestBase[key];
}
/**
* Abort the request, and clear potential timeout.
*
* @return {Request}
* @api public
*/
Request.prototype.abort = function(){
if (this.aborted) return;
this.aborted = true;
this.xhr.abort();
this.clearTimeout();
this.emit('abort');
return this;
};
/**
* Set Content-Type to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.xml = 'application/xml';
*
* request.post('/')
* .type('xml')
* .send(xmlstring)
* .end(callback);
*
* request.post('/')
* .type('application/xml')
* .send(xmlstring)
* .end(callback);
*
* @param {String} type
* @return {Request} for chaining
* @api public
*/
Request.prototype.type = function(type){
this.set('Content-Type', request.types[type] || type);
return this;
};
/**
* Set responseType to `val`. Presently valid responseTypes are 'blob' and
* 'arraybuffer'.
*
* Examples:
*
* req.get('/')
* .responseType('blob')
* .end(callback);
*
* @param {String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.responseType = function(val){
this._responseType = val;
return this;
};
/**
* Set Accept to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.json = 'application/json';
*
* request.get('/agent')
* .accept('json')
* .end(callback);
*
* request.get('/agent')
* .accept('application/json')
* .end(callback);
*
* @param {String} accept
* @return {Request} for chaining
* @api public
*/
Request.prototype.accept = function(type){
this.set('Accept', request.types[type] || type);
return this;
};
/**
* Set Authorization field value with `user` and `pass`.
*
* @param {String} user
* @param {String} pass
* @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic')
* @return {Request} for chaining
* @api public
*/
Request.prototype.auth = function(user, pass, options){
if (!options) {
options = {
type: 'basic'
}
}
switch (options.type) {
case 'basic':
var str = btoa(user + ':' + pass);
this.set('Authorization', 'Basic ' + str);
break;
case 'auto':
this.username = user;
this.password = pass;
break;
}
return this;
};
/**
* Add query-string `val`.
*
* Examples:
*
* request.get('/shoes')
* .query('size=10')
* .query({ color: 'blue' })
*
* @param {Object|String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.query = function(val){
if ('string' != typeof val) val = serialize(val);
if (val) this._query.push(val);
return this;
};
/**
* Queue the given `file` as an attachment to the specified `field`,
* with optional `filename`.
*
* ``` js
* request.post('/upload')
* .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
* .end(callback);
* ```
*
* @param {String} field
* @param {Blob|File} file
* @param {String} filename
* @return {Request} for chaining
* @api public
*/
Request.prototype.attach = function(field, file, filename){
this._getFormData().append(field, file, filename || file.name);
return this;
};
Request.prototype._getFormData = function(){
if (!this._formData) {
this._formData = new root.FormData();
}
return this._formData;
};
/**
* Send `data` as the request body, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
*
* request.post('/user')
* .type('json')
* .send('{"name":"tj"}')
* .end(callback)
*
*
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
*
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
*
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
*
* request.post('/user')
* .send('name=tobi')
* .send('species=ferret')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
Request.prototype.send = function(data){
var obj = isObject(data);
var type = this._header['content-type'];
if (obj && isObject(this._data)) {
for (var key in data) {
this._data[key] = data[key];
}
} else if ('string' == typeof data) {
if (!type) this.type('form');
type = this._header['content-type'];
if ('application/x-www-form-urlencoded' == type) {
this._data = this._data
? this._data + '&' + data
: data;
} else {
this._data = (this._data || '') + data;
}
} else {
this._data = data;
}
if (!obj || isHost(data)) return this;
if (!type) this.type('json');
return this;
};
/**
* @deprecated
*/
Response.prototype.parse = function serialize(fn){
if (root.console) {
console.warn("Client-side parse() method has been renamed to serialize(). This method is not compatible with superagent v2.0");
}
this.serialize(fn);
return this;
};
Response.prototype.serialize = function serialize(fn){
this._parser = fn;
return this;
};
/**
* Invoke the callback with `err` and `res`
* and handle arity check.
*
* @param {Error} err
* @param {Response} res
* @api private
*/
Request.prototype.callback = function(err, res){
var fn = this._callback;
this.clearTimeout();
fn(err, res);
};
/**
* Invoke callback with x-domain error.
*
* @api private
*/
Request.prototype.crossDomainError = function(){
var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');
err.crossDomain = true;
err.status = this.status;
err.method = this.method;
err.url = this.url;
this.callback(err);
};
/**
* Invoke callback with timeout error.
*
* @api private
*/
Request.prototype.timeoutError = function(){
var timeout = this._timeout;
var err = new Error('timeout of ' + timeout + 'ms exceeded');
err.timeout = timeout;
this.callback(err);
};
/**
* Enable transmission of cookies with x-domain requests.
*
* Note that for this to work the origin must not be
* using "Access-Control-Allow-Origin" with a wildcard,
* and also must set "Access-Control-Allow-Credentials"
* to "true".
*
* @api public
*/
Request.prototype.withCredentials = function(){
this._withCredentials = true;
return this;
};
/**
* Initiate request, invoking callback `fn(res)`
* with an instanceof `Response`.
*
* @param {Function} fn
* @return {Request} for chaining
* @api public
*/
Request.prototype.end = function(fn){
var self = this;
var xhr = this.xhr = request.getXHR();
var query = this._query.join('&');
var timeout = this._timeout;
var data = this._formData || this._data;
this._callback = fn || noop;
xhr.onreadystatechange = function(){
if (4 != xhr.readyState) return;
var status;
try { status = xhr.status } catch(e) { status = 0; }
if (0 == status) {
if (self.timedout) return self.timeoutError();
if (self.aborted) return;
return self.crossDomainError();
}
self.emit('end');
};
var handleProgress = function(e){
if (e.total > 0) {
e.percent = e.loaded / e.total * 100;
}
e.direction = 'download';
self.emit('progress', e);
};
if (this.hasListeners('progress')) {
xhr.onprogress = handleProgress;
}
try {
if (xhr.upload && this.hasListeners('progress')) {
xhr.upload.onprogress = handleProgress;
}
} catch(e) {
}
if (timeout && !this._timer) {
this._timer = setTimeout(function(){
self.timedout = true;
self.abort();
}, timeout);
}
if (query) {
query = request.serializeObject(query);
this.url += ~this.url.indexOf('?')
? '&' + query
: '?' + query;
}
if (this.username && this.password) {
xhr.open(this.method, this.url, true, this.username, this.password);
} else {
xhr.open(this.method, this.url, true);
}
if (this._withCredentials) xhr.withCredentials = true;
if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
var contentType = this._header['content-type'];
var serialize = this._parser || request.serialize[contentType ? contentType.split(';')[0] : ''];
if (!serialize && isJSON(contentType)) serialize = request.serialize['application/json'];
if (serialize) data = serialize(data);
}
for (var field in this.header) {
if (null == this.header[field]) continue;
xhr.setRequestHeader(field, this.header[field]);
}
if (this._responseType) {
xhr.responseType = this._responseType;
}
this.emit('request', this);
xhr.send(typeof data !== 'undefined' ? data : null);
return this;
};
/**
* Expose `Request`.
*/
request.Request = Request;
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.get = function(url, data, fn){
var req = request('GET', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.query(data);
if (fn) req.end(fn);
return req;
};
/**
* HEAD `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.head = function(url, data, fn){
var req = request('HEAD', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* DELETE `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Function} fn
* @return {Request}
* @api public
*/
function del(url, fn){
var req = request('DELETE', url);
if (fn) req.end(fn);
return req;
};
request['del'] = del;
request['delete'] = del;
/**
* PATCH `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.patch = function(url, data, fn){
var req = request('PATCH', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* POST `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.post = function(url, data, fn){
var req = request('POST', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* PUT `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.put = function(url, data, fn){
var req = request('PUT', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
},{"./is-object":7,"./request":9,"./request-base":8,"emitter":1,"reduce":4}],7:[function(require,module,exports){
/**
* Check if `obj` is an object.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isObject(obj) {
return null != obj && 'object' == typeof obj;
}
module.exports = isObject;
},{}],8:[function(require,module,exports){
/**
* Module of mixed-in functions shared between node and client code
*/
var isObject = require('./is-object');
/**
* Clear previous timeout.
*
* @return {Request} for chaining
* @api public
*/
exports.clearTimeout = function _clearTimeout(){
this._timeout = 0;
clearTimeout(this._timer);
return this;
};
/**
* Force given parser
*
* Sets the body parser no matter type.
*
* @param {Function}
* @api public
*/
exports.parse = function parse(fn){
this._parser = fn;
return this;
};
/**
* Set timeout to `ms`.
*
* @param {Number} ms
* @return {Request} for chaining
* @api public
*/
exports.timeout = function timeout(ms){
this._timeout = ms;
return this;
};
/**
* Faux promise support
*
* @param {Function} fulfill
* @param {Function} reject
* @return {Request}
*/
exports.then = function then(fulfill, reject) {
return this.end(function(err, res) {
err ? reject(err) : fulfill(res);
});
}
/**
* Allow for extension
*/
exports.use = function use(fn) {
fn(this);
return this;
}
/**
* Get request header `field`.
* Case-insensitive.
*
* @param {String} field
* @return {String}
* @api public
*/
exports.get = function(field){
return this._header[field.toLowerCase()];
};
/**
* Get case-insensitive header `field` value.
* This is a deprecated internal API. Use `.get(field)` instead.
*
* (getHeader is no longer used internally by the superagent code base)
*
* @param {String} field
* @return {String}
* @api private
* @deprecated
*/
exports.getHeader = exports.get;
/**
* Set header `field` to `val`, or multiple fields with one object.
* Case-insensitive.
*
* Examples:
*
* req.get('/')
* .set('Accept', 'application/json')
* .set('X-API-Key', 'foobar')
* .end(callback);
*
* req.get('/')
* .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
* .end(callback);
*
* @param {String|Object} field
* @param {String} val
* @return {Request} for chaining
* @api public
*/
exports.set = function(field, val){
if (isObject(field)) {
for (var key in field) {
this.set(key, field[key]);
}
return this;
}
this._header[field.toLowerCase()] = val;
this.header[field] = val;
return this;
};
/**
* Remove header `field`.
* Case-insensitive.
*
* Example:
*
* req.get('/')
* .unset('User-Agent')
* .end(callback);
*
* @param {String} field
*/
exports.unset = function(field){
delete this._header[field.toLowerCase()];
delete this.header[field];
return this;
};
/**
* Write the field `name` and `val` for "multipart/form-data"
* request bodies.
*
* ``` js
* request.post('/upload')
* .field('foo', 'bar')
* .end(callback);
* ```
*
* @param {String} name
* @param {String|Blob|File|Buffer|fs.ReadStream} val
* @return {Request} for chaining
* @api public
*/
exports.field = function(name, val) {
this._getFormData().append(name, val);
return this;
};
},{"./is-object":7}],9:[function(require,module,exports){
/**
* Issue a request:
*
* Examples:
*
* request('GET', '/users').end(callback)
* request('/users').end(callback)
* request('/users', callback)
*
* @param {String} method
* @param {String|Function} url or callback
* @return {Request}
* @api public
*/
function request(RequestConstructor, method, url) {
if ('function' == typeof url) {
return new RequestConstructor('GET', method).end(url);
}
if (2 == arguments.length) {
return new RequestConstructor('GET', method);
}
return new RequestConstructor(method, url);
}
module.exports = request;
},{}],10:[function(require,module,exports){
var Keen = require("./index"),
each = require("./utils/each");
module.exports = function(){
var loaded = window['Keen'] || null,
cached = window['_' + 'Keen'] || null,
clients,
ready;
if (loaded && cached) {
clients = cached['clients'] || {},
ready = cached['ready'] || [];
each(clients, function(client, id){
each(Keen.prototype, function(method, key){
loaded.prototype[key] = method;
});
each(["Query", "Request", "Dataset", "Dataviz"], function(name){
loaded[name] = (Keen[name]) ? Keen[name] : function(){};
});
if (client._config) {
client.configure.call(client, client._config);
}
if (client._setGlobalProperties) {
each(client._setGlobalProperties, function(fn){
client.setGlobalProperties.apply(client, fn);
});
}
if (client._addEvent) {
each(client._addEvent, function(obj){
client.addEvent.apply(client, obj);
});
}
var callback = client._on || [];
if (client._on) {
each(client._on, function(obj){
client.on.apply(client, obj);
});
client.trigger('ready');
}
each(["_config", "_setGlobalProperties", "_addEvent", "_on"], function(name){
if (client[name]) {
client[name] = undefined;
try{
delete client[name];
} catch(e){}
}
});
});
each(ready, function(cb, i){
Keen.once("ready", cb);
});
}
window['_' + 'Keen'] = undefined;
try {
delete window['_' + 'Keen']
} catch(e) {}
};
},{"./index":18,"./utils/each":31}],11:[function(require,module,exports){
module.exports = function(){
return "undefined" == typeof window ? "server" : "browser";
};
},{}],12:[function(require,module,exports){
var each = require('../utils/each'),
json = require('../utils/json-shim');
module.exports = function(params){
var query = [];
each(params, function(value, key){
if ('string' !== typeof value) {
value = json.stringify(value);
}
query.push(key + '=' + encodeURIComponent(value));
});
return '?' + query.join('&');
};
},{"../utils/each":31,"../utils/json-shim":34}],13:[function(require,module,exports){
module.exports = function(){
return new Date().getTimezoneOffset() * -60;
};
},{}],14:[function(require,module,exports){
module.exports = function(){
if ("undefined" !== typeof window) {
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
return 2000;
}
}
return 16000;
};
},{}],15:[function(require,module,exports){
module.exports = function() {
var root = "undefined" == typeof window ? this : window;
if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
}
return false;
};
},{}],16:[function(require,module,exports){
module.exports = function(err, res, callback) {
var cb = callback || function() {};
if (res && !res.ok) {
var is_err = res.body && res.body.error_code;
err = new Error(is_err ? res.body.message : 'Unknown error occurred');
err.code = is_err ? res.body.error_code : 'UnknownError';
}
if (err) {
cb(err, null);
}
else {
cb(null, res.body);
}
return;
};
},{}],17:[function(require,module,exports){
var superagent = require('superagent');
var each = require('../utils/each'),
getXHR = require('./get-xhr-object');
module.exports = function(type, opts){
return function(request) {
var __super__ = request.constructor.prototype.end;
if ( typeof window === 'undefined' ) return;
request.requestType = request.requestType || {};
request.requestType['type'] = type;
request.requestType['options'] = request.requestType['options'] || {
async: true,
success: {
responseText: '{ "created": true }',
status: 201
},
error: {
responseText: '{ "error_code": "ERROR", "message": "Request failed" }',
status: 404
}
};
if (opts) {
if ( typeof opts.async === 'boolean' ) {
request.requestType['options'].async = opts.async;
}
if ( opts.success ) {
extend(request.requestType['options'].success, opts.success);
}
if ( opts.error ) {
extend(request.requestType['options'].error, opts.error);
}
}
request.end = function(fn){
var self = this,
reqType = (this.requestType) ? this.requestType['type'] : 'xhr',
query,
timeout;
if ( ('GET' !== self['method'] || reqType === 'xhr' ) && self.requestType['options'].async ) {
__super__.call(self, fn);
return;
}
query = self._query.join('&');
timeout = self._timeout;
self._callback = fn || noop;
if (timeout && !self._timer) {
self._timer = setTimeout(function(){
abortRequest.call(self);
}, timeout);
}
if (query) {
query = superagent.serializeObject(query);
self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query;
}
self.emit('request', self);
if ( !self.requestType['options'].async ) {
sendXhrSync.call(self);
}
else if ( reqType === 'jsonp' ) {
sendJsonp.call(self);
}
else if ( reqType === 'beacon' ) {
sendBeacon.call(self);
}
return self;
};
return request;
};
};
function sendXhrSync(){
var xhr = getXHR();
if (xhr) {
xhr.open('GET', this.url, false);
xhr.send(null);
}
return this;
}
function sendJsonp(){
var self = this,
timestamp = new Date().getTime(),
script = document.createElement('script'),
parent = document.getElementsByTagName('head')[0],
callbackName = 'keenJSONPCallback',
loaded = false;
callbackName += timestamp;
while (callbackName in window) {
callbackName += 'a';
}
window[callbackName] = function(response) {
if (loaded === true) return;
loaded = true;
handleSuccess.call(self, response);
cleanup();
};
script.src = self.url + '&jsonp=' + callbackName;
parent.appendChild(script);
script.onreadystatechange = function() {
if (loaded === false && self.readyState === 'loaded') {
loaded = true;
handleError.call(self);
cleanup();
}
};
script.onerror = function() {
if (loaded === false) {
loaded = true;
handleError.call(self);
cleanup();
}
};
function cleanup(){
window[callbackName] = undefined;
try {
delete window[callbackName];
} catch(e){}
parent.removeChild(script);
}
}
function sendBeacon(){
var self = this,
img = document.createElement('img'),
loaded = false;
img.onload = function() {
loaded = true;
if ('naturalHeight' in this) {
if (this.naturalHeight + this.naturalWidth === 0) {
this.onerror();
return;
}
} else if (this.width + this.height === 0) {
this.onerror();
return;
}
handleSuccess.call(self);
};
img.onerror = function() {
loaded = true;
handleError.call(self);
};
img.src = self.url + '&c=clv1';
}
function handleSuccess(res){
var opts = this.requestType['options']['success'],
response = '';
xhrShim.call(this, opts);
if (res) {
try {
response = JSON.stringify(res);
} catch(e) {}
}
else {
response = opts['responseText'];
}
this.xhr.responseText = response;
this.xhr.status = opts['status'];
this.emit('end');
}
function handleError(){
var opts = this.requestType['options']['error'];
xhrShim.call(this, opts);
this.xhr.responseText = opts['responseText'];
this.xhr.status = opts['status'];
this.emit('end');
}
function abortRequest(){
this.aborted = true;
this.clearTimeout();
this.emit('abort');
}
function xhrShim(opts){
this.xhr = {
getAllResponseHeaders: function(){ return ''; },
getResponseHeader: function(){ return 'application/json'; },
responseText: opts['responseText'],
status: opts['status']
};
return this;
}
},{"../utils/each":31,"./get-xhr-object":15,"superagent":6}],18:[function(require,module,exports){
var root = 'undefined' !== typeof window ? window : this;
var previous_Keen = root.Keen;
var Emitter = require('./utils/emitter-shim');
function Keen(config) {
this.configure(config || {});
Keen.trigger('client', this);
}
Keen.debug = false;
Keen.enabled = true;
Keen.loaded = true;
Keen.version = '3.4.1';
Emitter(Keen);
Emitter(Keen.prototype);
Keen.prototype.configure = function(cfg){
var config = cfg || {};
if (config['host']) {
config['host'].replace(/.*?:\/\//g, '');
}
if (config.protocol && config.protocol === 'auto') {
config['protocol'] = location.protocol.replace(/:/g, '');
}
this.config = {
projectId : config.projectId,
writeKey : config.writeKey,
readKey : config.readKey,
masterKey : config.masterKey,
requestType : config.requestType || 'jsonp',
host : config['host'] || 'api.keen.io/3.0',
protocol : config['protocol'] || 'https',
globalProperties: null
};
if (Keen.debug) {
this.on('error', Keen.log);
}
this.trigger('ready');
};
Keen.prototype.projectId = function(str){
if (!arguments.length) return this.config.projectId;
this.config.projectId = (str ? String(str) : null);
return this;
};
Keen.prototype.masterKey = function(str){
if (!arguments.length) return this.config.masterKey;
this.config.masterKey = (str ? String(str) : null);
return this;
};
Keen.prototype.readKey = function(str){
if (!arguments.length) return this.config.readKey;
this.config.readKey = (str ? String(str) : null);
return this;
};
Keen.prototype.writeKey = function(str){
if (!arguments.length) return this.config.writeKey;
this.config.writeKey = (str ? String(str) : null);
return this;
};
Keen.prototype.url = function(path){
if (!this.projectId()) {
this.trigger('error', 'Client is missing projectId property');
return;
}
return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path;
};
Keen.log = function(message) {
if (Keen.debug && typeof console == 'object') {
console.log('[Keen IO]', message);
}
};
Keen.noConflict = function(){
root.Keen = previous_Keen;
return Keen;
};
Keen.ready = function(fn){
if (Keen.loaded) {
fn();
} else {
Keen.once('ready', fn);
}
};
module.exports = Keen;
},{"./utils/emitter-shim":32}],19:[function(require,module,exports){
var json = require('../utils/json-shim');
var request = require('superagent');
var Keen = require('../index');
var base64 = require('../utils/base64'),
each = require('../utils/each'),
getContext = require('../helpers/get-context'),
getQueryString = require('../helpers/get-query-string'),
getUrlMaxLength = require('../helpers/get-url-max-length'),
getXHR = require('../helpers/get-xhr-object'),
requestTypes = require('../helpers/superagent-request-types'),
responseHandler = require('../helpers/superagent-handle-response');
module.exports = function(collection, payload, callback, async) {
var self = this,
urlBase = this.url('/events/' + encodeURIComponent(collection)),
reqType = this.config.requestType,
data = {},
cb = callback,
isAsync,
getUrl;
isAsync = ('boolean' === typeof async) ? async : true;
if (!Keen.enabled) {
handleValidationError.call(self, 'Keen.enabled = false');
return;
}
if (!self.projectId()) {
handleValidationError.call(self, 'Missing projectId property');
return;
}
if (!self.writeKey()) {
handleValidationError.call(self, 'Missing writeKey property');
return;
}
if (!collection || typeof collection !== 'string') {
handleValidationError.call(self, 'Collection name must be a string');
return;
}
if (self.config.globalProperties) {
data = self.config.globalProperties(collection);
}
each(payload, function(value, key){
data[key] = value;
});
if ( !getXHR() && 'xhr' === reqType ) {
reqType = 'jsonp';
}
if ( 'xhr' !== reqType || !isAsync ) {
getUrl = prepareGetRequest.call(self, urlBase, data);
}
if ( getUrl && getContext() === 'browser' ) {
request
.get(getUrl)
.use(requestTypes(reqType, { async: isAsync }))
.end(handleResponse);
}
else if ( getXHR() || getContext() === 'server' ) {
request
.post(urlBase)
.set('Content-Type', 'application/json')
.set('Authorization', self.writeKey())
.send(data)
.end(handleResponse);
}
else {
self.trigger('error', 'Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.');
}
function handleResponse(err, res){
responseHandler(err, res, cb);
cb = callback = null;
}
function handleValidationError(msg){
var err = 'Event not recorded: ' + msg;
self.trigger('error', err);
if (cb) {
cb.call(self, err, null);
cb = callback = null;
}
}
return;
};
function prepareGetRequest(url, data){
url += getQueryString({
api_key : this.writeKey(),
data : base64.encode( json.stringify(data) ),
modified : new Date().getTime()
});
return ( url.length < getUrlMaxLength() ) ? url : false;
}
},{"../helpers/get-context":11,"../helpers/get-query-string":12,"../helpers/get-url-max-length":14,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"../index":18,"../utils/base64":29,"../utils/each":31,"../utils/json-shim":34,"superagent":6}],20:[function(require,module,exports){
var Keen = require('../index');
var request = require('superagent');
var each = require('../utils/each'),
getContext = require('../helpers/get-context'),
getXHR = require('../helpers/get-xhr-object'),
requestTypes = require('../helpers/superagent-request-types'),
responseHandler = require('../helpers/superagent-handle-response');
module.exports = function(payload, callback) {
var self = this,
urlBase = this.url('/events'),
data = {},
cb = callback;
if (!Keen.enabled) {
handleValidationError.call(self, 'Keen.enabled = false');
return;
}
if (!self.projectId()) {
handleValidationError.call(self, 'Missing projectId property');
return;
}
if (!self.writeKey()) {
handleValidationError.call(self, 'Missing writeKey property');
return;
}
if (arguments.length > 2) {
handleValidationError.call(self, 'Incorrect arguments provided to #addEvents method');
return;
}
if (typeof payload !== 'object' || payload instanceof Array) {
handleValidationError.call(self, 'Request payload must be an object');
return;
}
if (self.config.globalProperties) {
each(payload, function(events, collection){
each(events, function(body, index){
var base = self.config.globalProperties(collection);
each(body, function(value, key){
base[key] = value;
});
data[collection].push(base);
});
});
}
else {
data = payload;
}
if ( getXHR() || getContext() === 'server' ) {
request
.post(urlBase)
.set('Content-Type', 'application/json')
.set('Authorization', self.writeKey())
.send(data)
.end(function(err, res){
responseHandler(err, res, cb);
cb = callback = null;
});
}
else {
self.trigger('error', 'Events not recorded: XHR support is required for batch upload');
}
function handleValidationError(msg){
var err = 'Events not recorded: ' + msg;
self.trigger('error', err);
if (cb) {
cb.call(self, err, null);
cb = callback = null;
}
}
return;
};
},{"../helpers/get-context":11,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"../index":18,"../utils/each":31,"superagent":6}],21:[function(require,module,exports){
var request = require('superagent');
var getQueryString = require('../helpers/get-query-string'),
handleResponse = require('../helpers/superagent-handle-response'),
requestTypes = require('../helpers/superagent-request-types');
module.exports = function(url, params, api_key, callback){
var reqType = this.config.requestType,
data = params || {};
if (reqType === 'beacon') {
reqType = 'jsonp';
}
data['api_key'] = data['api_key'] || api_key;
request
.get(url+getQueryString(data))
.use(requestTypes(reqType))
.end(function(err, res){
handleResponse(err, res, callback);
callback = null;
});
};
},{"../helpers/get-query-string":12,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"superagent":6}],22:[function(require,module,exports){
var request = require('superagent');
var handleResponse = require('../helpers/superagent-handle-response');
module.exports = function(url, data, api_key, callback){
request
.post(url)
.set('Content-Type', 'application/json')
.set('Authorization', api_key)
.send(data || {})
.end(function(err, res) {
handleResponse(err, res, callback);
callback = null;
});
};
},{"../helpers/superagent-handle-response":16,"superagent":6}],23:[function(require,module,exports){
var Request = require("../request");
module.exports = function(query, callback) {
var queries = [],
cb = callback,
request;
if (!this.config.projectId || !this.config.projectId.length) {
handleConfigError.call(this, 'Missing projectId property');
}
if (!this.config.readKey || !this.config.readKey.length) {
handleConfigError.call(this, 'Missing readKey property');
}
function handleConfigError(msg){
var err = 'Query not sent: ' + msg;
this.trigger('error', err);
if (cb) {
cb.call(this, err, null);
cb = callback = null;
}
}
if (query instanceof Array) {
queries = query;
} else {
queries.push(query);
}
request = new Request(this, queries, cb).refresh();
cb = callback = null;
return request;
};
},{"../request":27}],24:[function(require,module,exports){
module.exports = function(newGlobalProperties) {
if (newGlobalProperties && typeof(newGlobalProperties) == "function") {
this.config.globalProperties = newGlobalProperties;
} else {
this.trigger("error", "Invalid value for global properties: " + newGlobalProperties);
}
};
},{}],25:[function(require,module,exports){
var addEvent = require("./addEvent");
module.exports = function(jsEvent, eventCollection, payload, timeout, timeoutCallback){
var evt = jsEvent,
target = (evt.currentTarget) ? evt.currentTarget : (evt.srcElement || evt.target),
timer = timeout || 500,
triggered = false,
targetAttr = "",
callback,
win;
if (target.getAttribute !== void 0) {
targetAttr = target.getAttribute("target");
} else if (target.target) {
targetAttr = target.target;
}
if ((targetAttr == "_blank" || targetAttr == "blank") && !evt.metaKey) {
win = window.open("about:blank");
win.document.location = target.href;
}
if (target.nodeName === "A") {
callback = function(){
if(!triggered && !evt.metaKey && (targetAttr !== "_blank" && targetAttr !== "blank")){
triggered = true;
window.location = target.href;
}
};
} else if (target.nodeName === "FORM") {
callback = function(){
if(!triggered){
triggered = true;
target.submit();
}
};
} else {
this.trigger("error", "#trackExternalLink method not attached to an <a> or <form> DOM element");
}
if (timeoutCallback) {
callback = function(){
if(!triggered){
triggered = true;
timeoutCallback();
}
};
}
addEvent.call(this, eventCollection, payload, callback);
setTimeout(callback, timer);
if (!evt.metaKey) {
return false;
}
};
},{"./addEvent":19}],26:[function(require,module,exports){
var each = require("./utils/each"),
extend = require("./utils/extend"),
getTimezoneOffset = require("./helpers/get-timezone-offset"),
getQueryString = require("./helpers/get-query-string");
var Emitter = require('./utils/emitter-shim');
function Query(){
this.configure.apply(this, arguments);
};
Emitter(Query.prototype);
Query.prototype.configure = function(analysisType, params) {
this.analysis = analysisType;
this.params = this.params || {};
this.set(params);
if (this.params.timezone === void 0) {
this.params.timezone = getTimezoneOffset();
}
return this;
};
Query.prototype.set = function(attributes) {
var self = this;
each(attributes, function(v, k){
var key = k, value = v;
if (k.match(new RegExp("[A-Z]"))) {
key = k.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); });
}
self.params[key] = value;
if (value instanceof Array) {
each(value, function(dv, index){
if (dv instanceof Array == false && typeof dv === "object") {
each(dv, function(deepValue, deepKey){
if (deepKey.match(new RegExp("[A-Z]"))) {
var _deepKey = deepKey.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); });
delete self.params[key][index][deepKey];
self.params[key][index][_deepKey] = deepValue;
}
});
}
});
}
});
return self;
};
Query.prototype.get = function(attribute) {
var key = attribute;
if (key.match(new RegExp("[A-Z]"))) {
key = key.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); });
}
if (this.params) {
return this.params[key] || null;
}
};
Query.prototype.addFilter = function(property, operator, value) {
this.params.filters = this.params.filters || [];
this.params.filters.push({
"property_name": property,
"operator": operator,
"property_value": value
});
return this;
};
module.exports = Query;
},{"./helpers/get-query-string":12,"./helpers/get-timezone-offset":13,"./utils/each":31,"./utils/emitter-shim":32,"./utils/extend":33}],27:[function(require,module,exports){
var each = require('./utils/each'),
extend = require('./utils/extend'),
sendQuery = require('./utils/sendQuery'),
sendSavedQuery = require('./utils/sendSavedQuery');
var Emitter = require('./utils/emitter-shim');
var Keen = require('./');
var Query = require('./query');
function Request(client, queries, callback){
var cb = callback;
this.config = {
timeout: 300 * 1000
};
this.configure(client, queries, cb);
cb = callback = null;
};
Emitter(Request.prototype);
Request.prototype.configure = function(client, queries, callback){
var cb = callback;
extend(this, {
'client' : client,
'queries' : queries,
'data' : {},
'callback' : cb
});
cb = callback = null;
return this;
};
Request.prototype.timeout = function(ms){
if (!arguments.length) return this.config.timeout;
this.config.timeout = (!isNaN(parseInt(ms)) ? parseInt(ms) : null);
return this;
};
Request.prototype.refresh = function(){
var self = this,
completions = 0,
response = [],
errored = false;
var handleResponse = function(err, res, index){
if (errored) {
return;
}
if (err) {
self.trigger('error', err);
if (self.callback) {
self.callback(err, null);
}
errored = true;
return;
}
response[index] = res;
completions++;
if (completions == self.queries.length && !errored) {
self.data = (self.queries.length == 1) ? response[0] : response;
self.trigger('complete', null, self.data);
if (self.callback) {
self.callback(null, self.data);
}
}
};
each(self.queries, function(query, index){
var cbSequencer = function(err, res){
handleResponse(err, res, index);
};
var path = '/queries';
if (typeof query === 'string') {
path += '/saved/' + query + '/result';
sendSavedQuery.call(self, path, {}, cbSequencer);
}
else if (query instanceof Query) {
path += '/' + query.analysis;
if (query.analysis === 'saved') {
path += '/' + query.params.query_name + '/result';
sendSavedQuery.call(self, path, {}, cbSequencer);
}
else {
sendQuery.call(self, path, query.params, cbSequencer);
}
}
else {
var res = {
statusText: 'Bad Request',
responseText: { message: 'Error: Query ' + (+index+1) + ' of ' + self.queries.length + ' for project ' + self.client.projectId() + ' is not a valid request' }
};
self.trigger('error', res.responseText.message);
if (self.callback) {
self.callback(res.responseText.message, null);
}
}
});
return this;
};
module.exports = Request;
},{"./":18,"./query":26,"./utils/each":31,"./utils/emitter-shim":32,"./utils/extend":33,"./utils/sendQuery":36,"./utils/sendSavedQuery":37}],28:[function(require,module,exports){
var request = require('superagent');
var responseHandler = require('./helpers/superagent-handle-response');
function savedQueries() {
var _this = this;
this.all = function(callback) {
var url = _this.url('/queries/saved');
request
.get(url)
.set('Content-Type', 'application/json')
.set('Authorization', _this.masterKey())
.end(handleResponse);
function handleResponse(err, res){
responseHandler(err, res, callback);
callback = null;
}
};
this.get = function(queryName, callback) {
var url = _this.url('/queries/saved/' + queryName);
request
.get(url)
.set('Content-Type', 'application/json')
.set('Authorization', _this.masterKey())
.end(handleResponse);
function handleResponse(err, res){
responseHandler(err, res, callback);
callback = null;
}
};
this.update = function(queryName, body, callback) {
var url = _this.url('/queries/saved/' + queryName);
request
.put(url)
.set('Content-Type', 'application/json')
.set('Authorization', _this.masterKey())
.send(body || {})
.end(handleResponse);
function handleResponse(err, res){
responseHandler(err, res, callback);
callback = null;
}
};
this.create = this.update;
this.destroy = function(queryName, callback) {
var url = _this.url('/queries/saved/' + queryName);
request
.del(url)
.set('Content-Type', 'application/json')
.set('Authorization', _this.masterKey())
.end(handleResponse);
function handleResponse(err, res){
responseHandler(err, res, callback);
callback = null;
}
};
return this;
}
module.exports = savedQueries;
},{"./helpers/superagent-handle-response":16,"superagent":6}],29:[function(require,module,exports){
module.exports = {
map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function (n) {
"use strict";
var o = "", i = 0, m = this.map, i1, i2, i3, e1, e2, e3, e4;
n = this.utf8.encode(n);
while (i < n.length) {
i1 = n.charCodeAt(i++); i2 = n.charCodeAt(i++); i3 = n.charCodeAt(i++);
e1 = (i1 >> 2); e2 = (((i1 & 3) << 4) | (i2 >> 4)); e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6));
e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63;
o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4);
} return o;
},
decode: function (n) {
"use strict";
var o = "", i = 0, m = this.map, cc = String.fromCharCode, e1, e2, e3, e4, c1, c2, c3;
n = n.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < n.length) {
e1 = m.indexOf(n.charAt(i++)); e2 = m.indexOf(n.charAt(i++));
e3 = m.indexOf(n.charAt(i++)); e4 = m.indexOf(n.charAt(i++));
c1 = (e1 << 2) | (e2 >> 4); c2 = ((e2 & 15) << 4) | (e3 >> 2);
c3 = ((e3 & 3) << 6) | e4;
o = o + (cc(c1) + ((e3 != 64) ? cc(c2) : "")) + (((e4 != 64) ? cc(c3) : ""));
} return this.utf8.decode(o);
},
utf8: {
encode: function (n) {
"use strict";
var o = "", i = 0, cc = String.fromCharCode, c;
while (i < n.length) {
c = n.charCodeAt(i++); o = o + ((c < 128) ? cc(c) : ((c > 127) && (c < 2048)) ?
(cc((c >> 6) | 192) + cc((c & 63) | 128)) : (cc((c >> 12) | 224) + cc(((c >> 6) & 63) | 128) + cc((c & 63) | 128)));
} return o;
},
decode: function (n) {
"use strict";
var o = "", i = 0, cc = String.fromCharCode, c2, c;
while (i < n.length) {
c = n.charCodeAt(i);
o = o + ((c < 128) ? [cc(c), i++][0] : ((c > 191) && (c < 224)) ?
[cc(((c & 31) << 6) | ((c2 = n.charCodeAt(i + 1)) & 63)), (i += 2)][0] :
[cc(((c & 15) << 12) | (((c2 = n.charCodeAt(i + 1)) & 63) << 6) | ((c3 = n.charCodeAt(i + 2)) & 63)), (i += 3)][0]);
} return o;
}
}
};
},{}],30:[function(require,module,exports){
var json = require('./json-shim');
module.exports = function(target) {
return json.parse( json.stringify( target ) );
};
},{"./json-shim":34}],31:[function(require,module,exports){
module.exports = function(o, cb, s){
var n;
if (!o){
return 0;
}
s = !s ? o : s;
if (o instanceof Array){
for (n=0; n<o.length; n++) {
if (cb.call(s, o[n], n, o) === false){
return 0;
}
}
} else {
for (n in o){
if (o.hasOwnProperty(n)) {
if (cb.call(s, o[n], n, o) === false){
return 0;
}
}
}
}
return 1;
};
},{}],32:[function(require,module,exports){
var Emitter = require('component-emitter');
Emitter.prototype.trigger = Emitter.prototype.emit;
module.exports = Emitter;
},{"component-emitter":1}],33:[function(require,module,exports){
module.exports = function(target){
for (var i = 1; i < arguments.length; i++) {
for (var prop in arguments[i]){
target[prop] = arguments[i][prop];
}
}
return target;
};
},{}],34:[function(require,module,exports){
module.exports = ('undefined' !== typeof window && window.JSON) ? window.JSON : require("json3");
},{"json3":3}],35:[function(require,module,exports){
function parseParams(str){
var urlParams = {},
match,
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = str.split("?")[1];
while (!!(match=search.exec(query))) {
urlParams[decode(match[1])] = decode(match[2]);
}
return urlParams;
};
module.exports = parseParams;
},{}],36:[function(require,module,exports){
var request = require('superagent');
var getContext = require('../helpers/get-context'),
getXHR = require('../helpers/get-xhr-object'),
responseHandler = require('../helpers/superagent-handle-response');
module.exports = function(path, params, callback){
var url = this.client.url(path);
if (!this.client.projectId()) {
this.client.trigger('error', 'Query not sent: Missing projectId property');
return;
}
if (!this.client.readKey()) {
this.client.trigger('error', 'Query not sent: Missing readKey property');
return;
}
if (getContext() === 'server' || getXHR()) {
request
.post(url)
.set('Content-Type', 'application/json')
.set('Authorization', this.client.readKey())
.timeout(this.timeout())
.send(params || {})
.end(handleResponse);
}
function handleResponse(err, res){
responseHandler(err, res, callback);
callback = null;
}
return;
}
},{"../helpers/get-context":11,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"superagent":6}],37:[function(require,module,exports){
var request = require('superagent');
var responseHandler = require('../helpers/superagent-handle-response');
module.exports = function(path, params, callback){
var key;
if (this.client.readKey()) {
key = this.client.readKey();
}
else if (this.client.masterKey()) {
key = this.client.masterKey();
}
request
.get(this.client.url(path))
.set('Content-Type', 'application/json')
.set('Authorization', key)
.timeout(this.timeout())
.send()
.end(function(err, res) {
responseHandler(err, res, callback);
callback = null;
});
return;
}
},{"../helpers/superagent-handle-response":16,"superagent":6}],38:[function(require,module,exports){
var clone = require("../core/utils/clone"),
each = require("../core/utils/each"),
flatten = require("./utils/flatten"),
parse = require("./utils/parse");
var Emitter = require('../core/utils/emitter-shim');
function Dataset(){
this.data = {
input: {},
output: [['Index']]
};
this.meta = {
schema: {},
method: undefined
};
this.parser = undefined;
if (arguments.length > 0) {
this.parse.apply(this, arguments);
}
}
Dataset.defaults = {
delimeter: " -> "
};
Emitter(Dataset);
Emitter(Dataset.prototype);
Dataset.parser = require('./utils/parsers')(Dataset);
Dataset.prototype.input = function(obj){
if (!arguments.length) return this["data"]["input"];
this["data"]["input"] = (obj ? clone(obj) : null);
return this;
};
Dataset.prototype.output = function(arr){
if (!arguments.length) return this["data"].output;
this["data"].output = (arr instanceof Array ? arr : null);
return this;
}
Dataset.prototype.method = function(str){
if (!arguments.length) return this.meta["method"];
this.meta["method"] = (str ? String(str) : null);
return this;
};
Dataset.prototype.schema = function(obj){
if (!arguments.length) return this.meta.schema;
this.meta.schema = (obj ? obj : null);
return this;
};
Dataset.prototype.parse = function(raw, schema){
var options;
if (raw) this.input(raw);
if (schema) this.schema(schema);
this.output([[]]);
if (this.meta.schema.select) {
this.method("select");
options = extend({
records: "",
select: true
}, this.schema());
_select.call(this, _optHash(options));
}
else if (this.meta.schema.unpack) {
this.method("unpack");
options = extend({
records: "",
unpack: {
index: false,
value: false,
label: false
}
}, this.schema());
_unpack.call(this, _optHash(options));
}
return this;
};
function _select(cfg){
var self = this,
options = cfg || {},
target_set = [],
unique_keys = [];
var root, records_target;
if (options.records === "" || !options.records) {
root = [self.input()];
} else {
records_target = options.records.split(Dataset.defaults.delimeter);
root = parse.apply(self, [self.input()].concat(records_target))[0];
}
each(options.select, function(prop){
target_set.push(prop.path.split(Dataset.defaults.delimeter));
});
if (target_set.length == 0) {
each(root, function(record, interval){
var flat = flatten(record);
for (var key in flat) {
if (flat.hasOwnProperty(key) && unique_keys.indexOf(key) == -1) {
unique_keys.push(key);
target_set.push([key]);
}
}
});
}
var test = [[]];
each(target_set, function(props, i){
if (target_set.length == 1) {
test[0].push('label', 'value');
} else {
test[0].push(props.join("."));
}
});
each(root, function(record, i){
var flat = flatten(record);
if (target_set.length == 1) {
test.push([target_set.join("."), flat[target_set.join(".")]]);
} else {
test.push([]);
each(target_set, function(t, j){
var target = t.join(".");
test[i+1].push(flat[target]);
});
}
});
self.output(test);
self.format(options.select);
return self;
}
function _unpack(options){
var self = this, discovered_labels = [];
var value_set = (options.unpack.value) ? options.unpack.value.path.split(Dataset.defaults.delimeter) : false,
label_set = (options.unpack.label) ? options.unpack.label.path.split(Dataset.defaults.delimeter) : false,
index_set = (options.unpack.index) ? options.unpack.index.path.split(Dataset.defaults.delimeter) : false;
var value_desc = (value_set[value_set.length-1] !== "") ? value_set[value_set.length-1] : "Value",
label_desc = (label_set[label_set.length-1] !== "") ? label_set[label_set.length-1] : "Label",
index_desc = (index_set[index_set.length-1] !== "") ? index_set[index_set.length-1] : "Index";
var root = (function(){
var root;
if (options.records == "") {
root = [self.input()];
} else {
root = parse.apply(self, [self.input()].concat(options.records.split(Dataset.defaults.delimeter)));
}
return root[0];
})();
if (root instanceof Array == false) {
root = [root];
}
each(root, function(record, interval){
var labels = (label_set) ? parse.apply(self, [record].concat(label_set)) : [];
if (labels) {
discovered_labels = labels;
}
});
each(root, function(record, interval){
var plucked_value = (value_set) ? parse.apply(self, [record].concat(value_set)) : false,
plucked_index = (index_set) ? parse.apply(self, [record].concat(index_set)) : false;
if (plucked_index) {
each(plucked_index, function(){
self.data.output.push([]);
});
} else {
self.data.output.push([]);
}
if (plucked_index) {
if (interval == 0) {
self.data.output[0].push(index_desc);
if (discovered_labels.length > 0) {
each(discovered_labels, function(value, i){
self.data.output[0].push(value);
});
} else {
self.data.output[0].push(value_desc);
}
}
if (root.length < self.data.output.length-1) {
if (interval == 0) {
each(self.data.output, function(row, i){
if (i > 0) {
self.data.output[i].push(plucked_index[i-1]);
}
});
}
} else {
self.data.output[interval+1].push(plucked_index[0]);
}
}
if (!plucked_index && discovered_labels.length > 0) {
if (interval == 0) {
self.data.output[0].push(label_desc);
self.data.output[0].push(value_desc);
}
self.data.output[interval+1].push(discovered_labels[0]);
}
if (!plucked_index && discovered_labels.length == 0) {
self.data.output[0].push('');
}
if (plucked_value) {
if (root.length < self.data.output.length-1) {
if (interval == 0) {
each(self.data.output, function(row, i){
if (i > 0) {
self.data.output[i].push(plucked_value[i-1]);
}
});
}
} else {
each(plucked_value, function(value){
self.data.output[interval+1].push(value);
});
}
} else {
each(self.data.output[0], function(cell, i){
var offset = (plucked_index) ? 0 : -1;
if (i > offset) {
self.data.output[interval+1].push(null);
}
})
}
});
self.format(options.unpack);
return this;
}
function _optHash(options){
each(options.unpack, function(value, key, object){
if (value && is(value, 'string')) {
options.unpack[key] = { path: options.unpack[key] };
}
});
return options;
}
function is(o, t){
o = typeof(o);
if (!t){
return o != 'undefined';
}
return o == t;
}
function extend(o, e){
each(e, function(v, n){
if (is(o[n], 'object') && is(v, 'object')){
o[n] = extend(o[n], v);
} else if (v !== null) {
o[n] = v;
}
});
return o;
}
module.exports = Dataset;
},{"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/emitter-shim":32,"./utils/flatten":51,"./utils/parse":52,"./utils/parsers":53}],39:[function(require,module,exports){
var extend = require("../core/utils/extend"),
Dataset = require("./dataset");
extend(Dataset.prototype, require("./lib/append"));
extend(Dataset.prototype, require("./lib/delete"));
extend(Dataset.prototype, require("./lib/filter"));
extend(Dataset.prototype, require("./lib/insert"));
extend(Dataset.prototype, require("./lib/select"));
extend(Dataset.prototype, require("./lib/set"));
extend(Dataset.prototype, require("./lib/sort"));
extend(Dataset.prototype, require("./lib/update"));
extend(Dataset.prototype, require("./lib/analyses"));
extend(Dataset.prototype, {
"format": require("./lib/format")
});
module.exports = Dataset;
},{"../core/utils/extend":33,"./dataset":38,"./lib/analyses":40,"./lib/append":41,"./lib/delete":42,"./lib/filter":43,"./lib/format":44,"./lib/insert":45,"./lib/select":46,"./lib/set":47,"./lib/sort":48,"./lib/update":49}],40:[function(require,module,exports){
var each = require("../../core/utils/each"),
arr = ["Average", "Maximum", "Minimum", "Sum"],
output = {};
output["average"] = function(arr, start, end){
var set = arr.slice(start||0, (end ? end+1 : arr.length)),
sum = 0,
avg = null;
each(set, function(val, i){
if (typeof val === "number" && !isNaN(parseFloat(val))) {
sum += parseFloat(val);
}
});
return sum / set.length;
};
output["maximum"] = function(arr, start, end){
var set = arr.slice(start||0, (end ? end+1 : arr.length)),
nums = [];
each(set, function(val, i){
if (typeof val === "number" && !isNaN(parseFloat(val))) {
nums.push(parseFloat(val));
}
});
return Math.max.apply(Math, nums);
};
output["minimum"] = function(arr, start, end){
var set = arr.slice(start||0, (end ? end+1 : arr.length)),
nums = [];
each(set, function(val, i){
if (typeof val === "number" && !isNaN(parseFloat(val))) {
nums.push(parseFloat(val));
}
});
return Math.min.apply(Math, nums);
};
output["sum"] = function(arr, start, end){
var set = arr.slice(start||0, (end ? end+1 : arr.length)),
sum = 0;
each(set, function(val, i){
if (typeof val === "number" && !isNaN(parseFloat(val))) {
sum += parseFloat(val);
}
});
return sum;
};
each(arr, function(v,i){
output["getColumn"+v] = output["getRow"+v] = function(arr){
return this[v.toLowerCase()](arr, 1);
};
});
output["getColumnLabel"] = output["getRowIndex"] = function(arr){
return arr[0];
};
module.exports = output;
},{"../../core/utils/each":31}],41:[function(require,module,exports){
var each = require("../../core/utils/each");
var createNullList = require('../utils/create-null-list');
module.exports = {
"appendColumn": appendColumn,
"appendRow": appendRow
};
function appendColumn(str, input){
var self = this,
args = Array.prototype.slice.call(arguments, 2),
label = (str !== undefined) ? str : null;
if (typeof input === "function") {
self.data.output[0].push(label);
each(self.output(), function(row, i){
var cell;
if (i > 0) {
cell = input.call(self, row, i);
if (typeof cell === "undefined") {
cell = null;
}
self.data.output[i].push(cell);
}
});
}
else if (!input || input instanceof Array) {
input = input || [];
if (input.length <= self.output().length - 1) {
input = input.concat( createNullList(self.output().length - 1 - input.length) );
}
else {
each(input, function(value, i){
if (self.data.output.length -1 < input.length) {
appendRow.call(self, String( self.data.output.length ));
}
});
}
self.data.output[0].push(label);
each(input, function(value, i){
self.data.output[i+1][self.data.output[0].length-1] = value;
});
}
return self;
}
function appendRow(str, input){
var self = this,
args = Array.prototype.slice.call(arguments, 2),
label = (str !== undefined) ? str : null,
newRow = [];
newRow.push(label);
if (typeof input === "function") {
each(self.data.output[0], function(label, i){
var col, cell;
if (i > 0) {
col = self.selectColumn(i);
cell = input.call(self, col, i);
if (typeof cell === "undefined") {
cell = null;
}
newRow.push(cell);
}
});
self.data.output.push(newRow);
}
else if (!input || input instanceof Array) {
input = input || [];
if (input.length <= self.data.output[0].length - 1) {
input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) );
}
else {
each(input, function(value, i){
if (self.data.output[0].length -1 < input.length) {
appendColumn.call(self, String( self.data.output[0].length ));
}
});
}
self.data.output.push( newRow.concat(input) );
}
return self;
}
},{"../../core/utils/each":31,"../utils/create-null-list":50}],42:[function(require,module,exports){
var each = require("../../core/utils/each");
module.exports = {
"deleteColumn": deleteColumn,
"deleteRow": deleteRow
};
function deleteColumn(q){
var self = this,
index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q);
if (index > -1) {
each(self.data.output, function(row, i){
self.data.output[i].splice(index, 1);
});
}
return self;
}
function deleteRow(q){
var index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q);
if (index > -1) {
this.data.output.splice(index, 1);
}
return this;
}
},{"../../core/utils/each":31}],43:[function(require,module,exports){
var each = require("../../core/utils/each");
module.exports = {
"filterColumns": filterColumns,
"filterRows": filterRows
};
function filterColumns(fn){
var self = this,
clone = new Array();
each(self.data.output, function(row, i){
clone.push([]);
});
each(self.data.output[0], function(col, i){
var selectedColumn = self.selectColumn(i);
if (i == 0 || fn.call(self, selectedColumn, i)) {
each(selectedColumn, function(cell, ri){
clone[ri].push(cell);
});
}
});
self.output(clone);
return self;
}
function filterRows(fn){
var self = this,
clone = [];
each(self.output(), function(row, i){
if (i == 0 || fn.call(self, row, i)) {
clone.push(row);
}
});
self.output(clone);
return self;
}
},{"../../core/utils/each":31}],44:[function(require,module,exports){
var each = require("../../core/utils/each");
module.exports = function(options){
var self = this;
if (this.method() === 'select') {
each(self.output(), function(row, i){
if (i == 0) {
each(row, function(cell, j){
if (options[j] && options[j].label) {
self.data.output[i][j] = options[j].label;
}
});
} else {
each(row, function(cell, j){
self.data.output[i][j] = _applyFormat(self.data.output[i][j], options[j]);
});
}
});
}
if (this.method() === 'unpack') {
if (options.index) {
each(self.output(), function(row, i){
if (i == 0) {
if (options.index.label) {
self.data.output[i][0] = options.index.label;
}
} else {
self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.index);
}
});
}
if (options.label) {
if (options.index) {
each(self.output(), function(row, i){
each(row, function(cell, j){
if (i == 0 && j > 0) {
self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.label);
}
});
});
} else {
each(self.output(), function(row, i){
if (i > 0) {
self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.label);
}
});
}
}
if (options.value) {
if (options.index) {
each(self.output(), function(row, i){
each(row, function(cell, j){
if (i > 0 && j > 0) {
self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value);
}
});
});
} else {
each(self.output(), function(row, i){
each(row, function(cell, j){
if (i > 0) {
self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value);
}
});
});
}
}
}
return self;
};
function _applyFormat(value, opts){
var output = value,
options = opts || {};
if (options.replace) {
each(options.replace, function(val, key){
if (output == key || String(output) == String(key) || parseFloat(output) == parseFloat(key)) {
output = val;
}
});
}
if (options.type && options.type == 'date') {
if (options.format && moment && moment(value).isValid()) {
output = moment(output).format(options.format);
} else {
output = new Date(output);
}
}
if (options.type && options.type == 'string') {
output = String(output);
}
if (options.type && options.type == 'number' && !isNaN(parseFloat(output))) {
output = parseFloat(output);
}
return output;
}
},{"../../core/utils/each":31}],45:[function(require,module,exports){
var each = require("../../core/utils/each");
var createNullList = require('../utils/create-null-list');
var append = require('./append');
var appendRow = append.appendRow,
appendColumn = append.appendColumn;
module.exports = {
"insertColumn": insertColumn,
"insertRow": insertRow
};
function insertColumn(index, str, input){
var self = this, label;
label = (str !== undefined) ? str : null;
if (typeof input === "function") {
self.data.output[0].splice(index, 0, label);
each(self.output(), function(row, i){
var cell;
if (i > 0) {
cell = input.call(self, row, i);
if (typeof cell === "undefined") {
cell = null;
}
self.data.output[i].splice(index, 0, cell);
}
});
}
else if (!input || input instanceof Array) {
input = input || [];
if (input.length <= self.output().length - 1) {
input = input.concat( createNullList(self.output().length - 1 - input.length) );
}
else {
each(input, function(value, i){
if (self.data.output.length -1 < input.length) {
appendRow.call(self, String( self.data.output.length ));
}
});
}
self.data.output[0].splice(index, 0, label);
each(input, function(value, i){
self.data.output[i+1].splice(index, 0, value);
});
}
return self;
}
function insertRow(index, str, input){
var self = this, label, newRow = [];
label = (str !== undefined) ? str : null;
newRow.push(label);
if (typeof input === "function") {
each(self.output()[0], function(label, i){
var col, cell;
if (i > 0) {
col = self.selectColumn(i);
cell = input.call(self, col, i);
if (typeof cell === "undefined") {
cell = null;
}
newRow.push(cell);
}
});
self.data.output.splice(index, 0, newRow);
}
else if (!input || input instanceof Array) {
input = input || [];
if (input.length <= self.data.output[0].length - 1) {
input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) );
}
else {
each(input, function(value, i){
if (self.data.output[0].length -1 < input.length) {
appendColumn.call(self, String( self.data.output[0].length ));
}
});
}
self.data.output.splice(index, 0, newRow.concat(input) );
}
return self;
}
},{"../../core/utils/each":31,"../utils/create-null-list":50,"./append":41}],46:[function(require,module,exports){
var each = require("../../core/utils/each");
module.exports = {
"selectColumn": selectColumn,
"selectRow": selectRow
};
function selectColumn(q){
var result = new Array(),
index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q);
if (index > -1 && 'undefined' !== typeof this.data.output[0][index]) {
each(this.data.output, function(row, i){
result.push(row[index]);
});
}
return result;
}
function selectRow(q){
var result = new Array(),
index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q);
if (index > -1 && 'undefined' !== typeof this.data.output[index]) {
result = this.data.output[index];
}
return result;
}
},{"../../core/utils/each":31}],47:[function(require,module,exports){
var each = require("../../core/utils/each");
var append = require('./append');
var select = require('./select');
module.exports = {
"set": set
};
function set(coords, value){
if (arguments.length < 2 || coords.length < 2) {
throw Error('Incorrect arguments provided for #set method');
}
var colIndex = 'number' === typeof coords[0] ? coords[0] : this.data.output[0].indexOf(coords[0]),
rowIndex = 'number' === typeof coords[1] ? coords[1] : select.selectColumn.call(this, 0).indexOf(coords[1]);
var colResult = select.selectColumn.call(this, coords[0]),
rowResult = select.selectRow.call(this, coords[1]);
if (colResult.length < 1) {
append.appendColumn.call(this, coords[0]);
colIndex = this.data.output[0].length-1;
}
if (rowResult.length < 1) {
append.appendRow.call(this, coords[1]);
rowIndex = this.data.output.length-1;
}
this.data.output[ rowIndex ][ colIndex ] = value;
return this;
}
},{"../../core/utils/each":31,"./append":41,"./select":46}],48:[function(require,module,exports){
var each = require("../../core/utils/each");
module.exports = {
"sortColumns": sortColumns,
"sortRows": sortRows
};
function sortColumns(str, comp){
var self = this,
head = this.output()[0].slice(1),
cols = [],
clone = [],
fn = comp || this.getColumnLabel;
each(head, function(cell, i){
cols.push(self.selectColumn(i+1).slice(0));
});
cols.sort(function(a,b){
var op = fn.call(self, a) > fn.call(self, b);
if (op) {
return (str === "asc" ? 1 : -1);
} else if (!op) {
return (str === "asc" ? -1 : 1);
} else {
return 0;
}
});
each(cols, function(col, i){
self
.deleteColumn(i+1)
.insertColumn(i+1, col[0], col.slice(1));
});
return self;
}
function sortRows(str, comp){
var self = this,
head = this.output().slice(0,1),
body = this.output().slice(1),
fn = comp || this.getRowIndex;
body.sort(function(a, b){
var op = fn.call(self, a) > fn.call(self, b);
if (op) {
return (str === "asc" ? 1 : -1);
} else if (!op) {
return (str === "asc" ? -1 : 1);
} else {
return 0;
}
});
self.output(head.concat(body));
return self;
}
},{"../../core/utils/each":31}],49:[function(require,module,exports){
var each = require("../../core/utils/each");
var createNullList = require('../utils/create-null-list');
var append = require('./append');
var appendRow = append.appendRow,
appendColumn = append.appendColumn;
module.exports = {
"updateColumn": updateColumn,
"updateRow": updateRow
};
function updateColumn(q, input){
var self = this,
index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q);
if (index > -1) {
if (typeof input === "function") {
each(self.output(), function(row, i){
var cell;
if (i > 0) {
cell = input.call(self, row[index], i, row);
if (typeof cell !== "undefined") {
self.data.output[i][index] = cell;
}
}
});
} else if (!input || input instanceof Array) {
input = input || [];
if (input.length <= self.output().length - 1) {
input = input.concat( createNullList(self.output().length - 1 - input.length) );
}
else {
each(input, function(value, i){
if (self.data.output.length -1 < input.length) {
appendRow.call(self, String( self.data.output.length ));
}
});
}
each(input, function(value, i){
self.data.output[i+1][index] = value;
});
}
}
return self;
}
function updateRow(q, input){
var self = this,
index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q);
if (index > -1) {
if (typeof input === "function") {
each(self.output()[index], function(value, i){
var col = self.selectColumn(i),
cell = input.call(self, value, i, col);
if (typeof cell !== "undefined") {
self.data.output[index][i] = cell;
}
});
} else if (!input || input instanceof Array) {
input = input || [];
if (input.length <= self.data.output[0].length - 1) {
input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) );
}
else {
each(input, function(value, i){
if (self.data.output[0].length -1 < input.length) {
appendColumn.call(self, String( self.data.output[0].length ));
}
});
}
each(input, function(value, i){
self.data.output[index][i+1] = value;
});
}
}
return self;
}
},{"../../core/utils/each":31,"../utils/create-null-list":50,"./append":41}],50:[function(require,module,exports){
module.exports = function(len){
var list = new Array();
for (i = 0; i < len; i++) {
list.push(null);
}
return list;
};
},{}],51:[function(require,module,exports){
module.exports = flatten;
function flatten(ob) {
var toReturn = {};
for (var i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object' && ob[i] !== null) {
var flatObject = flatten(ob[i]);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + '.' + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
}
},{}],52:[function(require,module,exports){
var each = require("../../core/utils/each");
module.exports = function() {
var result = [];
var loop = function() {
var root = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
var target = args.pop();
if (args.length === 0) {
if (root instanceof Array) {
args = root;
} else if (typeof root === 'object') {
args.push(root);
}
}
each(args, function(el){
if (target == "") {
if (typeof el == "number" || el == null) {
return result.push(el);
}
}
if (el[target] || el[target] === 0 || el[target] !== void 0) {
if (el[target] === null) {
return result.push(null);
} else {
return result.push(el[target]);
}
} else if (root[el]){
if (root[el] instanceof Array) {
each(root[el], function(n, i) {
var splinter = [root[el]].concat(root[el][i]).concat(args.slice(1)).concat(target);
return loop.apply(this, splinter);
});
} else {
if (root[el][target]) {
return result.push(root[el][target]);
} else {
return loop.apply(this, [root[el]].concat(args.splice(1)).concat(target));
}
}
} else if (typeof root === 'object' && root instanceof Array === false && !root[target]) {
throw new Error("Target property does not exist", target);
} else {
return loop.apply(this, [el].concat(args.splice(1)).concat(target));
}
return;
});
if (result.length > 0) {
return result;
}
};
return loop.apply(this, arguments);
}
},{"../../core/utils/each":31}],53:[function(require,module,exports){
var Dataset; /* injected */
var each = require('../../core/utils/each'),
flatten = require('./flatten');
var parsers = {
'metric': parseMetric,
'interval': parseInterval,
'grouped-metric': parseGroupedMetric,
'grouped-interval': parseGroupedInterval,
'double-grouped-metric': parseDoubleGroupedMetric,
'double-grouped-interval': parseDoubleGroupedInterval,
'funnel': parseFunnel,
'list': parseList,
'extraction': parseExtraction
};
module.exports = initialize;
function initialize(lib){
Dataset = lib;
return function(name){
var options = Array.prototype.slice.call(arguments, 1);
if (!parsers[name]) {
throw 'Requested parser does not exist';
}
else {
return parsers[name].apply(this, options);
}
};
}
function parseMetric(){
return function(res){
var dataset = new Dataset();
dataset.data.input = res;
dataset.parser = {
name: 'metric'
};
return dataset.set(['Value', 'Result'], res.result);
}
}
function parseInterval(){
var options = Array.prototype.slice.call(arguments);
return function(res){
var dataset = new Dataset();
each(res.result, function(record, i){
var index = options[0] && options[0] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start;
dataset.set(['Result', index], record.value);
});
dataset.data.input = res;
dataset.parser = 'interval';
dataset.parser = {
name: 'interval',
options: options
};
return dataset;
}
}
function parseGroupedMetric(){
return function(res){
var dataset = new Dataset();
each(res.result, function(record, i){
var label;
each(record, function(value, key){
if (key !== 'result') {
label = key;
}
});
dataset.set(['Result', String(record[label])], record.result);
});
dataset.data.input = res;
dataset.parser = {
name: 'grouped-metric'
};
return dataset;
}
}
function parseGroupedInterval(){
var options = Array.prototype.slice.call(arguments);
return function(res){
var dataset = new Dataset();
each(res.result, function(record, i){
var index = options[0] && options[0] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start;
if (record.value.length) {
each(record.value, function(group, j){
var label;
each(group, function(value, key){
if (key !== 'result') {
label = key;
}
});
dataset.set([ String(group[label]) || '', index ], group.result);
});
}
else {
dataset.appendRow(index);
}
});
dataset.data.input = res;
dataset.parser = {
name: 'grouped-interval',
options: options
};
return dataset;
}
}
function parseDoubleGroupedMetric(){
var options = Array.prototype.slice.call(arguments);
if (!options[0]) throw 'Requested parser requires a sequential list (array) of properties to target as a second argument';
return function(res){
var dataset = new Dataset();
each(res.result, function(record, i){
dataset.set([ 'Result', record[options[0][0]] + ' ' + record[options[0][1]] ], record.result);
});
dataset.data.input = res;
dataset.parser = {
name: 'double-grouped-metric',
options: options
};
return dataset;
}
}
function parseDoubleGroupedInterval(){
var options = Array.prototype.slice.call(arguments);
if (!options[0]) throw 'Requested parser requires a sequential list (array) of properties to target as a second argument';
return function(res){
var dataset = new Dataset();
each(res.result, function(record, i){
var index = options[1] && options[1] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start;
each(record['value'], function(value, j){
var label = String(value[options[0][0]]) + ' ' + String(value[options[0][1]]);
dataset.set([ label, index ], value.result);
});
});
dataset.data.input = res;
dataset.parser = {
name: 'double-grouped-interval',
options: options
};
return dataset;
}
}
function parseFunnel(){
return function(res){
var dataset = new Dataset();
dataset.appendColumn('Step Value');
each(res.result, function(value, i){
dataset.appendRow(res.steps[i].event_collection, [ value ]);
});
dataset.data.input = res;
dataset.parser = {
name: 'funnel'
};
return dataset;
}
}
function parseList(){
return function(res){
var dataset = new Dataset();
each(res.result, function(value, i){
dataset.set( [ 'Value', i+1 ], value );
});
dataset.data.input = res;
dataset.parser = {
name: 'list'
};
return dataset;
}
}
function parseExtraction(){
return function(res){
var dataset = new Dataset();
each(res.result, function(record, i){
each(flatten(record), function(value, key){
dataset.set([key, i+1], value);
});
});
dataset.deleteColumn(0);
dataset.data.input = res;
dataset.parser = {
name: 'extraction'
};
return dataset;
}
}
},{"../../core/utils/each":31,"./flatten":51}],54:[function(require,module,exports){
/*!
* ----------------------
* C3.js Adapter
* ----------------------
*/
var Dataviz = require('../dataviz'),
each = require('../../core/utils/each'),
extend = require('../../core/utils/extend');
getSetupTemplate = require('./c3/get-setup-template')
module.exports = function(){
var dataTypes = {
'singular' : ['gauge'],
'categorical' : ['donut', 'pie'],
'cat-interval' : ['area-step', 'step', 'bar', 'area', 'area-spline', 'spline', 'line'],
'cat-ordinal' : ['bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'],
'chronological' : ['area', 'area-spline', 'spline', 'line', 'bar', 'step', 'area-step'],
'cat-chronological' : ['line', 'spline', 'area', 'area-spline', 'bar', 'step', 'area-step']
};
var charts = {};
each(['gauge', 'donut', 'pie', 'bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'], function(type, index){
charts[type] = {
render: function(){
if (this.data()[0].length === 1 || this.data().length === 1) {
this.error('No data to display');
return;
}
this.view._artifacts['c3'] = c3.generate(getSetupTemplate.call(this, type));
this.update();
},
update: function(){
var self = this, cols = [];
if (type === 'gauge') {
self.view._artifacts['c3'].load({
columns: [ [self.title(), self.data()[1][1]] ]
})
}
else if (type === 'pie' || type === 'donut') {
self.view._artifacts['c3'].load({
columns: self.dataset.data.output.slice(1)
});
}
else {
if (this.dataType().indexOf('chron') > -1) {
cols.push(self.dataset.selectColumn(0));
cols[0][0] = 'x';
}
each(self.data()[0], function(c, i){
if (i > 0) {
cols.push(self.dataset.selectColumn(i));
}
});
if (self.stacked()) {
self.view._artifacts['c3'].groups([self.labels()]);
}
self.view._artifacts['c3'].load({
columns: cols
});
}
},
destroy: function(){
_selfDestruct.call(this);
}
};
});
function _selfDestruct(){
if (this.view._artifacts['c3']) {
this.view._artifacts['c3'].destroy();
this.view._artifacts['c3'] = null;
}
}
Dataviz.register('c3', charts, { capabilities: dataTypes });
};
},{"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59,"./c3/get-setup-template":55}],55:[function(require,module,exports){
var extend = require('../../../core/utils/extend');
var clone = require('../../../core/utils/clone');
module.exports = function (type) {
var chartOptions = clone(this.chartOptions());
var setup = extend({
axis: {},
color: {},
data: {},
size: {}
}, chartOptions);
setup.bindto = this.el();
setup.color.pattern = this.colors();
setup.data.columns = [];
setup.size.height = this.height();
setup.size.width = this.width();
setup['data']['type'] = type;
if (type === 'gauge') {}
else if (type === 'pie' || type === 'donut') {
setup[type] = { title: this.title() };
}
else {
if (this.dataType().indexOf('chron') > -1) {
setup['data']['x'] = 'x';
setup['axis']['x'] = setup['axis']['x'] || {};
setup['axis']['x']['type'] = 'timeseries';
setup['axis']['x']['tick'] = setup['axis']['x']['tick'] || {
format: this.dateFormat() || getDateFormatDefault(this.data()[1][0], this.data()[2][0])
};
}
else {
if (this.dataType() === 'cat-ordinal') {
setup['axis']['x'] = setup['axis']['x'] || {};
setup['axis']['x']['type'] = 'category';
setup['axis']['x']['categories'] = setup['axis']['x']['categories'] || this.labels()
}
}
if (this.title()) {
setup['axis']['y'] = { label: this.title() };
}
}
return setup;
}
function getDateFormatDefault(a, b){
var d = Math.abs(new Date(a).getTime() - new Date(b).getTime());
var months = [
'Jan', 'Feb', 'Mar',
'Apr', 'May', 'June',
'July', 'Aug', 'Sept',
'Oct', 'Nov', 'Dec'
];
if (d >= 2419200000) {
return function(ms){
var date = new Date(ms);
return months[date.getMonth()] + ' ' + date.getFullYear();
};
}
else if (d >= 86400000) {
return function(ms){
var date = new Date(ms);
return months[date.getMonth()] + ' ' + date.getDate();
};
}
else if (d >= 3600000) {
return '%I:%M %p';
}
else {
return '%I:%M:%S %p';
}
}
},{"../../../core/utils/clone":30,"../../../core/utils/extend":33}],56:[function(require,module,exports){
/*!
* ----------------------
* Chart.js Adapter
* ----------------------
*/
var Dataviz = require("../dataviz"),
each = require("../../core/utils/each"),
extend = require("../../core/utils/extend");
module.exports = function(){
if (typeof Chart !== "undefined") {
Chart.defaults.global.responsive = true;
}
var dataTypes = {
"categorical" : ["doughnut", "pie", "polar-area", "radar"],
"cat-interval" : ["bar", "line"],
"cat-ordinal" : ["bar", "line"],
"chronological" : ["line", "bar"],
"cat-chronological" : ["line", "bar"]
};
var ChartNameMap = {
"radar": "Radar",
"polar-area": "PolarArea",
"pie": "Pie",
"doughnut": "Doughnut",
"line": "Line",
"bar": "Bar"
};
var dataTransformers = {
'doughnut': getCategoricalData,
'pie': getCategoricalData,
'polar-area': getCategoricalData,
'radar': getSeriesData,
'line': getSeriesData,
'bar': getSeriesData
};
function getCategoricalData(){
var self = this, result = [];
each(self.dataset.selectColumn(0).slice(1), function(label, i){
result.push({
value: self.dataset.selectColumn(1).slice(1)[i],
color: self.colors()[+i],
hightlight: self.colors()[+i+9],
label: label
});
});
return result;
}
function getSeriesData(){
var self = this,
labels,
result = {
labels: [],
datasets: []
};
labels = this.dataset.selectColumn(0).slice(1);
each(labels, function(l,i){
if (l instanceof Date) {
result.labels.push((l.getMonth()+1) + "-" + l.getDate() + "-" + l.getFullYear());
} else {
result.labels.push(l);
}
})
each(self.dataset.selectRow(0).slice(1), function(label, i){
var hex = {
r: hexToR(self.colors()[i]),
g: hexToG(self.colors()[i]),
b: hexToB(self.colors()[i])
};
result.datasets.push({
label: label,
fillColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",0.2)",
strokeColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)",
pointColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)",
data: self.dataset.selectColumn(+i+1).slice(1)
});
});
return result;
}
var charts = {};
each(["doughnut", "pie", "polar-area", "radar", "bar", "line"], function(type, index){
charts[type] = {
initialize: function(){
if (this.data()[0].length === 1 || this.data().length === 1) {
this.error('No data to display');
return;
}
if (this.el().nodeName.toLowerCase() !== "canvas") {
var canvas = document.createElement('canvas');
this.el().innerHTML = "";
this.el().appendChild(canvas);
this.view._artifacts["ctx"] = canvas.getContext("2d");
}
else {
this.view._artifacts["ctx"] = this.el().getContext("2d");
}
if (this.height()) {
this.view._artifacts["ctx"].canvas.height = this.height();
this.view._artifacts["ctx"].canvas.style.height = String(this.height() + "px");
}
if (this.width()) {
this.view._artifacts["ctx"].canvas.width = this.width();
this.view._artifacts["ctx"].canvas.style.width = String(this.width() + "px");
}
return this;
},
render: function(){
if(_isEmptyOutput(this.dataset)) {
this.error("No data to display");
return;
}
var method = ChartNameMap[type],
opts = extend({}, this.chartOptions()),
data = dataTransformers[type].call(this);
if (this.view._artifacts["chartjs"]) {
this.view._artifacts["chartjs"].destroy();
}
this.view._artifacts["chartjs"] = new Chart(this.view._artifacts["ctx"])[method](data, opts);
return this;
},
destroy: function(){
_selfDestruct.call(this);
}
};
});
function _selfDestruct(){
if (this.view._artifacts["chartjs"]) {
this.view._artifacts["chartjs"].destroy();
this.view._artifacts["chartjs"] = null;
}
}
function _isEmptyOutput(dataset) {
var flattened = dataset.output().reduce(function(a, b) {
return a.concat(b)
});
return flattened.length === 0
}
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
Dataviz.register("chartjs", charts, { capabilities: dataTypes });
};
},{"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59}],57:[function(require,module,exports){
/*!
* ----------------------
* Google Charts Adapter
* ----------------------
*/
/*
TODO:
[ ] Build a more robust DataTable transformer
[ ] ^Expose date parser for google charts tooltips (#70)
[ ] ^Allow custom tooltips (#147)
*/
var Dataviz = require("../dataviz"),
each = require("../../core/utils/each"),
extend = require("../../core/utils/extend"),
Keen = require("../../core");
module.exports = function(){
Keen.loaded = false;
var errorMapping = {
"Data column(s) for axis #0 cannot be of type string": "No results to visualize"
};
var chartTypes = ['AreaChart', 'BarChart', 'ColumnChart', 'LineChart', 'PieChart', 'Table'];
var chartMap = {};
var dataTypes = {
'categorical': ['piechart', 'barchart', 'columnchart', 'table'],
'cat-interval': ['columnchart', 'barchart', 'table'],
'cat-ordinal': ['barchart', 'columnchart', 'areachart', 'linechart', 'table'],
'chronological': ['areachart', 'linechart', 'table'],
'cat-chronological': ['linechart', 'columnchart', 'barchart', 'areachart'],
'nominal': ['table'],
'extraction': ['table']
};
each(chartTypes, function (type) {
var name = type.toLowerCase();
chartMap[name] = {
initialize: function(){
},
render: function(){
if(typeof google === "undefined") {
this.error("The Google Charts library could not be loaded.");
return;
}
var self = this;
if (self.view._artifacts['googlechart']) {
this.destroy();
}
self.view._artifacts['googlechart'] = self.view._artifacts['googlechart'] || new google.visualization[type](self.el());
google.visualization.events.addListener(self.view._artifacts['googlechart'], 'error', function(stack){
_handleErrors.call(self, stack);
});
this.update();
},
update: function(){
var options = _getDefaultAttributes.call(this, type);
extend(options, this.chartOptions(), this.attributes());
options['isStacked'] = (this.stacked() || options['isStacked']);
this.view._artifacts['datatable'] = google.visualization.arrayToDataTable(this.data());
if (options.dateFormat) {
if (typeof options.dateFormat === 'function') {
options.dateFormat(this.view._artifacts['datatable']);
}
else if (typeof options.dateFormat === 'string') {
new google.visualization.DateFormat({
pattern: options.dateFormat
}).format(this.view._artifacts['datatable'], 0);
}
}
if (this.view._artifacts['googlechart']) {
this.view._artifacts['googlechart'].draw(this.view._artifacts['datatable'], options);
}
},
destroy: function(){
if (this.view._artifacts['googlechart']) {
google.visualization.events.removeAllListeners(this.view._artifacts['googlechart']);
this.view._artifacts['googlechart'].clearChart();
this.view._artifacts['googlechart'] = null;
this.view._artifacts['datatable'] = null;
}
}
};
});
Dataviz.register('google', chartMap, {
capabilities: dataTypes,
dependencies: [{
type: 'script',
url: 'https://www.google.com/jsapi',
cb: function(done) {
if (typeof google === 'undefined'){
this.trigger("error", "Problem loading Google Charts library. Please contact us!");
done();
}
else {
google.load('visualization', '1.1', {
packages: ['corechart', 'table'],
callback: function(){
done();
}
});
}
}
}]
});
function _handleErrors(stack){
var message = errorMapping[stack['message']] || stack['message'] || 'An error occurred';
this.error(message);
}
function _getDefaultAttributes(type){
var output = {};
switch (type.toLowerCase()) {
case "areachart":
output.lineWidth = 2;
output.hAxis = {
baselineColor: 'transparent',
gridlines: { color: 'transparent' }
};
output.vAxis = {
viewWindow: { min: 0 }
};
if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") {
output.legend = "none";
output.chartArea = {
width: "85%"
};
}
if (this.dateFormat() && typeof this.dateFormat() === 'string') {
output.hAxis.format = this.dateFormat();
}
break;
case "barchart":
output.hAxis = {
viewWindow: { min: 0 }
};
output.vAxis = {
baselineColor: 'transparent',
gridlines: { color: 'transparent' }
};
if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") {
output.legend = "none";
}
if (this.dateFormat() && typeof this.dateFormat() === 'string') {
output.vAxis.format = this.dateFormat();
}
break;
case "columnchart":
output.hAxis = {
baselineColor: 'transparent',
gridlines: { color: 'transparent' }
};
output.vAxis = {
viewWindow: { min: 0 }
};
if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") {
output.legend = "none";
output.chartArea = {
width: "85%"
};
}
if (this.dateFormat() && typeof this.dateFormat() === 'string') {
output.hAxis.format = this.dateFormat();
}
break;
case "linechart":
output.lineWidth = 2;
output.hAxis = {
baselineColor: 'transparent',
gridlines: { color: 'transparent' }
};
output.vAxis = {
viewWindow: { min: 0 }
};
if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") {
output.legend = "none";
output.chartArea = {
width: "85%"
};
}
if (this.dateFormat() && typeof this.dateFormat() === 'string') {
output.hAxis.format = this.dateFormat();
}
break;
case "piechart":
output.sliceVisibilityThreshold = 0.01;
break;
case "table":
break;
}
return output;
}
};
},{"../../core":18,"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59}],58:[function(require,module,exports){
/*!
* ----------------------
* Keen IO Adapter
* ----------------------
*/
var Keen = require("../../core"),
Dataviz = require("../dataviz");
var clone = require("../../core/utils/clone"),
each = require("../../core/utils/each"),
extend = require("../../core/utils/extend"),
prettyNumber = require("../utils/prettyNumber");
module.exports = function(){
var Metric, Error, Spinner;
Keen.Error = {
defaults: {
backgroundColor : "",
borderRadius : "4px",
color : "#ccc",
display : "block",
fontFamily : "Helvetica Neue, Helvetica, Arial, sans-serif",
fontSize : "21px",
fontWeight : "light",
textAlign : "center"
}
};
Keen.Spinner.defaults = {
height: 138,
lines: 10,
length: 8,
width: 3,
radius: 10,
corners: 1,
rotate: 0,
direction: 1,
color: '#4d4d4d',
speed: 1.67,
trail: 60,
shadow: false,
hwaccel: false,
className: 'keen-spinner',
zIndex: 2e9,
top: '50%',
left: '50%'
};
var dataTypes = {
'singular': ['metric']
};
Metric = {
initialize: function(){
var css = document.createElement("style"),
bgDefault = "#49c5b1";
css.id = "keen-widgets";
css.type = "text/css";
css.innerHTML = "\
.keen-metric { \n background: " + bgDefault + "; \n border-radius: 4px; \n color: #fff; \n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; \n padding: 10px 0; \n text-align: center; \n} \
.keen-metric-value { \n display: block; \n font-size: 84px; \n font-weight: 700; \n line-height: 84px; \n} \
.keen-metric-title { \n display: block; \n font-size: 24px; \n font-weight: 200; \n}";
if (!document.getElementById(css.id)) {
document.body.appendChild(css);
}
},
render: function(){
var bgColor = (this.colors().length == 1) ? this.colors()[0] : "#49c5b1",
title = this.title() || "Result",
value = (this.data()[1] && this.data()[1][1]) ? this.data()[1][1] : 0,
width = this.width(),
opts = this.chartOptions() || {},
prefix = "",
suffix = "";
var styles = {
'width': (width) ? width + 'px' : 'auto'
};
var formattedNum = value;
if ( typeof opts.prettyNumber === 'undefined' || opts.prettyNumber == true ) {
if ( !isNaN(parseInt(value)) ) {
formattedNum = prettyNumber(value);
}
}
if (opts['prefix']) {
prefix = '<span class="keen-metric-prefix">' + opts['prefix'] + '</span>';
}
if (opts['suffix']) {
suffix = '<span class="keen-metric-suffix">' + opts['suffix'] + '</span>';
}
this.el().innerHTML = '' +
'<div class="keen-widget keen-metric" style="background-color: ' + bgColor + '; width:' + styles.width + ';" title="' + value + '">' +
'<span class="keen-metric-value">' + prefix + formattedNum + suffix + '</span>' +
'<span class="keen-metric-title">' + title + '</span>' +
'</div>';
}
};
Error = {
initialize: function(){},
render: function(text, style){
var err, msg;
var defaultStyle = clone(Keen.Error.defaults);
var currentStyle = extend(defaultStyle, style);
err = document.createElement("div");
err.className = "keen-error";
each(currentStyle, function(value, key){
err.style[key] = value;
});
err.style.height = String(this.height() + "px");
err.style.paddingTop = (this.height() / 2 - 15) + "px";
err.style.width = String(this.width() + "px");
msg = document.createElement("span");
msg.innerHTML = text || "Yikes! An error occurred!";
err.appendChild(msg);
this.el().innerHTML = "";
this.el().appendChild(err);
},
destroy: function(){
this.el().innerHTML = "";
}
};
Spinner = {
initialize: function(){},
render: function(){
var spinner = document.createElement("div");
var height = this.height() || Keen.Spinner.defaults.height;
spinner.className = "keen-loading";
spinner.style.height = String(height + "px");
spinner.style.position = "relative";
spinner.style.width = String(this.width() + "px");
this.el().innerHTML = "";
this.el().appendChild(spinner);
this.view._artifacts.spinner = new Keen.Spinner(Keen.Spinner.defaults).spin(spinner);
},
destroy: function(){
this.view._artifacts.spinner.stop();
this.view._artifacts.spinner = null;
}
};
Keen.Dataviz.register('keen-io', {
'metric': Metric,
'error': Error,
'spinner': Spinner
}, {
capabilities: dataTypes
});
};
},{"../../core":18,"../../core/utils/clone":30,"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59,"../utils/prettyNumber":98}],59:[function(require,module,exports){
var clone = require('../core/utils/clone'),
each = require('../core/utils/each'),
extend = require('../core/utils/extend'),
loadScript = require('./utils/loadScript'),
loadStyle = require('./utils/loadStyle');
var Keen = require('../core');
var Emitter = require('../core/utils/emitter-shim');
var Dataset = require('../dataset');
function Dataviz(){
this.dataset = new Dataset();
this.view = {
_prepared: false,
_initialized: false,
_rendered: false,
_artifacts: { /* state bin */ },
adapter: {
library: undefined,
chartOptions: {},
chartType: undefined,
defaultChartType: undefined,
dataType: undefined
},
attributes: clone(Dataviz.defaults),
defaults: clone(Dataviz.defaults),
el: undefined,
loader: { library: 'keen-io', chartType: 'spinner' }
};
Dataviz.visuals.push(this);
};
extend(Dataviz, {
dataTypeMap: {
'singular': { library: 'keen-io', chartType: 'metric' },
'categorical': { library: 'google', chartType: 'piechart' },
'cat-interval': { library: 'google', chartType: 'columnchart' },
'cat-ordinal': { library: 'google', chartType: 'barchart' },
'chronological': { library: 'google', chartType: 'areachart' },
'cat-chronological': { library: 'google', chartType: 'linechart' },
'extraction': { library: 'google', chartType: 'table' },
'nominal': { library: 'google', chartType: 'table' }
},
defaults: {
colors: [
/* teal red yellow purple orange mint blue green lavender */
'#00bbde', '#fe6672', '#eeb058', '#8a8ad6', '#ff855c', '#00cfbb', '#5a9eed', '#73d483', '#c879bb',
'#0099b6', '#d74d58', '#cb9141', '#6b6bb6', '#d86945', '#00aa99', '#4281c9', '#57b566', '#ac5c9e',
'#27cceb', '#ff818b', '#f6bf71', '#9b9be1', '#ff9b79', '#26dfcd', '#73aff4', '#87e096', '#d88bcb'
],
indexBy: 'timeframe.start',
stacked: false
},
dependencies: {
loading: 0,
loaded: 0,
urls: {}
},
libraries: {},
visuals: []
});
Emitter(Dataviz);
Emitter(Dataviz.prototype);
Dataviz.register = function(name, methods, config){
var self = this;
var loadHandler = function(st) {
st.loaded++;
if(st.loaded === st.loading) {
Keen.loaded = true;
Keen.trigger('ready');
}
};
Dataviz.libraries[name] = Dataviz.libraries[name] || {};
each(methods, function(method, key){
Dataviz.libraries[name][key] = method;
});
if (config && config.capabilities) {
Dataviz.libraries[name]._defaults = Dataviz.libraries[name]._defaults || {};
each(config.capabilities, function(typeSet, key){
Dataviz.libraries[name]._defaults[key] = typeSet;
});
}
if (config && config.dependencies) {
each(config.dependencies, function (dependency, index, collection) {
var status = Dataviz.dependencies;
if(!status.urls[dependency.url]) {
status.urls[dependency.url] = true;
status.loading++;
var method = dependency.type === 'script' ? loadScript : loadStyle;
method(dependency.url, function() {
if(dependency.cb) {
dependency.cb.call(self, function() {
loadHandler(status);
});
} else {
loadHandler(status);
}
});
}
});
}
};
Dataviz.find = function(target){
if (!arguments.length) return Dataviz.visuals;
var el = target.nodeName ? target : document.querySelector(target),
match;
each(Dataviz.visuals, function(visual){
if (el == visual.el()){
match = visual;
return false;
}
});
if (match) return match;
};
module.exports = Dataviz;
},{"../core":18,"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/emitter-shim":32,"../core/utils/extend":33,"../dataset":39,"./utils/loadScript":96,"./utils/loadStyle":97}],60:[function(require,module,exports){
var clone = require("../../core/utils/clone"),
extend = require("../../core/utils/extend"),
Dataviz = require("../dataviz"),
Request = require("../../core/request");
module.exports = function(query, el, cfg) {
var DEFAULTS = clone(Dataviz.defaults),
visual = new Dataviz(),
request = new Request(this, [query]),
config = cfg || {};
visual
.attributes(extend(DEFAULTS, config))
.el(el)
.prepare();
request.refresh();
request.on("complete", function(){
visual
.parseRequest(this)
.call(function(){
if (config.labels) {
this.labels(config.labels);
}
})
.render();
});
request.on("error", function(res){
visual.error(res.message);
});
return visual;
};
},{"../../core/request":27,"../../core/utils/clone":30,"../../core/utils/extend":33,"../dataviz":59}],61:[function(require,module,exports){
var Dataviz = require("../dataviz"),
extend = require("../../core/utils/extend")
module.exports = function(){
var map = extend({}, Dataviz.dataTypeMap),
dataType = this.dataType(),
library = this.library(),
chartType = this.chartType() || this.defaultChartType();
if (!library && map[dataType]) {
library = map[dataType].library;
}
if (library && !chartType && dataType) {
chartType = Dataviz.libraries[library]._defaults[dataType][0];
}
if (library && !chartType && map[dataType]) {
chartType = map[dataType].chartType;
}
if (library && chartType && Dataviz.libraries[library][chartType]) {
return Dataviz.libraries[library][chartType];
}
else {
return {};
}
};
},{"../../core/utils/extend":33,"../dataviz":59}],62:[function(require,module,exports){
module.exports = function(req){
var analysis = req.queries[0].analysis.replace("_", " "),
collection = req.queries[0].get('event_collection'),
output;
output = analysis.replace( /\b./g, function(a){
return a.toUpperCase();
});
if (collection) {
output += ' - ' + collection;
}
return output;
};
},{}],63:[function(require,module,exports){
module.exports = function(query){
var isInterval = typeof query.params.interval === "string",
isGroupBy = typeof query.params.group_by === "string",
is2xGroupBy = query.params.group_by instanceof Array,
dataType;
if (!isGroupBy && !isInterval) {
dataType = 'singular';
}
if (isGroupBy && !isInterval) {
dataType = 'categorical';
}
if (isInterval && !isGroupBy) {
dataType = 'chronological';
}
if (isInterval && isGroupBy) {
dataType = 'cat-chronological';
}
if (!isInterval && is2xGroupBy) {
dataType = 'categorical';
}
if (isInterval && is2xGroupBy) {
dataType = 'cat-chronological';
}
if (query.analysis === "funnel") {
dataType = 'cat-ordinal';
}
if (query.analysis === "extraction") {
dataType = 'extraction';
}
if (query.analysis === "select_unique") {
dataType = 'nominal';
}
return dataType;
};
},{}],64:[function(require,module,exports){
var extend = require('../core/utils/extend'),
Dataviz = require('./dataviz');
extend(Dataviz.prototype, {
'adapter' : require('./lib/adapter'),
'attributes' : require('./lib/attributes'),
'call' : require('./lib/call'),
'chartOptions' : require('./lib/chartOptions'),
'chartType' : require('./lib/chartType'),
'colorMapping' : require('./lib/colorMapping'),
'colors' : require('./lib/colors'),
'data' : require('./lib/data'),
'dataType' : require('./lib/dataType'),
'dateFormat' : require('./lib/dateFormat'),
'defaultChartType' : require('./lib/defaultChartType'),
'el' : require('./lib/el'),
'height' : require('./lib/height'),
'indexBy' : require('./lib/indexBy'),
'labelMapping' : require('./lib/labelMapping'),
'labels' : require('./lib/labels'),
'library' : require('./lib/library'),
'parseRawData' : require('./lib/parseRawData'),
'parseRequest' : require('./lib/parseRequest'),
'prepare' : require('./lib/prepare'),
'sortGroups' : require('./lib/sortGroups'),
'sortIntervals' : require('./lib/sortIntervals'),
'stacked' : require('./lib/stacked'),
'title' : require('./lib/title'),
'width' : require('./lib/width')
});
extend(Dataviz.prototype, {
'destroy' : require('./lib/actions/destroy'),
'error' : require('./lib/actions/error'),
'initialize' : require('./lib/actions/initialize'),
'render' : require('./lib/actions/render'),
'update' : require('./lib/actions/update')
});
module.exports = Dataviz;
},{"../core/utils/extend":33,"./dataviz":59,"./lib/actions/destroy":65,"./lib/actions/error":66,"./lib/actions/initialize":67,"./lib/actions/render":68,"./lib/actions/update":69,"./lib/adapter":70,"./lib/attributes":71,"./lib/call":72,"./lib/chartOptions":73,"./lib/chartType":74,"./lib/colorMapping":75,"./lib/colors":76,"./lib/data":77,"./lib/dataType":78,"./lib/dateFormat":79,"./lib/defaultChartType":80,"./lib/el":81,"./lib/height":82,"./lib/indexBy":83,"./lib/labelMapping":84,"./lib/labels":85,"./lib/library":86,"./lib/parseRawData":87,"./lib/parseRequest":88,"./lib/prepare":89,"./lib/sortGroups":90,"./lib/sortIntervals":91,"./lib/stacked":92,"./lib/title":93,"./lib/width":94}],65:[function(require,module,exports){
var getAdapterActions = require("../../helpers/getAdapterActions");
module.exports = function(){
var actions = getAdapterActions.call(this);
if (actions.destroy) {
actions.destroy.apply(this, arguments);
}
if (this.el()) {
this.el().innerHTML = "";
}
this.view._prepared = false;
this.view._initialized = false;
this.view._rendered = false;
this.view._artifacts = {};
return this;
};
},{"../../helpers/getAdapterActions":61}],66:[function(require,module,exports){
var getAdapterActions = require("../../helpers/getAdapterActions"),
Dataviz = require("../../dataviz");
module.exports = function(){
var actions = getAdapterActions.call(this);
if (this.el()) {
if (actions['error']) {
actions['error'].apply(this, arguments);
} else {
Dataviz.libraries['keen-io']['error'].render.apply(this, arguments);
}
}
else {
this.emit('error', 'No DOM element provided');
}
return this;
};
},{"../../dataviz":59,"../../helpers/getAdapterActions":61}],67:[function(require,module,exports){
var getAdapterActions = require("../../helpers/getAdapterActions"),
Dataviz = require("../../dataviz");
module.exports = function(){
var actions = getAdapterActions.call(this);
var loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType];
if (this.view._prepared) {
if (loader.destroy) loader.destroy.apply(this, arguments);
} else {
if (this.el()) this.el().innerHTML = "";
}
if (actions.initialize) {
actions.initialize.apply(this, arguments);
}
else {
this.error('Incorrect chartType');
this.emit('error', 'Incorrect chartType');
}
this.view._initialized = true;
return this;
};
},{"../../dataviz":59,"../../helpers/getAdapterActions":61}],68:[function(require,module,exports){
var getAdapterActions = require("../../helpers/getAdapterActions"),
applyTransforms = require("../../utils/applyTransforms");
module.exports = function(){
var actions = getAdapterActions.call(this);
applyTransforms.call(this);
if (!this.view._initialized) {
this.initialize();
}
if (this.el() && actions.render) {
actions.render.apply(this, arguments);
this.view._rendered = true;
}
return this;
};
},{"../../helpers/getAdapterActions":61,"../../utils/applyTransforms":95}],69:[function(require,module,exports){
var getAdapterActions = require("../../helpers/getAdapterActions"),
applyTransforms = require("../../utils/applyTransforms");
module.exports = function(){
var actions = getAdapterActions.call(this);
applyTransforms.call(this);
if (actions.update) {
actions.update.apply(this, arguments);
} else if (actions.render) {
this.render();
}
return this;
};
},{"../../helpers/getAdapterActions":61,"../../utils/applyTransforms":95}],70:[function(require,module,exports){
var each = require("../../core/utils/each");
module.exports = function(obj){
if (!arguments.length) return this.view.adapter;
var self = this;
each(obj, function(prop, key){
self.view.adapter[key] = (prop ? prop : null);
});
return this;
};
},{"../../core/utils/each":31}],71:[function(require,module,exports){
var each = require("../../core/utils/each");
var chartOptions = require("./chartOptions")
chartType = require("./chartType"),
library = require("./library");
module.exports = function(obj){
if (!arguments.length) return this.view["attributes"];
var self = this;
each(obj, function(prop, key){
if (key === "library") {
library.call(self, prop);
}
else if (key === "chartType") {
chartType.call(self, prop);
}
else if (key === "chartOptions") {
chartOptions.call(self, prop);
}
else {
self.view["attributes"][key] = prop;
}
});
return this;
};
},{"../../core/utils/each":31,"./chartOptions":73,"./chartType":74,"./library":86}],72:[function(require,module,exports){
module.exports = function(fn){
fn.call(this);
return this;
};
},{}],73:[function(require,module,exports){
var extend = require('../../core/utils/extend');
module.exports = function(obj){
if (!arguments.length) return this.view.adapter.chartOptions;
if (typeof obj === 'object' && obj !== null) {
extend(this.view.adapter.chartOptions, obj);
}
else {
this.view.adapter.chartOptions = {};
}
return this;
};
},{"../../core/utils/extend":33}],74:[function(require,module,exports){
module.exports = function(str){
if (!arguments.length) return this.view.adapter.chartType;
this.view.adapter.chartType = (str ? String(str) : null);
return this;
};
},{}],75:[function(require,module,exports){
var each = require("../../core/utils/each");
module.exports = function(obj){
if (!arguments.length) return this.view["attributes"].colorMapping;
this.view["attributes"].colorMapping = (obj ? obj : null);
colorMapping.call(this);
return this;
};
function colorMapping(){
var self = this,
schema = this.dataset.schema,
data = this.dataset.output(),
colorSet = this.view.defaults.colors.slice(),
colorMap = this.colorMapping(),
dt = this.dataType() || "";
if (colorMap) {
if (dt.indexOf("chronological") > -1 || (schema.unpack && data[0].length > 2)) {
each(data[0].slice(1), function(label, i){
var color = colorMap[label];
if (color && colorSet[i] !== color) {
colorSet.splice(i, 0, color);
}
});
}
else {
each(self.dataset.selectColumn(0).slice(1), function(label, i){
var color = colorMap[label];
if (color && colorSet[i] !== color) {
colorSet.splice(i, 0, color);
}
});
}
self.view.attributes.colors = colorSet;
}
}
},{"../../core/utils/each":31}],76:[function(require,module,exports){
module.exports = function(arr){
if (!arguments.length) return this.view["attributes"].colors;
this.view["attributes"].colors = (arr instanceof Array ? arr : null);
this.view.defaults.colors = (arr instanceof Array ? arr : null);
return this;
};
},{}],77:[function(require,module,exports){
var Dataset = require("../../dataset"),
Request = require("../../core/request");
module.exports = function(data){
if (!arguments.length) return this.dataset.output();
if (data instanceof Dataset) {
this.dataset = data;
} else if (data instanceof Request) {
this.parseRequest(data);
} else {
this.parseRawData(data);
}
return this;
};
},{"../../core/request":27,"../../dataset":39}],78:[function(require,module,exports){
module.exports = function(str){
if (!arguments.length) return this.view.adapter.dataType;
this.view.adapter.dataType = (str ? String(str) : null);
return this;
};
},{}],79:[function(require,module,exports){
module.exports = function(val){
if (!arguments.length) return this.view.attributes.dateFormat;
if (typeof val === 'string' || typeof val === 'function') {
this.view.attributes.dateFormat = val;
}
else {
this.view.attributes.dateFormat = undefined;
}
return this;
};
},{}],80:[function(require,module,exports){
module.exports = function(str){
if (!arguments.length) return this.view.adapter.defaultChartType;
this.view.adapter.defaultChartType = (str ? String(str) : null);
return this;
};
},{}],81:[function(require,module,exports){
module.exports = function(el){
if (!arguments.length) return this.view.el;
this.view.el = el;
return this;
};
},{}],82:[function(require,module,exports){
module.exports = function(num){
if (!arguments.length) return this.view["attributes"]["height"];
this.view["attributes"]["height"] = (!isNaN(parseInt(num)) ? parseInt(num) : null);
return this;
};
},{}],83:[function(require,module,exports){
var Dataset = require('../../dataset'),
Dataviz = require('../dataviz'),
each = require('../../core/utils/each');
module.exports = function(str){
if (!arguments.length) return this.view['attributes'].indexBy;
this.view['attributes'].indexBy = (str ? String(str) : Dataviz.defaults.indexBy);
indexBy.call(this);
return this;
};
function indexBy(){
var parser, options;
if (this.dataset.output().length > 1
&& !isNaN(new Date(this.dataset.output()[1][0]).getTime())) {
if (this.dataset.parser
&& this.dataset.parser.name
&& this.dataset.parser.options) {
if (this.dataset.parser.options.length === 1) {
parser = Dataset.parser(this.dataset.parser.name, this.indexBy());
this.dataset.parser.options[0] = this.indexBy();
}
else {
parser = Dataset.parser(this.dataset.parser.name, this.dataset.parser.options[0], this.indexBy());
this.dataset.parser.options[1] = this.indexBy();
}
}
else if (this.dataset.output()[0].length === 2) {
parser = Dataset.parser('interval', this.indexBy());
this.dataset.parser = {
name: 'interval',
options: [this.indexBy()]
};
}
else {
parser = Dataset.parser('grouped-interval', this.indexBy());
this.dataset.parser = {
name: 'grouped-interval',
options: [this.indexBy()]
};
}
this.dataset = parser(this.dataset.input());
this.dataset.updateColumn(0, function(value){
return (typeof value === 'string') ? new Date(value) : value;
});
}
}
},{"../../core/utils/each":31,"../../dataset":39,"../dataviz":59}],84:[function(require,module,exports){
var each = require("../../core/utils/each");
module.exports = function(obj){
if (!arguments.length) return this.view["attributes"].labelMapping;
this.view["attributes"].labelMapping = (obj ? obj : null);
applyLabelMapping.call(this);
return this;
};
function applyLabelMapping(){
var self = this,
labelMap = this.labelMapping(),
dt = this.dataType() || "";
if (labelMap) {
if (dt.indexOf("chronological") > -1 || (self.dataset.output()[0].length > 2)) {
each(self.dataset.output()[0], function(c, i){
if (i > 0) {
self.dataset.data.output[0][i] = labelMap[c] || c;
}
});
}
else if (self.dataset.output()[0].length === 2) {
self.dataset.updateColumn(0, function(c, i){
return labelMap[c] || c;
});
}
}
}
},{"../../core/utils/each":31}],85:[function(require,module,exports){
var each = require('../../core/utils/each');
module.exports = function(arr){
if (!arguments.length) {
if (!this.view['attributes'].labels || !this.view['attributes'].labels.length) {
return getLabels.call(this);
}
else {
return this.view['attributes'].labels;
}
}
else {
this.view['attributes'].labels = (arr instanceof Array ? arr : null);
setLabels.call(this);
return this;
}
};
function setLabels(){
var self = this,
labelSet = this.labels() || null,
data = this.dataset.output(),
dt = this.dataType() || '';
if (labelSet) {
if (dt.indexOf('chronological') > -1 || (data[0].length > 2)) {
each(data[0], function(cell,i){
if (i > 0 && labelSet[i-1]) {
self.dataset.data.output[0][i] = labelSet[i-1];
}
});
}
else {
each(data, function(row,i){
if (i > 0 && labelSet[i-1]) {
self.dataset.data.output[i][0] = labelSet[i-1];
}
});
}
}
}
function getLabels(){
var data = this.dataset.output(),
dt = this.dataType() || '',
labels;
if (dt.indexOf('chron') > -1 || (data[0].length > 2)) {
labels = this.dataset.selectRow(0).slice(1);
}
else {
labels = this.dataset.selectColumn(0).slice(1);
}
return labels;
}
},{"../../core/utils/each":31}],86:[function(require,module,exports){
module.exports = function(str){
if (!arguments.length) return this.view.adapter.library;
this.view.adapter.library = (str ? String(str) : null);
return this;
};
},{}],87:[function(require,module,exports){
var Dataset = require('../../dataset');
var extend = require('../../core/utils/extend');
module.exports = function(response){
var dataType,
indexBy = this.indexBy() ? this.indexBy() : 'timestamp.start',
parser,
parserArgs = [],
query = (typeof response.query !== 'undefined') ? response.query : {};
query = extend({
analysis_type: null,
event_collection: null,
filters: [],
group_by: null,
interval: null,
timeframe: null,
timezone: null
}, query);
if (query.analysis_type === 'funnel') {
dataType = 'cat-ordinal';
parser = 'funnel';
}
else if (query.analysis_type === 'extraction'){
dataType = 'extraction';
parser = 'extraction';
}
else if (query.analysis_type === 'select_unique') {
if (!query.group_by && !query.interval) {
dataType = 'nominal';
parser = 'list';
}
}
else if (query.analysis_type) {
if (!query.group_by && !query.interval) {
dataType = 'singular';
parser = 'metric';
}
else if (query.group_by && !query.interval) {
if (query.group_by instanceof Array && query.group_by.length > 1) {
dataType = 'categorical';
parser = 'double-grouped-metric';
parserArgs.push(query.group_by);
}
else {
dataType = 'categorical';
parser = 'grouped-metric';
}
}
else if (query.interval && !query.group_by) {
dataType = 'chronological';
parser = 'interval';
parserArgs.push(indexBy);
}
else if (query.group_by && query.interval) {
if (query.group_by instanceof Array && query.group_by.length > 1) {
dataType = 'cat-chronological';
parser = 'double-grouped-interval';
parserArgs.push(query.group_by);
parserArgs.push(indexBy);
}
else {
dataType = 'cat-chronological';
parser = 'grouped-interval';
parserArgs.push(indexBy);
}
}
}
if (!parser) {
if (typeof response.result === 'number'){
dataType = 'singular';
parser = 'metric';
}
if (response.result instanceof Array && response.result.length > 0){
if (response.result[0].timeframe && (typeof response.result[0].value == 'number' || response.result[0].value == null)) {
dataType = 'chronological';
parser = 'interval';
parserArgs.push(indexBy)
}
if (typeof response.result[0].result == 'number'){
dataType = 'categorical';
parser = 'grouped-metric';
}
if (response.result[0].value instanceof Array){
dataType = 'cat-chronological';
parser = 'grouped-interval';
parserArgs.push(indexBy)
}
if (typeof response.result[0] == 'number' && typeof response.steps !== "undefined"){
dataType = 'cat-ordinal';
parser = 'funnel';
}
if ((typeof response.result[0] == 'string' || typeof response.result[0] == 'number') && typeof response.steps === "undefined"){
dataType = 'nominal';
parser = 'list';
}
if (dataType === void 0) {
dataType = 'extraction';
parser = 'extraction';
}
}
}
if (dataType) {
this.dataType(dataType);
}
this.dataset = Dataset.parser.apply(this, [parser].concat(parserArgs))(response);
if (parser.indexOf('interval') > -1) {
this.dataset.updateColumn(0, function(value, i){
return new Date(value);
});
}
return this;
};
},{"../../core/utils/extend":33,"../../dataset":39}],88:[function(require,module,exports){
var Query = require('../../core/query');
var dataType = require('./dataType'),
extend = require('../../core/utils/extend'),
getDefaultTitle = require('../helpers/getDefaultTitle'),
getQueryDataType = require('../helpers/getQueryDataType'),
parseRawData = require('./parseRawData'),
title = require('./title');
module.exports = function(req){
var response = req.data instanceof Array ? req.data[0] : req.data;
if (req.queries[0] instanceof Query) {
response.query = extend({
analysis_type: req.queries[0].analysis
}, req.queries[0].params);
dataType.call(this, getQueryDataType(req.queries[0]));
this.view.defaults.title = getDefaultTitle.call(this, req);
if (!title.call(this)) {
title.call(this, this.view.defaults.title);
}
}
parseRawData.call(this, response);
return this;
};
},{"../../core/query":26,"../../core/utils/extend":33,"../helpers/getDefaultTitle":62,"../helpers/getQueryDataType":63,"./dataType":78,"./parseRawData":87,"./title":93}],89:[function(require,module,exports){
var Dataviz = require("../dataviz");
module.exports = function(){
var loader;
if (this.view._rendered) {
this.destroy();
}
if (this.el()) {
this.el().innerHTML = "";
loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType];
if (loader.initialize) {
loader.initialize.apply(this, arguments);
}
if (loader.render) {
loader.render.apply(this, arguments);
}
this.view._prepared = true;
}
return this;
};
},{"../dataviz":59}],90:[function(require,module,exports){
module.exports = function(str){
if (!arguments.length) return this.view["attributes"].sortGroups;
this.view["attributes"].sortGroups = (str ? String(str) : null);
runSortGroups.call(this);
return this;
};
function runSortGroups(){
var dt = this.dataType();
if (!this.sortGroups()) return;
if ((dt && dt.indexOf("chronological") > -1) || this.data()[0].length > 2) {
this.dataset.sortColumns(this.sortGroups(), this.dataset.getColumnSum);
}
else if (dt && (dt.indexOf("cat-") > -1 || dt.indexOf("categorical") > -1)) {
this.dataset.sortRows(this.sortGroups(), this.dataset.getRowSum);
}
return;
}
},{}],91:[function(require,module,exports){
module.exports = function(str){
if (!arguments.length) return this.view["attributes"].sortIntervals;
this.view["attributes"].sortIntervals = (str ? String(str) : null);
runSortIntervals.call(this);
return this;
};
function runSortIntervals(){
if (!this.sortIntervals()) return;
this.dataset.sortRows(this.sortIntervals());
return;
}
},{}],92:[function(require,module,exports){
module.exports = function(bool){
if (!arguments.length) return this.view['attributes']['stacked'];
this.view['attributes']['stacked'] = bool ? true : false;
return this;
};
},{}],93:[function(require,module,exports){
module.exports = function(str){
if (!arguments.length) return this.view["attributes"]["title"];
this.view["attributes"]["title"] = (str ? String(str) : null);
return this;
};
},{}],94:[function(require,module,exports){
module.exports = function(num){
if (!arguments.length) return this.view["attributes"]["width"];
this.view["attributes"]["width"] = (!isNaN(parseInt(num)) ? parseInt(num) : null);
return this;
};
},{}],95:[function(require,module,exports){
module.exports = function(){
if (this.labelMapping()) {
this.labelMapping(this.labelMapping());
}
if (this.colorMapping()) {
this.colorMapping(this.colorMapping());
}
if (this.sortGroups()) {
this.sortGroups(this.sortGroups());
}
if (this.sortIntervals()) {
this.sortIntervals(this.sortIntervals());
}
};
},{}],96:[function(require,module,exports){
module.exports = function(url, cb) {
var doc = document;
var handler;
var head = doc.head || doc.getElementsByTagName("head");
setTimeout(function () {
if ('item' in head) {
if (!head[0]) {
setTimeout(arguments.callee, 25);
return;
}
head = head[0];
}
var script = doc.createElement("script"),
scriptdone = false;
script.onload = script.onreadystatechange = function () {
if ((script.readyState && script.readyState !== "complete" && script.readyState !== "loaded") || scriptdone) {
return false;
}
script.onload = script.onreadystatechange = null;
scriptdone = true;
cb();
};
script.src = url;
head.insertBefore(script, head.firstChild);
}, 0);
if (doc.readyState === null && doc.addEventListener) {
doc.readyState = "loading";
doc.addEventListener("DOMContentLoaded", handler = function () {
doc.removeEventListener("DOMContentLoaded", handler, false);
doc.readyState = "complete";
}, false);
}
};
},{}],97:[function(require,module,exports){
module.exports = function(url, cb) {
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.href = url;
cb();
document.head.appendChild(link);
};
},{}],98:[function(require,module,exports){
module.exports = function(_input) {
var input = Number(_input),
sciNo = input.toPrecision(3),
prefix = "",
suffixes = ["", "k", "M", "B", "T"];
if (Number(sciNo) == input && String(input).length <= 4) {
return String(input);
}
if(input >= 1 || input <= -1) {
if(input < 0){
input = -input;
prefix = "-";
}
return prefix + recurse(input, 0);
} else {
return input.toPrecision(3);
}
function recurse(input, iteration) {
var input = String(input);
var split = input.split(".");
if(split.length > 1) {
input = split[0];
var rhs = split[1];
if (input.length == 2 && rhs.length > 0) {
if (rhs.length > 0) {
input = input + "." + rhs.charAt(0);
}
else {
input += "0";
}
}
else if (input.length == 1 && rhs.length > 0) {
input = input + "." + rhs.charAt(0);
if(rhs.length > 1) {
input += rhs.charAt(1);
}
else {
input += "0";
}
}
}
var numNumerals = input.length;
if (input.split(".").length > 1) {
numNumerals--;
}
if(numNumerals <= 3) {
return String(input) + suffixes[iteration];
}
else {
return recurse(Number(input) / 1000, iteration + 1);
}
}
};
},{}],99:[function(require,module,exports){
(function (global){
;(function (f) {
if (typeof define === "function" && define.amd) {
define("keen", [], function(){ return f(); });
}
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f();
}
var g = null;
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
}
if (g) {
g.Keen = f();
}
})(function() {
"use strict";
var Keen = require("./core"),
extend = require("./core/utils/extend");
extend(Keen.prototype, {
"addEvent" : require("./core/lib/addEvent"),
"addEvents" : require("./core/lib/addEvents"),
"setGlobalProperties" : require("./core/lib/setGlobalProperties"),
"trackExternalLink" : require("./core/lib/trackExternalLink"),
"get" : require("./core/lib/get"),
"post" : require("./core/lib/post"),
"put" : require("./core/lib/post"),
"run" : require("./core/lib/run"),
"savedQueries" : require("./core/saved-queries"),
"draw" : require("./dataviz/extensions/draw")
});
Keen.Query = require("./core/query");
Keen.Request = require("./core/request");
Keen.Dataset = require("./dataset");
Keen.Dataviz = require("./dataviz");
Keen.Base64 = require("./core/utils/base64");
Keen.Spinner = require("spin.js");
Keen.utils = {
"domready" : require("domready"),
"each" : require("./core/utils/each"),
"extend" : extend,
"parseParams" : require("./core/utils/parseParams"),
"prettyNumber" : require("./dataviz/utils/prettyNumber")
};
require("./dataviz/adapters/keen-io")();
require("./dataviz/adapters/google")();
require("./dataviz/adapters/c3")();
require("./dataviz/adapters/chartjs")();
if (Keen.loaded) {
setTimeout(function(){
Keen.utils.domready(function(){
Keen.emit("ready");
});
}, 0);
}
require("./core/async")();
module.exports = Keen;
return Keen;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./core":18,"./core/async":10,"./core/lib/addEvent":19,"./core/lib/addEvents":20,"./core/lib/get":21,"./core/lib/post":22,"./core/lib/run":23,"./core/lib/setGlobalProperties":24,"./core/lib/trackExternalLink":25,"./core/query":26,"./core/request":27,"./core/saved-queries":28,"./core/utils/base64":29,"./core/utils/each":31,"./core/utils/extend":33,"./core/utils/parseParams":35,"./dataset":39,"./dataviz":64,"./dataviz/adapters/c3":54,"./dataviz/adapters/chartjs":56,"./dataviz/adapters/google":57,"./dataviz/adapters/keen-io":58,"./dataviz/extensions/draw":60,"./dataviz/utils/prettyNumber":98,"domready":2,"spin.js":5}]},{},[99]);
|
keicheng/cdnjs
|
ajax/libs/keen-js/3.4.1/keen.js
|
JavaScript
|
mit
| 186,623 |
๏ปฟ/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.lang} object, for the
* Latvian language.
*/
/**#@+
@type String
@example
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang['lv'] =
{
/**
* The language reading direction. Possible values are "rtl" for
* Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right
* languages (like English).
* @default 'ltr'
*/
dir : 'ltr',
/*
* Screenreader titles. Please note that screenreaders are not always capable
* of reading non-English words. So be careful while translating it.
*/
editorTitle : 'Rich text editor, %1, press ALT 0 for help.', // MISSING
// ARIA descriptions.
toolbars : 'Editor toolbars', // MISSING
editor : 'Rich Text Editor', // MISSING
// Toolbar buttons without dialogs.
source : 'HTML kods',
newPage : 'Jauna lapa',
save : 'Saglabฤt',
preview : 'Pฤrskatฤซt',
cut : 'Izgriezt',
copy : 'Kopฤt',
paste : 'Ievietot',
print : 'Drukฤt',
underline : 'Apakลกsvฤซtra',
bold : 'Treknu ลกriftu',
italic : 'Slฤซprakstฤ',
selectAll : 'Iezฤซmฤt visu',
removeFormat : 'Noลemt stilus',
strike : 'Pฤrsvฤซtrots',
subscript : 'Zemrakstฤ',
superscript : 'Augลกrakstฤ',
horizontalrule : 'Ievietot horizontฤlu Atdalฤซtฤjsvฤซtru',
pagebreak : 'Ievietot lapas pฤrtraukumu',
pagebreakAlt : 'Page Break', // MISSING
unlink : 'Noลemt hipersaiti',
undo : 'Atcelt',
redo : 'Atkฤrtot',
// Common messages and labels.
common :
{
browseServer : 'Skatฤซt servera saturu',
url : 'URL',
protocol : 'Protokols',
upload : 'Augลกupielฤdฤt',
uploadSubmit : 'Nosลซtฤซt serverim',
image : 'Attฤls',
flash : 'Flash',
form : 'Forma',
checkbox : 'Atzฤซmฤลกanas kastฤซte',
radio : 'Izvฤles poga',
textField : 'Teksta rinda',
textarea : 'Teksta laukums',
hiddenField : 'Paslฤpta teksta rinda',
button : 'Poga',
select : 'Iezฤซmฤลกanas lauks',
imageButton : 'Attฤlpoga',
notSet : '<nav iestatฤซts>',
id : 'Id',
name : 'Nosaukums',
langDir : 'Valodas lasฤซลกanas virziens',
langDirLtr : 'No kreisฤs uz labo (LTR)',
langDirRtl : 'No labฤs uz kreiso (RTL)',
langCode : 'Valodas kods',
longDescr : 'Gara apraksta Hipersaite',
cssClass : 'Stilu saraksta klases',
advisoryTitle : 'Konsultatฤซvs virsraksts',
cssStyle : 'Stils',
ok : 'Darฤซts!',
cancel : 'Atcelt',
close : 'Close', // MISSING
preview : 'Preview', // MISSING
generalTab : 'General', // MISSING
advancedTab : 'Izvฤrstais',
validateNumberFailed : 'This value is not a number.', // MISSING
confirmNewPage : 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
options : 'Options', // MISSING
target : 'Target', // MISSING
targetNew : 'New Window (_blank)', // MISSING
targetTop : 'Topmost Window (_top)', // MISSING
targetSelf : 'Same Window (_self)', // MISSING
targetParent : 'Parent Window (_parent)', // MISSING
langDirLTR : 'Left to Right (LTR)', // MISSING
langDirRTL : 'Right to Left (RTL)', // MISSING
styles : 'Style', // MISSING
cssClasses : 'Stylesheet Classes', // MISSING
width : 'Platums',
height : 'Augstums',
align : 'Nolฤซdzinฤt',
alignLeft : 'Pa kreisi',
alignRight : 'Pa labi',
alignCenter : 'Centrฤti',
alignTop : 'Augลกฤ',
alignMiddle : 'Vertikฤli centrฤts',
alignBottom : 'Apakลกฤ',
invalidHeight : 'Height must be a number.', // MISSING
invalidWidth : 'Width must be a number.', // MISSING
invalidCssLength : 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING
invalidHtmlLength : 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', // MISSING
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>' // MISSING
},
contextmenu :
{
options : 'Context Menu Options' // MISSING
},
// Special char dialog.
specialChar :
{
toolbar : 'Ievietot speciฤlo simbolu',
title : 'Ievietot ฤซpaลกu simbolu',
options : 'Special Character Options' // MISSING
},
// Link dialog.
link :
{
toolbar : 'Ievietot/Labot hipersaiti',
other : '<cits>',
menu : 'Labot hipersaiti',
title : 'Hipersaite',
info : 'Hipersaites informฤcija',
target : 'Mฤrฤทis',
upload : 'Augลกupielฤdฤt',
advanced : 'Izvฤrstais',
type : 'Hipersaites tips',
toUrl : 'URL', // MISSING
toAnchor : 'Iezฤซme ลกajฤ lapฤ',
toEmail : 'E-pasts',
targetFrame : '<ietvars>',
targetPopup : '<uznirstoลกฤ logฤ>',
targetFrameName : 'Mฤrฤทa ietvara nosaukums',
targetPopupName : 'Uznirstoลกฤ loga nosaukums',
popupFeatures : 'Uznirstoลกฤ loga nosaukums ฤซpaลกฤซbas',
popupResizable : 'Resizable', // MISSING
popupStatusBar : 'Statusa josla',
popupLocationBar: 'Atraลกanฤs vietas josla',
popupToolbar : 'Rฤซku josla',
popupMenuBar : 'Izvฤlnes josla',
popupFullScreen : 'Pilnฤ ekrฤnฤ (IE)',
popupScrollBars : 'Ritjoslas',
popupDependent : 'Atkarฤซgs (Netscape)',
popupLeft : 'Kreisฤ koordinฤte',
popupTop : 'Augลกฤjฤ koordinฤte',
id : 'Id', // MISSING
langDir : 'Valodas lasฤซลกanas virziens',
langDirLTR : 'No kreisฤs uz labo (LTR)',
langDirRTL : 'No labฤs uz kreiso (RTL)',
acccessKey : 'Pieejas kods',
name : 'Nosaukums',
langCode : 'Valodas lasฤซลกanas virziens',
tabIndex : 'Ciฤผลu indekss',
advisoryTitle : 'Konsultatฤซvs virsraksts',
advisoryContentType : 'Konsultatฤซvs satura tips',
cssClasses : 'Stilu saraksta klases',
charset : 'Pievienotฤ resursa kodu tabula',
styles : 'Stils',
rel : 'Relationship', // MISSING
selectAnchor : 'Izvฤlฤties iezฤซmi',
anchorName : 'Pฤc iezฤซmes nosaukuma',
anchorId : 'Pฤc elementa ID',
emailAddress : 'E-pasta adrese',
emailSubject : 'Ziลas tฤma',
emailBody : 'Ziลas saturs',
noAnchors : '(ล ajฤ dokumentฤ nav iezฤซmju)',
noUrl : 'Lลซdzu norฤdi hipersaiti',
noEmail : 'Lลซdzu norฤdi e-pasta adresi'
},
// Anchor dialog
anchor :
{
toolbar : 'Ievietot/Labot iezฤซmi',
menu : 'Iezฤซmes ฤซpaลกฤซbas',
title : 'Iezฤซmes ฤซpaลกฤซbas',
name : 'Iezฤซmes nosaukums',
errorName : 'Lลซdzu norฤdiet iezฤซmes nosaukumu',
remove : 'Remove Anchor' // MISSING
},
// List style dialog
list:
{
numberedTitle : 'Numbered List Properties', // MISSING
bulletedTitle : 'Bulleted List Properties', // MISSING
type : 'Type', // MISSING
start : 'Start', // MISSING
validateStartNumber :'List start number must be a whole number.', // MISSING
circle : 'Circle', // MISSING
disc : 'Disc', // MISSING
square : 'Square', // MISSING
none : 'None', // MISSING
notset : '<not set>', // MISSING
armenian : 'Armenian numbering', // MISSING
georgian : 'Georgian numbering (an, ban, gan, etc.)', // MISSING
lowerRoman : 'Lower Roman (i, ii, iii, iv, v, etc.)', // MISSING
upperRoman : 'Upper Roman (I, II, III, IV, V, etc.)', // MISSING
lowerAlpha : 'Lower Alpha (a, b, c, d, e, etc.)', // MISSING
upperAlpha : 'Upper Alpha (A, B, C, D, E, etc.)', // MISSING
lowerGreek : 'Lower Greek (alpha, beta, gamma, etc.)', // MISSING
decimal : 'Decimal (1, 2, 3, etc.)', // MISSING
decimalLeadingZero : 'Decimal leading zero (01, 02, 03, etc.)' // MISSING
},
// Find And Replace Dialog
findAndReplace :
{
title : 'Find and Replace', // MISSING
find : 'Meklฤt',
replace : 'Nomainฤซt',
findWhat : 'Meklฤt:',
replaceWith : 'Nomainฤซt uz:',
notFoundMsg : 'Norฤdฤซtฤ frฤze netika atrasta.',
matchCase : 'Reฤฃistrjลซtฤซgs',
matchWord : 'Jฤsakrฤซt pilnฤซbฤ',
matchCyclic : 'Match cyclic', // MISSING
replaceAll : 'Aizvietot visu',
replaceSuccessMsg : '%1 occurrence(s) replaced.' // MISSING
},
// Table Dialog
table :
{
toolbar : 'Tabula',
title : 'Tabulas ฤซpaลกฤซbas',
menu : 'Tabulas ฤซpaลกฤซbas',
deleteTable : 'Dzฤst tabulu',
rows : 'Rindas',
columns : 'Kolonnas',
border : 'Rฤmja izmฤrs',
widthPx : 'pikseฤผos',
widthPc : 'procentuฤli',
widthUnit : 'width unit', // MISSING
cellSpace : 'Rลซtiลu atstatums',
cellPad : 'Rลซtiลu nobฤซde',
caption : 'Leฤฃenda',
summary : 'Anotฤcija',
headers : 'Headers', // MISSING
headersNone : 'None', // MISSING
headersColumn : 'First column', // MISSING
headersRow : 'First Row', // MISSING
headersBoth : 'Both', // MISSING
invalidRows : 'Number of rows must be a number greater than 0.', // MISSING
invalidCols : 'Number of columns must be a number greater than 0.', // MISSING
invalidBorder : 'Border size must be a number.', // MISSING
invalidWidth : 'Table width must be a number.', // MISSING
invalidHeight : 'Table height must be a number.', // MISSING
invalidCellSpacing : 'Cell spacing must be a positive number.', // MISSING
invalidCellPadding : 'Cell padding must be a positive number.', // MISSING
cell :
{
menu : 'ล ลซna',
insertBefore : 'Insert Cell Before', // MISSING
insertAfter : 'Insert Cell After', // MISSING
deleteCell : 'Dzฤst rลซtiลas',
merge : 'Apvienot rลซtiลas',
mergeRight : 'Merge Right', // MISSING
mergeDown : 'Merge Down', // MISSING
splitHorizontal : 'Split Cell Horizontally', // MISSING
splitVertical : 'Split Cell Vertically', // MISSING
title : 'Cell Properties', // MISSING
cellType : 'Cell Type', // MISSING
rowSpan : 'Rows Span', // MISSING
colSpan : 'Columns Span', // MISSING
wordWrap : 'Word Wrap', // MISSING
hAlign : 'Horizontal Alignment', // MISSING
vAlign : 'Vertical Alignment', // MISSING
alignBaseline : 'Baseline', // MISSING
bgColor : 'Background Color', // MISSING
borderColor : 'Border Color', // MISSING
data : 'Data', // MISSING
header : 'Header', // MISSING
yes : 'Yes', // MISSING
no : 'No', // MISSING
invalidWidth : 'Cell width must be a number.', // MISSING
invalidHeight : 'Cell height must be a number.', // MISSING
invalidRowSpan : 'Rows span must be a whole number.', // MISSING
invalidColSpan : 'Columns span must be a whole number.', // MISSING
chooseColor : 'Choose' // MISSING
},
row :
{
menu : 'Rinda',
insertBefore : 'Insert Row Before', // MISSING
insertAfter : 'Insert Row After', // MISSING
deleteRow : 'Dzฤst rindas'
},
column :
{
menu : 'Kolonna',
insertBefore : 'Insert Column Before', // MISSING
insertAfter : 'Insert Column After', // MISSING
deleteColumn : 'Dzฤst kolonnas'
}
},
// Button Dialog.
button :
{
title : 'Pogas ฤซpaลกฤซbas',
text : 'Teksts (vฤrtฤซba)',
type : 'Tips',
typeBtn : 'Button', // MISSING
typeSbm : 'Submit', // MISSING
typeRst : 'Reset' // MISSING
},
// Checkbox and Radio Button Dialogs.
checkboxAndRadio :
{
checkboxTitle : 'Atzฤซmฤลกanas kastฤซtes ฤซpaลกฤซbas',
radioTitle : 'Izvฤles poga ฤซpaลกฤซbas',
value : 'Vฤrtฤซba',
selected : 'Iezฤซmฤts'
},
// Form Dialog.
form :
{
title : 'Formas ฤซpaลกฤซbas',
menu : 'Formas ฤซpaลกฤซbas',
action : 'Darbฤซba',
method : 'Metode',
encoding : 'Encoding' // MISSING
},
// Select Field Dialog.
select :
{
title : 'Iezฤซmฤลกanas lauka ฤซpaลกฤซbas',
selectInfo : 'Informฤcija',
opAvail : 'Pieejamฤs iespฤjas',
value : 'Vฤrtฤซba',
size : 'Izmฤrs',
lines : 'rindas',
chkMulti : 'Atฤผaut vairฤkus iezฤซmฤjumus',
opText : 'Teksts',
opValue : 'Vฤrtฤซba',
btnAdd : 'Pievienot',
btnModify : 'Veikt izmaiลas',
btnUp : 'Augลกup',
btnDown : 'Lejup',
btnSetValue : 'Noteikt kฤ iezฤซmฤto vฤrtฤซbu',
btnDelete : 'Dzฤst'
},
// Textarea Dialog.
textarea :
{
title : 'Teksta laukuma ฤซpaลกฤซbas',
cols : 'Kolonnas',
rows : 'Rindas'
},
// Text Field Dialog.
textfield :
{
title : 'Teksta rindas ฤซpaลกฤซbas',
name : 'Nosaukums',
value : 'Vฤrtฤซba',
charWidth : 'Simbolu platums',
maxChars : 'Simbolu maksimฤlais daudzums',
type : 'Tips',
typeText : 'Teksts',
typePass : 'Parole'
},
// Hidden Field Dialog.
hidden :
{
title : 'Paslฤptฤs teksta rindas ฤซpaลกฤซbas',
name : 'Nosaukums',
value : 'Vฤrtฤซba'
},
// Image Dialog.
image :
{
title : 'Attฤla ฤซpaลกฤซbas',
titleButton : 'Attฤlpogas ฤซpaลกฤซbas',
menu : 'Attฤla ฤซpaลกฤซbas',
infoTab : 'Informฤcija par attฤlu',
btnUpload : 'Nosลซtฤซt serverim',
upload : 'Augลกupielฤdฤt',
alt : 'Alternatฤซvais teksts',
lockRatio : 'Nemainฤซga Augstuma/Platuma attiecฤซba',
resetSize : 'Atjaunot sฤkotnฤjo izmฤru',
border : 'Rฤmis',
hSpace : 'Horizontฤlฤ telpa',
vSpace : 'Vertikฤlฤ telpa',
alertUrl : 'Lลซdzu norฤdฤซt attฤla hipersaiti',
linkTab : 'Hipersaite',
button2Img : 'Do you want to transform the selected image button on a simple image?', // MISSING
img2Button : 'Do you want to transform the selected image on a image button?', // MISSING
urlMissing : 'Image source URL is missing.', // MISSING
validateBorder : 'Border must be a whole number.', // MISSING
validateHSpace : 'HSpace must be a whole number.', // MISSING
validateVSpace : 'VSpace must be a whole number.' // MISSING
},
// Flash Dialog
flash :
{
properties : 'Flash ฤซpaลกฤซbas',
propertiesTab : 'Properties', // MISSING
title : 'Flash ฤซpaลกฤซbas',
chkPlay : 'Automฤtiska atskaลoลกana',
chkLoop : 'Nepฤrtraukti',
chkMenu : 'Atฤผaut Flash izvฤlni',
chkFull : 'Allow Fullscreen', // MISSING
scale : 'Mainฤซt izmฤru',
scaleAll : 'Rฤdฤซt visu',
scaleNoBorder : 'Bez rฤmja',
scaleFit : 'Precฤซzs izmฤrs',
access : 'Script Access', // MISSING
accessAlways : 'Always', // MISSING
accessSameDomain: 'Same domain', // MISSING
accessNever : 'Never', // MISSING
alignAbsBottom : 'Absolลซti apakลกฤ',
alignAbsMiddle : 'Absolลซti vertikฤli centrฤts',
alignBaseline : 'Pamatrindฤ',
alignTextTop : 'Teksta augลกฤ',
quality : 'Quality', // MISSING
qualityBest : 'Best', // MISSING
qualityHigh : 'High', // MISSING
qualityAutoHigh : 'Auto High', // MISSING
qualityMedium : 'Medium', // MISSING
qualityAutoLow : 'Auto Low', // MISSING
qualityLow : 'Low', // MISSING
windowModeWindow: 'Window', // MISSING
windowModeOpaque: 'Opaque', // MISSING
windowModeTransparent : 'Transparent', // MISSING
windowMode : 'Window mode', // MISSING
flashvars : 'Variables for Flash', // MISSING
bgcolor : 'Fona krฤsa',
hSpace : 'Horizontฤlฤ telpa',
vSpace : 'Vertikฤlฤ telpa',
validateSrc : 'Lลซdzu norฤdi hipersaiti',
validateHSpace : 'HSpace must be a number.', // MISSING
validateVSpace : 'VSpace must be a number.' // MISSING
},
// Speller Pages Dialog
spellCheck :
{
toolbar : 'Pareizrakstฤซbas pฤrbaude',
title : 'Spell Check', // MISSING
notAvailable : 'Sorry, but service is unavailable now.', // MISSING
errorLoading : 'Error loading application service host: %s.', // MISSING
notInDic : 'Netika atrasts vฤrdnฤซcฤ',
changeTo : 'Nomainฤซt uz',
btnIgnore : 'Ignorฤt',
btnIgnoreAll : 'Ignorฤt visu',
btnReplace : 'Aizvietot',
btnReplaceAll : 'Aizvietot visu',
btnUndo : 'Atcelt',
noSuggestions : '- Nav ieteikumu -',
progress : 'Notiek pareizrakstฤซbas pฤrbaude...',
noMispell : 'Pareizrakstฤซbas pฤrbaude pabeigta: kฤผลซdas netika atrastas',
noChanges : 'Pareizrakstฤซbas pฤrbaude pabeigta: nekas netika labots',
oneChange : 'Pareizrakstฤซbas pฤrbaude pabeigta: 1 vฤrds izmainฤซts',
manyChanges : 'Pareizrakstฤซbas pฤrbaude pabeigta: %1 vฤrdi tika mainฤซti',
ieSpellDownload : 'Pareizrakstฤซbas pฤrbaudฤซtฤjs nav pievienots. Vai vฤlaties to lejupielฤdฤt tagad?'
},
smiley :
{
toolbar : 'Smaidiลi',
title : 'Ievietot smaidiลu',
options : 'Smiley Options' // MISSING
},
elementsPath :
{
eleLabel : 'Elements path', // MISSING
eleTitle : '%1 element' // MISSING
},
numberedlist : 'Numurฤts saraksts',
bulletedlist : 'Izcelts saraksts',
indent : 'Palielinฤt atkฤpi',
outdent : 'Samazinฤt atkฤpi',
justify :
{
left : 'Izlฤซdzinฤt pa kreisi',
center : 'Izlฤซdzinฤt pret centru',
right : 'Izlฤซdzinฤt pa labi',
block : 'Izlฤซdzinฤt malas'
},
blockquote : 'Block Quote', // MISSING
clipboard :
{
title : 'Ievietot',
cutError : 'Jลซsu pฤrlลซkprogrammas droลกฤซbas iestatฤซjumi nepieฤผauj editoram automฤtiski veikt izgrieลกanas darbฤซbu. Lลซdzu, izmantojiet (Ctrl/Cmd+X, lai veiktu ลกo darbฤซbu.',
copyError : 'Jลซsu pฤrlลซkprogrammas droลกฤซbas iestatฤซjumi nepieฤผauj editoram automฤtiski veikt kopฤลกanas darbฤซbu. Lลซdzu, izmantojiet (Ctrl/Cmd+C), lai veiktu ลกo darbฤซbu.',
pasteMsg : 'Lลซdzu, ievietojiet tekstu ลกajฤ laukumฤ, izmantojot klaviatลซru (<STRONG>Ctrl/Cmd+V</STRONG>) un apstipriniet ar <STRONG>Darฤซts!</STRONG>.',
securityMsg : 'Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.', // MISSING
pasteArea : 'Paste Area' // MISSING
},
pastefromword :
{
confirmCleanup : 'The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?', // MISSING
toolbar : 'Ievietot no Worda',
title : 'Ievietot no Worda',
error : 'It was not possible to clean up the pasted data due to an internal error' // MISSING
},
pasteText :
{
button : 'Ievietot kฤ vienkฤrลกu tekstu',
title : 'Ievietot kฤ vienkฤrลกu tekstu'
},
templates :
{
button : 'Sagataves',
title : 'Satura sagataves',
options : 'Template Options', // MISSING
insertOption : 'Replace actual contents', // MISSING
selectPromptMsg : 'Lลซdzu, norฤdiet sagatavi, ko atvฤrt editorฤ<br>(patreizฤjie dati tiks zaudฤti):',
emptyListMsg : '(Nav norฤdฤซtas sagataves)'
},
showBlocks : 'Show Blocks', // MISSING
stylesCombo :
{
label : 'Stils',
panelTitle : 'Formatting Styles', // MISSING
panelTitle1 : 'Block Styles', // MISSING
panelTitle2 : 'Inline Styles', // MISSING
panelTitle3 : 'Object Styles' // MISSING
},
format :
{
label : 'Formฤts',
panelTitle : 'Formฤts',
tag_p : 'Normฤls teksts',
tag_pre : 'Formatฤts teksts',
tag_address : 'Adrese',
tag_h1 : 'Virsraksts 1',
tag_h2 : 'Virsraksts 2',
tag_h3 : 'Virsraksts 3',
tag_h4 : 'Virsraksts 4',
tag_h5 : 'Virsraksts 5',
tag_h6 : 'Virsraksts 6',
tag_div : 'Rindkopa (DIV)'
},
div :
{
title : 'Create Div Container', // MISSING
toolbar : 'Create Div Container', // MISSING
cssClassInputLabel : 'Stylesheet Classes', // MISSING
styleSelectLabel : 'Style', // MISSING
IdInputLabel : 'Id', // MISSING
languageCodeInputLabel : ' Language Code', // MISSING
inlineStyleInputLabel : 'Inline Style', // MISSING
advisoryTitleInputLabel : 'Advisory Title', // MISSING
langDirLabel : 'Language Direction', // MISSING
langDirLTRLabel : 'Left to Right (LTR)', // MISSING
langDirRTLLabel : 'Right to Left (RTL)', // MISSING
edit : 'Edit Div', // MISSING
remove : 'Remove Div' // MISSING
},
iframe :
{
title : 'IFrame Properties', // MISSING
toolbar : 'IFrame', // MISSING
noUrl : 'Please type the iframe URL', // MISSING
scrolling : 'Enable scrollbars', // MISSING
border : 'Show frame border' // MISSING
},
font :
{
label : 'ล rifts',
voiceLabel : 'Font', // MISSING
panelTitle : 'ล rifts'
},
fontSize :
{
label : 'Izmฤrs',
voiceLabel : 'Font Size', // MISSING
panelTitle : 'Izmฤrs'
},
colorButton :
{
textColorTitle : 'Teksta krฤsa',
bgColorTitle : 'Fona krฤsa',
panelTitle : 'Colors', // MISSING
auto : 'Automฤtiska',
more : 'Plaลกฤka palete...'
},
colors :
{
'000' : 'Black', // MISSING
'800000' : 'Maroon', // MISSING
'8B4513' : 'Saddle Brown', // MISSING
'2F4F4F' : 'Dark Slate Gray', // MISSING
'008080' : 'Teal', // MISSING
'000080' : 'Navy', // MISSING
'4B0082' : 'Indigo', // MISSING
'696969' : 'Dark Gray', // MISSING
'B22222' : 'Fire Brick', // MISSING
'A52A2A' : 'Brown', // MISSING
'DAA520' : 'Golden Rod', // MISSING
'006400' : 'Dark Green', // MISSING
'40E0D0' : 'Turquoise', // MISSING
'0000CD' : 'Medium Blue', // MISSING
'800080' : 'Purple', // MISSING
'808080' : 'Gray', // MISSING
'F00' : 'Red', // MISSING
'FF8C00' : 'Dark Orange', // MISSING
'FFD700' : 'Gold', // MISSING
'008000' : 'Green', // MISSING
'0FF' : 'Cyan', // MISSING
'00F' : 'Blue', // MISSING
'EE82EE' : 'Violet', // MISSING
'A9A9A9' : 'Dim Gray', // MISSING
'FFA07A' : 'Light Salmon', // MISSING
'FFA500' : 'Orange', // MISSING
'FFFF00' : 'Yellow', // MISSING
'00FF00' : 'Lime', // MISSING
'AFEEEE' : 'Pale Turquoise', // MISSING
'ADD8E6' : 'Light Blue', // MISSING
'DDA0DD' : 'Plum', // MISSING
'D3D3D3' : 'Light Grey', // MISSING
'FFF0F5' : 'Lavender Blush', // MISSING
'FAEBD7' : 'Antique White', // MISSING
'FFFFE0' : 'Light Yellow', // MISSING
'F0FFF0' : 'Honeydew', // MISSING
'F0FFFF' : 'Azure', // MISSING
'F0F8FF' : 'Alice Blue', // MISSING
'E6E6FA' : 'Lavender', // MISSING
'FFF' : 'White' // MISSING
},
scayt :
{
title : 'Spell Check As You Type', // MISSING
opera_title : 'Not supported by Opera', // MISSING
enable : 'Enable SCAYT', // MISSING
disable : 'Disable SCAYT', // MISSING
about : 'About SCAYT', // MISSING
toggle : 'Toggle SCAYT', // MISSING
options : 'Options', // MISSING
langs : 'Languages', // MISSING
moreSuggestions : 'More suggestions', // MISSING
ignore : 'Ignore', // MISSING
ignoreAll : 'Ignore All', // MISSING
addWord : 'Add Word', // MISSING
emptyDic : 'Dictionary name should not be empty.', // MISSING
optionsTab : 'Options', // MISSING
allCaps : 'Ignore All-Caps Words', // MISSING
ignoreDomainNames : 'Ignore Domain Names', // MISSING
mixedCase : 'Ignore Words with Mixed Case', // MISSING
mixedWithDigits : 'Ignore Words with Numbers', // MISSING
languagesTab : 'Languages', // MISSING
dictionariesTab : 'Dictionaries', // MISSING
dic_field_name : 'Dictionary name', // MISSING
dic_create : 'Create', // MISSING
dic_restore : 'Restore', // MISSING
dic_delete : 'Delete', // MISSING
dic_rename : 'Rename', // MISSING
dic_info : 'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.', // MISSING
aboutTab : 'About' // MISSING
},
about :
{
title : 'About CKEditor', // MISSING
dlgTitle : 'About CKEditor', // MISSING
help : 'Check $1 for help.', // MISSING
userGuide : 'CKEditor User\'s Guide', // MISSING
moreInfo : 'For licensing information please visit our web site:', // MISSING
copy : 'Copyright © $1. All rights reserved.' // MISSING
},
maximize : 'Maximize', // MISSING
minimize : 'Minimize', // MISSING
fakeobjects :
{
anchor : 'Anchor', // MISSING
flash : 'Flash Animation', // MISSING
iframe : 'IFrame', // MISSING
hiddenfield : 'Hidden Field', // MISSING
unknown : 'Unknown Object' // MISSING
},
resize : 'Drag to resize', // MISSING
colordialog :
{
title : 'Select color', // MISSING
options : 'Color Options', // MISSING
highlight : 'Highlight', // MISSING
selected : 'Selected Color', // MISSING
clear : 'Clear' // MISSING
},
toolbarCollapse : 'Collapse Toolbar', // MISSING
toolbarExpand : 'Expand Toolbar', // MISSING
toolbarGroups :
{
document : 'Document', // MISSING
clipboard : 'Clipboard/Undo', // MISSING
editing : 'Editing', // MISSING
forms : 'Forms', // MISSING
basicstyles : 'Basic Styles', // MISSING
paragraph : 'Paragraph', // MISSING
links : 'Links', // MISSING
insert : 'Insert', // MISSING
styles : 'Styles', // MISSING
colors : 'Colors', // MISSING
tools : 'Tools' // MISSING
},
bidi :
{
ltr : 'Text direction from left to right', // MISSING
rtl : 'Text direction from right to left' // MISSING
},
docprops :
{
label : 'Dokumenta ฤซpaลกฤซbas',
title : 'Dokumenta ฤซpaลกฤซbas',
design : 'Design', // MISSING
meta : 'META dati',
chooseColor : 'Choose', // MISSING
other : '<cits>',
docTitle : 'Dokumenta virsraksts <Title>',
charset : 'Simbolu kodฤjums',
charsetOther : 'Cits simbolu kodฤjums',
charsetASCII : 'ASCII', // MISSING
charsetCE : 'Central European', // MISSING
charsetCT : 'Chinese Traditional (Big5)', // MISSING
charsetCR : 'Cyrillic', // MISSING
charsetGR : 'Greek', // MISSING
charsetJP : 'Japanese', // MISSING
charsetKR : 'Korean', // MISSING
charsetTR : 'Turkish', // MISSING
charsetUN : 'Unicode (UTF-8)', // MISSING
charsetWE : 'Western European', // MISSING
docType : 'Dokumenta tips',
docTypeOther : 'Cits dokumenta tips',
xhtmlDec : 'Ietvert XHTML deklarฤcijas',
bgColor : 'Fona krฤsa',
bgImage : 'Fona attฤla hipersaite',
bgFixed : 'Fona attฤls ir fiksฤts',
txtColor : 'Teksta krฤsa',
margin : 'Lapas robeลพas',
marginTop : 'Augลกฤ',
marginLeft : 'Pa kreisi',
marginRight : 'Pa labi',
marginBottom : 'Apakลกฤ',
metaKeywords : 'Dokumentu aprakstoลกi atslฤgvฤrdi (atdalฤซti ar komatu)',
metaDescription : 'Dokumenta apraksts',
metaAuthor : 'Autors',
metaCopyright : 'Autortiesฤซbas',
previewHtml : '<p>This is some <strong>sample text</strong>. You are using <a href="javascript:void(0)">CKEditor</a>.</p>' // MISSING
}
};
|
monkeythecoder/wp_lisder
|
wp-content/plugins/wp-online-store/admin/ckeditor/_source/lang/lv.js
|
JavaScript
|
gpl-2.0
| 27,055 |
๏ปฟ/*
Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("a11yhelp","id",{title:"Instruksi Accessibility",contents:"Bantuan. Tekan ESC untuk menutup dialog ini.",legend:[{name:"Umum",items:[{name:"Toolbar Editor",legend:"Tekan ${toolbarFocus} untuk berpindah ke toolbar. Untuk berpindah ke group toolbar selanjutnya dan sebelumnya gunakan TAB dan SHIFT+TAB. Untuk berpindah ke tombol toolbar selanjutnya dan sebelumnya gunakan RIGHT ARROW atau LEFT ARROW. Tekan SPASI atau ENTER untuk mengaktifkan tombol toolbar."},{name:"Dialog Editor",
legend:"Pada jendela dialog, tekan TAB untuk berpindah pada elemen dialog selanjutnya, tekan SHIFT+TAB untuk berpindah pada elemen dialog sebelumnya, tekan ENTER untuk submit dialog, tekan ESC untuk membatalkan dialog. Pada dialog dengan multi tab, daftar tab dapat diakses dengan ALT+F10 ataupun dengan tombol TAB sesuai urutan tab pada dialog. Jika daftar tab aktif terpilih, untuk berpindah tab dapat menggunakan RIGHT dan LEFT ARROW."},{name:"Context Menu Editor",legend:"Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC."},
{name:"List Box Editor",legend:"Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box."},{name:"Editor Element Path Bar",legend:"Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor."}]},
{name:"Commands",items:[{name:" Undo command",legend:"Press ${undo}"},{name:" Redo command",legend:"Press ${redo}"},{name:" Bold command",legend:"Press ${bold}"},{name:" Italic command",legend:"Press ${italic}"},{name:" Underline command",legend:"Press ${underline}"},{name:" Link command",legend:"Press ${link}"},{name:" Toolbar Collapse command",legend:"Press ${toolbarCollapse}"},{name:" Access previous focus space command",legend:"Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."},
{name:" Access next focus space command",legend:"Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."},{name:" Accessibility Help",legend:"Press ${a11yHelp}"},{name:" Paste as plain text",legend:"Press ${pastetext}",legendEdge:"Press ${pastetext}, followed by ${paste}"}]}],tab:"Tab",pause:"Pause",capslock:"Caps Lock",escape:"Escape",pageUp:"Page Up",pageDown:"Page Down",
leftArrow:"Left Arrow",upArrow:"Up Arrow",rightArrow:"Right Arrow",downArrow:"Down Arrow",insert:"Insert",leftWindowKey:"Left Windows key",rightWindowKey:"Right Windows key",selectKey:"Select key",numpad0:"Numpad 0",numpad1:"Numpad 1",numpad2:"Numpad 2",numpad3:"Numpad 3",numpad4:"Numpad 4",numpad5:"Numpad 5",numpad6:"Numpad 6",numpad7:"Numpad 7",numpad8:"Numpad 8",numpad9:"Numpad 9",multiply:"Multiply",add:"Add",subtract:"Subtract",decimalPoint:"Decimal Point",divide:"Divide",f1:"F1",f2:"F2",f3:"F3",
f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Semicolon",equalSign:"Equal Sign",comma:"Comma",dash:"Dash",period:"Period",forwardSlash:"Forward Slash",graveAccent:"Grave Accent",openBracket:"Open Bracket",backSlash:"Backslash",closeBracket:"Close Bracket",singleQuote:"Single Quote"});
|
YAFNET/YAFNET
|
yafsrc/YetAnotherForum.NET/Scripts/ckeditor/plugins/plugins/a11yhelp/dialogs/lang/id.js
|
JavaScript
|
apache-2.0
| 4,041 |
VectorCanvas.prototype.createPath = function (config) {
var node;
if (this.mode === 'svg') {
node = this.createSvgNode('path');
node.setAttribute('d', config.path);
if (this.params.borderColor !== null) {
node.setAttribute('stroke', this.params.borderColor);
}
if (this.params.borderWidth > 0) {
node.setAttribute('stroke-width', this.params.borderWidth);
node.setAttribute('stroke-linecap', 'round');
node.setAttribute('stroke-linejoin', 'round');
}
if (this.params.borderOpacity > 0) {
node.setAttribute('stroke-opacity', this.params.borderOpacity);
}
node.setFill = function (color) {
this.setAttribute('fill', color);
if (this.getAttribute('original') === null) {
this.setAttribute('original', color);
}
};
node.getFill = function () {
return this.getAttribute('fill');
};
node.getOriginalFill = function () {
return this.getAttribute('original');
};
node.setOpacity = function (opacity) {
this.setAttribute('fill-opacity', opacity);
};
} else {
node = this.createVmlNode('shape');
node.coordorigin = '0 0';
node.coordsize = this.width + ' ' + this.height;
node.style.width = this.width + 'px';
node.style.height = this.height + 'px';
node.fillcolor = JQVMap.defaultFillColor;
node.stroked = false;
node.path = VectorCanvas.pathSvgToVml(config.path);
var scale = this.createVmlNode('skew');
scale.on = true;
scale.matrix = '0.01,0,0,0.01,0,0';
scale.offset = '0,0';
node.appendChild(scale);
var fill = this.createVmlNode('fill');
node.appendChild(fill);
node.setFill = function (color) {
this.getElementsByTagName('fill')[0].color = color;
if (this.getAttribute('original') === null) {
this.setAttribute('original', color);
}
};
node.getFill = function () {
return this.getElementsByTagName('fill')[0].color;
};
node.getOriginalFill = function () {
return this.getAttribute('original');
};
node.setOpacity = function (opacity) {
this.getElementsByTagName('fill')[0].opacity = parseInt(opacity * 100, 10) + '%';
};
}
return node;
};
|
krasnyuk/e-liquid-MS
|
wwwroot/assets/js/jqvmap/src/VectorCanvas/createPath.js
|
JavaScript
|
mit
| 2,230 |
/**
* jQuery plugin wrapper for TinySort
* Does not use the first argument in tinysort.js since that is handled internally by the jQuery selector.
* Sub-selections (option.selector) do not use the jQuery selector syntax but regular CSS3 selector syntax.
* @summary jQuery plugin wrapper for TinySort
* @version 2.2.2
* @requires tinysort
* @license MIT/GPL
* @author Ron Valstar (http://www.sjeiti.com/)
* @copyright Ron Valstar <ron@ronvalstar.nl>
*/
!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery","tinysort"],a):jQuery&&!jQuery.fn.tsort&&a(jQuery,tinysort)}(function(a,b){"use strict";a.tinysort={defaults:b.defaults},a.fn.extend({tinysort:function(){var a,c,d=Array.prototype.slice.call(arguments);d.unshift(this),a=b.apply(null,d),c=a.length;for(var e=0,f=this.length;f>e;e++)c>e?this[e]=a[e]:delete this[e];return this.length=c,this}}),a.fn.tsort=a.fn.tinysort});
|
sajochiu/cdnjs
|
ajax/libs/tinysort/2.2.2/jquery.tinysort.min.js
|
JavaScript
|
mit
| 912 |
//// [inheritedConstructorWithRestParams2.ts]
class IBaseBase<T, U> {
constructor(x: U) { }
}
interface IBase<T, U> extends IBaseBase<T, U> { }
class BaseBase2 {
constructor(x: number) { }
}
declare class BaseBase<T, U> extends BaseBase2 implements IBase<T, U> {
constructor(x: T, ...y: U[]);
constructor(x1: T, x2: T, ...y: U[]);
constructor(x1: T, x2: U, y: T);
}
class Base extends BaseBase<string, number> {
}
class Derived extends Base { }
// Ok
new Derived("", "");
new Derived("", 3);
new Derived("", 3, 3);
new Derived("", 3, 3, 3);
new Derived("", 3, "");
new Derived("", "", 3);
new Derived("", "", 3, 3);
// Errors
new Derived(3);
new Derived("", 3, "", 3);
new Derived("", 3, "", "");
//// [inheritedConstructorWithRestParams2.js]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var IBaseBase = (function () {
function IBaseBase(x) {
}
return IBaseBase;
})();
var BaseBase2 = (function () {
function BaseBase2(x) {
}
return BaseBase2;
})();
var Base = (function (_super) {
__extends(Base, _super);
function Base() {
_super.apply(this, arguments);
}
return Base;
})(BaseBase);
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived() {
_super.apply(this, arguments);
}
return Derived;
})(Base);
// Ok
new Derived("", "");
new Derived("", 3);
new Derived("", 3, 3);
new Derived("", 3, 3, 3);
new Derived("", 3, "");
new Derived("", "", 3);
new Derived("", "", 3, 3);
// Errors
new Derived(3);
new Derived("", 3, "", 3);
new Derived("", 3, "", "");
|
sassson/TypeScript
|
tests/baselines/reference/inheritedConstructorWithRestParams2.js
|
JavaScript
|
apache-2.0
| 1,838 |
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./_iobject')
, defined = require('./_defined');
module.exports = function(it){
return IObject(defined(it));
};
|
migua1204/jikexueyuan
|
ๆๅฎขๅญฆ้ข/nodeBaidu/node_modules/core-js/modules/_to-iobject.js
|
JavaScript
|
apache-2.0
| 213 |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('goog.ui.SubMenuTest');
goog.setTestOnly('goog.ui.SubMenuTest');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.State');
goog.require('goog.dom');
goog.require('goog.dom.classlist');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
goog.require('goog.functions');
goog.require('goog.positioning');
goog.require('goog.positioning.Overflow');
goog.require('goog.style');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.events');
goog.require('goog.testing.jsunit');
goog.require('goog.ui.Component');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuItem');
goog.require('goog.ui.SubMenu');
goog.require('goog.ui.SubMenuRenderer');
var menu;
var clonedMenuDom;
var mockClock;
// mock out goog.positioning.positionAtCoordinate so that
// the menu always fits. (we don't care about testing the
// dynamic menu positioning if the menu doesn't fit in the window.)
var oldPositionFn = goog.positioning.positionAtCoordinate;
goog.positioning.positionAtCoordinate = function(
absolutePos, movableElement, movableElementCorner, opt_margin,
opt_overflow) {
return oldPositionFn.call(
null, absolutePos, movableElement, movableElementCorner, opt_margin,
goog.positioning.Overflow.IGNORE);
};
function setUp() {
clonedMenuDom = goog.dom.getElement('demoMenu').cloneNode(true);
menu = new goog.ui.Menu();
}
function tearDown() {
document.body.style.direction = 'ltr';
menu.dispose();
var element = goog.dom.getElement('demoMenu');
element.parentNode.replaceChild(clonedMenuDom, element);
goog.dom.removeChildren(goog.dom.getElement('sandbox'));
if (mockClock) {
mockClock.uninstall();
mockClock = null;
}
}
function assertKeyHandlingIsCorrect(keyToOpenSubMenu, keyToCloseSubMenu) {
menu.setFocusable(true);
menu.decorate(goog.dom.getElement('demoMenu'));
var KeyCodes = goog.events.KeyCodes;
var plainItem = menu.getChildAt(0);
plainItem.setMnemonic(KeyCodes.F);
var subMenuItem1 = menu.getChildAt(1);
subMenuItem1.setMnemonic(KeyCodes.S);
var subMenuItem1Menu = subMenuItem1.getMenu();
menu.setHighlighted(plainItem);
var fireKeySequence = goog.testing.events.fireKeySequence;
assertTrue(
'Expected OpenSubMenu key to not be handled',
fireKeySequence(plainItem.getElement(), keyToOpenSubMenu));
assertFalse(subMenuItem1Menu.isVisible());
assertFalse(
'Expected F key to be handled',
fireKeySequence(plainItem.getElement(), KeyCodes.F));
assertFalse(
'Expected DOWN key to be handled',
fireKeySequence(plainItem.getElement(), KeyCodes.DOWN));
assertEquals(subMenuItem1, menu.getChildAt(1));
assertFalse(
'Expected OpenSubMenu key to be handled',
fireKeySequence(subMenuItem1.getElement(), keyToOpenSubMenu));
assertTrue(subMenuItem1Menu.isVisible());
assertFalse(
'Expected CloseSubMenu key to be handled',
fireKeySequence(subMenuItem1.getElement(), keyToCloseSubMenu));
assertFalse(subMenuItem1Menu.isVisible());
assertFalse(
'Expected UP key to be handled',
fireKeySequence(subMenuItem1.getElement(), KeyCodes.UP));
assertFalse(
'Expected S key to be handled',
fireKeySequence(plainItem.getElement(), KeyCodes.S));
assertTrue(subMenuItem1Menu.isVisible());
}
function testKeyHandling_ltr() {
assertKeyHandlingIsCorrect(
goog.events.KeyCodes.RIGHT, goog.events.KeyCodes.LEFT);
}
function testKeyHandling_rtl() {
document.body.style.direction = 'rtl';
assertKeyHandlingIsCorrect(
goog.events.KeyCodes.LEFT, goog.events.KeyCodes.RIGHT);
}
function testNormalLtrSubMenu() {
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
assertArrowDirection(subMenu, false);
assertRenderDirection(subMenu, false);
assertArrowPosition(subMenu, false);
}
function testNormalRtlSubMenu() {
document.body.style.direction = 'rtl';
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
assertArrowDirection(subMenu, true);
assertRenderDirection(subMenu, true);
assertArrowPosition(subMenu, true);
}
function testLtrSubMenuAlignedToStart() {
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
subMenu.setAlignToEnd(false);
assertArrowDirection(subMenu, true);
assertRenderDirection(subMenu, true);
assertArrowPosition(subMenu, false);
}
function testNullContentElement() {
var subMenu = new goog.ui.SubMenu();
subMenu.setContent('demo');
}
function testRtlSubMenuAlignedToStart() {
document.body.style.direction = 'rtl';
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
subMenu.setAlignToEnd(false);
assertArrowDirection(subMenu, false);
assertRenderDirection(subMenu, false);
assertArrowPosition(subMenu, true);
}
function testSetContentKeepsArrow_ltr() {
document.body.style.direction = 'ltr';
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
subMenu.setAlignToEnd(false);
subMenu.setContent('test');
assertArrowDirection(subMenu, true);
assertRenderDirection(subMenu, true);
assertArrowPosition(subMenu, false);
}
function testSetContentKeepsArrow_rtl() {
document.body.style.direction = 'rtl';
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
subMenu.setAlignToEnd(false);
subMenu.setContent('test');
assertArrowDirection(subMenu, false);
assertRenderDirection(subMenu, false);
assertArrowPosition(subMenu, true);
}
function testExitDocument() {
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
var innerMenu = subMenu.getMenu();
assertTrue('Top-level menu was not in document', menu.isInDocument());
assertTrue('Submenu was not in document', subMenu.isInDocument());
assertTrue('Inner menu was not in document', innerMenu.isInDocument());
menu.exitDocument();
assertFalse('Top-level menu was in document', menu.isInDocument());
assertFalse('Submenu was in document', subMenu.isInDocument());
assertFalse('Inner menu was in document', innerMenu.isInDocument());
}
function testDisposal() {
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
var innerMenu = subMenu.getMenu();
menu.dispose();
assert('Top-level menu was not disposed', menu.getDisposed());
assert('Submenu was not disposed', subMenu.getDisposed());
assert('Inner menu was not disposed', innerMenu.getDisposed());
}
function testShowAndDismissSubMenu() {
var openEventDispatched = false;
var closeEventDispatched = false;
function handleEvent(e) {
switch (e.type) {
case goog.ui.Component.EventType.OPEN:
openEventDispatched = true;
break;
case goog.ui.Component.EventType.CLOSE:
closeEventDispatched = true;
break;
default:
fail('Invalid event type: ' + e.type);
}
}
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
subMenu.setHighlighted(true);
goog.events.listen(
subMenu,
[goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE],
handleEvent);
assertFalse(
'Submenu must not have "-open" CSS class',
goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible());
assertFalse('No OPEN event must have been dispatched', openEventDispatched);
assertFalse('No CLOSE event must have been dispatched', closeEventDispatched);
subMenu.showSubMenu();
assertTrue(
'Submenu must have "-open" CSS class',
goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
assertTrue('Popup menu must be visible', subMenu.getMenu().isVisible());
assertTrue('OPEN event must have been dispatched', openEventDispatched);
assertFalse('No CLOSE event must have been dispatched', closeEventDispatched);
subMenu.dismissSubMenu();
assertFalse(
'Submenu must not have "-open" CSS class',
goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible());
assertTrue('CLOSE event must have been dispatched', closeEventDispatched);
goog.events.unlisten(
subMenu,
[goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE],
handleEvent);
}
function testDismissWhenSubMenuNotVisible() {
var openEventDispatched = false;
var closeEventDispatched = false;
function handleEvent(e) {
switch (e.type) {
case goog.ui.Component.EventType.OPEN:
openEventDispatched = true;
break;
case goog.ui.Component.EventType.CLOSE:
closeEventDispatched = true;
break;
default:
fail('Invalid event type: ' + e.type);
}
}
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
subMenu.setHighlighted(true);
goog.events.listen(
subMenu,
[goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE],
handleEvent);
assertFalse(
'Submenu must not have "-open" CSS class',
goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible());
assertFalse('No OPEN event must have been dispatched', openEventDispatched);
assertFalse('No CLOSE event must have been dispatched', closeEventDispatched);
subMenu.showSubMenu();
subMenu.getMenu().setVisible(false);
subMenu.dismissSubMenu();
assertFalse(
'Submenu must not have "-open" CSS class',
goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open'));
assertFalse(subMenu.menuIsVisible_);
assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible());
assertTrue('CLOSE event must have been dispatched', closeEventDispatched);
goog.events.unlisten(
subMenu,
[goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE],
handleEvent);
}
function testCloseSubMenuBehavior() {
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
subMenu.getElement().id = 'subMenu';
var innerMenu = subMenu.getMenu();
innerMenu.getChildAt(0).getElement().id = 'child1';
subMenu.setHighlighted(true);
subMenu.showSubMenu();
function MyFakeEvent(keyCode, opt_eventType) {
this.type = opt_eventType || goog.events.KeyHandler.EventType.KEY;
this.keyCode = keyCode;
this.propagationStopped = false;
this.preventDefault = goog.nullFunction;
this.stopPropagation = function() { this.propagationStopped = true; };
}
// Focus on the first item in the submenu and verify the activedescendant is
// set correctly.
subMenu.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.DOWN));
assertEquals(
'First item in submenu must be the aria-activedescendant', 'child1',
goog.a11y.aria.getState(
menu.getElement(), goog.a11y.aria.State.ACTIVEDESCENDANT));
// Dismiss the submenu and verify the activedescendant is updated correctly.
subMenu.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.LEFT));
assertEquals(
'Submenu must be the aria-activedescendant', 'subMenu',
goog.a11y.aria.getState(
menu.getElement(), goog.a11y.aria.State.ACTIVEDESCENDANT));
}
function testLazyInstantiateSubMenu() {
menu.decorate(goog.dom.getElement('demoMenu'));
var subMenu = menu.getChildAt(1);
subMenu.setHighlighted(true);
var lazyMenu;
var key = goog.events.listen(
subMenu, goog.ui.Component.EventType.OPEN, function(e) {
lazyMenu = new goog.ui.Menu();
lazyMenu.addItem(new goog.ui.MenuItem('foo'));
lazyMenu.addItem(new goog.ui.MenuItem('bar'));
subMenu.setMenu(lazyMenu, /* opt_internal */ false);
});
subMenu.showSubMenu();
assertNotNull('Popup menu must have been created', lazyMenu);
assertEquals(
'Popup menu must be a child of the submenu', subMenu,
lazyMenu.getParent());
assertTrue('Popup menu must have been rendered', lazyMenu.isInDocument());
assertTrue('Popup menu must be visible', lazyMenu.isVisible());
menu.dispose();
assertTrue('Submenu must have been disposed of', subMenu.isDisposed());
assertFalse(
'Popup menu must not have been disposed of', lazyMenu.isDisposed());
lazyMenu.dispose();
goog.events.unlistenByKey(key);
}
function testReusableMenu() {
var subMenuOne = new goog.ui.SubMenu('SubMenu One');
var subMenuTwo = new goog.ui.SubMenu('SubMenu Two');
menu.addItem(subMenuOne);
menu.addItem(subMenuTwo);
menu.render(goog.dom.getElement('sandbox'));
// It is possible for the same popup menu to be shared between different
// submenus.
var sharedMenu = new goog.ui.Menu();
sharedMenu.addItem(new goog.ui.MenuItem('Hello'));
sharedMenu.addItem(new goog.ui.MenuItem('World'));
assertNull('Shared menu must not have a parent', sharedMenu.getParent());
subMenuOne.setMenu(sharedMenu);
assertEquals(
'SubMenuOne must point to the shared menu', sharedMenu,
subMenuOne.getMenu());
assertEquals(
'SubMenuOne must be the shared menu\'s parent', subMenuOne,
sharedMenu.getParent());
subMenuTwo.setMenu(sharedMenu);
assertEquals(
'SubMenuTwo must point to the shared menu', sharedMenu,
subMenuTwo.getMenu());
assertEquals(
'SubMenuTwo must be the shared menu\'s parent', subMenuTwo,
sharedMenu.getParent());
assertEquals(
'SubMenuOne must still point to the shared menu', sharedMenu,
subMenuOne.getMenu());
menu.setHighlighted(subMenuOne);
subMenuOne.showSubMenu();
assertEquals(
'SubMenuOne must point to the shared menu', sharedMenu,
subMenuOne.getMenu());
assertEquals(
'SubMenuOne must be the shared menu\'s parent', subMenuOne,
sharedMenu.getParent());
assertEquals(
'SubMenuTwo must still point to the shared menu', sharedMenu,
subMenuTwo.getMenu());
assertTrue('Shared menu must be visible', sharedMenu.isVisible());
menu.setHighlighted(subMenuTwo);
subMenuTwo.showSubMenu();
assertEquals(
'SubMenuTwo must point to the shared menu', sharedMenu,
subMenuTwo.getMenu());
assertEquals(
'SubMenuTwo must be the shared menu\'s parent', subMenuTwo,
sharedMenu.getParent());
assertEquals(
'SubMenuOne must still point to the shared menu', sharedMenu,
subMenuOne.getMenu());
assertTrue('Shared menu must be visible', sharedMenu.isVisible());
}
/**
* If you remove a submenu in the interval between when a mouseover event
* is fired on it, and showSubMenu() is called, showSubMenu causes a null
* value to be dereferenced. This test validates that the fix for this works.
* (See bug 1823144).
*/
function testDeleteItemDuringSubmenuDisplayInterval() {
mockClock = new goog.testing.MockClock(true);
var submenu = new goog.ui.SubMenu('submenu');
submenu.addItem(new goog.ui.MenuItem('submenu item 1'));
menu.addItem(submenu);
// Trigger mouseover, and remove item before showSubMenu can be called.
var e = new goog.events.Event();
submenu.handleMouseOver(e);
menu.removeItem(submenu);
mockClock.tick(goog.ui.SubMenu.MENU_DELAY_MS);
// (No JS error should occur.)
}
function testShowSubMenuAfterRemoval() {
var submenu = new goog.ui.SubMenu('submenu');
menu.addItem(submenu);
menu.removeItem(submenu);
submenu.showSubMenu();
// (No JS error should occur.)
}
/**
* Tests that if a sub menu is selectable, then it can handle actions.
*/
function testSubmenuSelectable() {
var submenu = new goog.ui.SubMenu('submenu');
submenu.addItem(new goog.ui.MenuItem('submenu item 1'));
menu.addItem(submenu);
submenu.setSelectable(true);
var numClicks = 0;
var menuClickedFn = function(e) { numClicks++; };
goog.events.listen(
submenu, goog.ui.Component.EventType.ACTION, menuClickedFn);
submenu.performActionInternal(null);
submenu.performActionInternal(null);
assertEquals('The submenu should have fired an event', 2, numClicks);
submenu.setSelectable(false);
submenu.performActionInternal(null);
assertEquals(
'The submenu should not have fired any further events', 2, numClicks);
}
/**
* Tests that if a sub menu is checkable, then it can handle actions.
*/
function testSubmenuCheckable() {
var submenu = new goog.ui.SubMenu('submenu');
submenu.addItem(new goog.ui.MenuItem('submenu item 1'));
menu.addItem(submenu);
submenu.setCheckable(true);
var numClicks = 0;
var menuClickedFn = function(e) { numClicks++; };
goog.events.listen(
submenu, goog.ui.Component.EventType.ACTION, menuClickedFn);
submenu.performActionInternal(null);
submenu.performActionInternal(null);
assertEquals('The submenu should have fired an event', 2, numClicks);
submenu.setCheckable(false);
submenu.performActionInternal(null);
assertEquals(
'The submenu should not have fired any further events', 2, numClicks);
}
/**
* Tests that entering a child menu cancels the dismiss timer for the submenu.
*/
function testEnteringChildCancelsDismiss() {
var submenu = new goog.ui.SubMenu('submenu');
submenu.isInDocument = goog.functions.TRUE;
submenu.addItem(new goog.ui.MenuItem('submenu item 1'));
menu.addItem(submenu);
mockClock = new goog.testing.MockClock(true);
submenu.getMenu().setVisible(true);
// This starts the dismiss timer.
submenu.setHighlighted(false);
// This should cancel the dismiss timer.
submenu.getMenu().dispatchEvent(goog.ui.Component.EventType.ENTER);
// Tick the length of the dismiss timer.
mockClock.tick(goog.ui.SubMenu.MENU_DELAY_MS);
// Check that the menu is now highlighted and still visible.
assertTrue(submenu.getMenu().isVisible());
assertTrue(submenu.isHighlighted());
}
/**
* Asserts that this sub menu renders in the right direction relative to
* the parent menu.
* @param {goog.ui.SubMenu} subMenu The sub menu.
* @param {boolean} left True for left-pointing, false for right-pointing.
*/
function assertRenderDirection(subMenu, left) {
subMenu.getParent().setHighlighted(subMenu);
subMenu.showSubMenu();
var menuItemPosition = goog.style.getPageOffset(subMenu.getElement());
var menuPosition = goog.style.getPageOffset(subMenu.getMenu().getElement());
assert(Math.abs(menuItemPosition.y - menuPosition.y) < 5);
assertEquals(
'Menu at: ' + menuPosition.x + ', submenu item at: ' + menuItemPosition.x,
left, menuPosition.x < menuItemPosition.x);
}
/**
* Asserts that this sub menu has a properly-oriented arrow.
* @param {goog.ui.SubMenu} subMenu The sub menu.
* @param {boolean} left True for left-pointing, false for right-pointing.
*/
function assertArrowDirection(subMenu, left) {
assertEquals(
left ? goog.ui.SubMenuRenderer.LEFT_ARROW_ :
goog.ui.SubMenuRenderer.RIGHT_ARROW_,
getArrowElement(subMenu).innerHTML);
}
/**
* Asserts that the arrow position is correct.
* @param {goog.ui.SubMenu} subMenu The sub menu.
* @param {boolean} leftAlign True for left-aligned, false for right-aligned.
*/
function assertArrowPosition(subMenu, left) {
var arrow = getArrowElement(subMenu);
var expectedLeft =
left ? 0 : arrow.offsetParent.offsetWidth - arrow.offsetWidth;
var actualLeft = arrow.offsetLeft;
assertTrue(
'Expected left offset: ' + expectedLeft + '\n' +
'Actual left offset: ' + actualLeft + '\n',
Math.abs(expectedLeft - actualLeft) < 5);
}
/**
* Gets the arrow element of a sub menu.
* @param {goog.ui.SubMenu} subMenu The sub menu.
* @return {Element} The arrow.
*/
function getArrowElement(subMenu) {
return subMenu.getContentElement().lastChild;
}
|
LeoLombardi/tos-laimas-compass
|
tos-laimas-compass-win32-x64/resources/app/node_modules/closure-util/.deps/library/b06c979ecae7d78dd1ac4f7b09adec643baac308/closure/goog/ui/submenu_test.js
|
JavaScript
|
mit
| 20,504 |
// [Name] SVGLinearGradientElement-dom-x1-attr.js
// [Expected rendering result] green ellipse, no red visible - and a series of PASS messages
description("Tests dynamic updates of the 'x1' attribute of the SVGLinearGradientElement object")
createSVGTestCase();
var ellipseElement = createSVGElement("ellipse");
ellipseElement.setAttribute("cx", "150");
ellipseElement.setAttribute("cy", "150");
ellipseElement.setAttribute("rx", "100");
ellipseElement.setAttribute("ry", "150");
ellipseElement.setAttribute("fill", "url(#gradient)");
var defsElement = createSVGElement("defs");
rootSVGElement.appendChild(defsElement);
var linearGradientElement = createSVGElement("linearGradient");
linearGradientElement.setAttribute("id", "gradient");
linearGradientElement.setAttribute("x1", "100%");
var firstStopElement = createSVGElement("stop");
firstStopElement.setAttribute("offset", "0");
firstStopElement.setAttribute("stop-color", "red");
linearGradientElement.appendChild(firstStopElement);
var lastStopElement = createSVGElement("stop");
lastStopElement.setAttribute("offset", "1");
lastStopElement.setAttribute("stop-color", "green");
linearGradientElement.appendChild(lastStopElement);
defsElement.appendChild(linearGradientElement);
rootSVGElement.appendChild(ellipseElement);
shouldBeEqualToString("linearGradientElement.getAttribute('x1')", "100%");
function repaintTest() {
linearGradientElement.setAttribute("x1", "200%");
shouldBeEqualToString("linearGradientElement.getAttribute('x1')", "200%");
}
var successfullyParsed = true;
|
scheib/chromium
|
third_party/blink/web_tests/svg/dynamic-updates/script-tests/SVGLinearGradientElement-dom-x1-attr.js
|
JavaScript
|
bsd-3-clause
| 1,554 |
MessageFormat.locale.es = function ( n ) {
if ( n === 1 ) {
return "one";
}
return "other";
};
|
Ergosign/grunt-swagger-docs-onepage
|
test/fixtures/libs/messageformat/locale/es.js
|
JavaScript
|
mit
| 105 |
"format register";
System.register("angular2/src/mock/animation_builder_mock", ["angular2/src/core/di", "angular2/src/animate/animation_builder", "angular2/src/animate/css_animation_builder", "angular2/src/animate/animation", "angular2/src/animate/browser_details"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var di_1 = require("angular2/src/core/di");
var animation_builder_1 = require("angular2/src/animate/animation_builder");
var css_animation_builder_1 = require("angular2/src/animate/css_animation_builder");
var animation_1 = require("angular2/src/animate/animation");
var browser_details_1 = require("angular2/src/animate/browser_details");
var MockAnimationBuilder = (function(_super) {
__extends(MockAnimationBuilder, _super);
function MockAnimationBuilder() {
_super.call(this, null);
}
MockAnimationBuilder.prototype.css = function() {
return new MockCssAnimationBuilder();
};
MockAnimationBuilder = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], MockAnimationBuilder);
return MockAnimationBuilder;
}(animation_builder_1.AnimationBuilder));
exports.MockAnimationBuilder = MockAnimationBuilder;
var MockCssAnimationBuilder = (function(_super) {
__extends(MockCssAnimationBuilder, _super);
function MockCssAnimationBuilder() {
_super.call(this, null);
}
MockCssAnimationBuilder.prototype.start = function(element) {
return new MockAnimation(element, this.data);
};
return MockCssAnimationBuilder;
}(css_animation_builder_1.CssAnimationBuilder));
var MockBrowserAbstraction = (function(_super) {
__extends(MockBrowserAbstraction, _super);
function MockBrowserAbstraction() {
_super.apply(this, arguments);
}
MockBrowserAbstraction.prototype.doesElapsedTimeIncludesDelay = function() {
this.elapsedTimeIncludesDelay = false;
};
return MockBrowserAbstraction;
}(browser_details_1.BrowserDetails));
var MockAnimation = (function(_super) {
__extends(MockAnimation, _super);
function MockAnimation(element, data) {
_super.call(this, element, data, new MockBrowserAbstraction());
}
MockAnimation.prototype.wait = function(callback) {
this._callback = callback;
};
MockAnimation.prototype.flush = function() {
this._callback(0);
this._callback = null;
};
return MockAnimation;
}(animation_1.Animation));
global.define = __define;
return module.exports;
});
System.register("angular2/src/mock/directive_resolver_mock", ["angular2/src/core/di", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/core/metadata", "angular2/src/core/linker/directive_resolver"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var di_1 = require("angular2/src/core/di");
var collection_1 = require("angular2/src/facade/collection");
var lang_1 = require("angular2/src/facade/lang");
var metadata_1 = require("angular2/src/core/metadata");
var directive_resolver_1 = require("angular2/src/core/linker/directive_resolver");
var MockDirectiveResolver = (function(_super) {
__extends(MockDirectiveResolver, _super);
function MockDirectiveResolver() {
_super.apply(this, arguments);
this._providerOverrides = new collection_1.Map();
this.viewProviderOverrides = new collection_1.Map();
}
MockDirectiveResolver.prototype.resolve = function(type) {
var dm = _super.prototype.resolve.call(this, type);
var providerOverrides = this._providerOverrides.get(type);
var viewProviderOverrides = this.viewProviderOverrides.get(type);
var providers = dm.providers;
if (lang_1.isPresent(providerOverrides)) {
providers = dm.providers.concat(providerOverrides);
}
if (dm instanceof metadata_1.ComponentMetadata) {
var viewProviders = dm.viewProviders;
if (lang_1.isPresent(viewProviderOverrides)) {
viewProviders = dm.viewProviders.concat(viewProviderOverrides);
}
return new metadata_1.ComponentMetadata({
selector: dm.selector,
inputs: dm.inputs,
outputs: dm.outputs,
host: dm.host,
exportAs: dm.exportAs,
moduleId: dm.moduleId,
queries: dm.queries,
changeDetection: dm.changeDetection,
providers: providers,
viewProviders: viewProviders
});
}
return new metadata_1.DirectiveMetadata({
selector: dm.selector,
inputs: dm.inputs,
outputs: dm.outputs,
host: dm.host,
providers: providers,
exportAs: dm.exportAs,
queries: dm.queries
});
};
MockDirectiveResolver.prototype.setBindingsOverride = function(type, bindings) {
this._providerOverrides.set(type, bindings);
};
MockDirectiveResolver.prototype.setViewBindingsOverride = function(type, viewBindings) {
this.viewProviderOverrides.set(type, viewBindings);
};
MockDirectiveResolver.prototype.setProvidersOverride = function(type, providers) {
this._providerOverrides.set(type, providers);
};
MockDirectiveResolver.prototype.setViewProvidersOverride = function(type, viewProviders) {
this.viewProviderOverrides.set(type, viewProviders);
};
MockDirectiveResolver = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], MockDirectiveResolver);
return MockDirectiveResolver;
}(directive_resolver_1.DirectiveResolver));
exports.MockDirectiveResolver = MockDirectiveResolver;
global.define = __define;
return module.exports;
});
System.register("angular2/src/mock/view_resolver_mock", ["angular2/src/core/di", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/metadata", "angular2/src/core/linker/view_resolver"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var di_1 = require("angular2/src/core/di");
var collection_1 = require("angular2/src/facade/collection");
var lang_1 = require("angular2/src/facade/lang");
var exceptions_1 = require("angular2/src/facade/exceptions");
var metadata_1 = require("angular2/src/core/metadata");
var view_resolver_1 = require("angular2/src/core/linker/view_resolver");
var MockViewResolver = (function(_super) {
__extends(MockViewResolver, _super);
function MockViewResolver() {
_super.call(this);
this._views = new collection_1.Map();
this._inlineTemplates = new collection_1.Map();
this._viewCache = new collection_1.Map();
this._directiveOverrides = new collection_1.Map();
}
MockViewResolver.prototype.setView = function(component, view) {
this._checkOverrideable(component);
this._views.set(component, view);
};
MockViewResolver.prototype.setInlineTemplate = function(component, template) {
this._checkOverrideable(component);
this._inlineTemplates.set(component, template);
};
MockViewResolver.prototype.overrideViewDirective = function(component, from, to) {
this._checkOverrideable(component);
var overrides = this._directiveOverrides.get(component);
if (lang_1.isBlank(overrides)) {
overrides = new collection_1.Map();
this._directiveOverrides.set(component, overrides);
}
overrides.set(from, to);
};
MockViewResolver.prototype.resolve = function(component) {
var view = this._viewCache.get(component);
if (lang_1.isPresent(view))
return view;
view = this._views.get(component);
if (lang_1.isBlank(view)) {
view = _super.prototype.resolve.call(this, component);
}
var directives = view.directives;
var overrides = this._directiveOverrides.get(component);
if (lang_1.isPresent(overrides) && lang_1.isPresent(directives)) {
directives = collection_1.ListWrapper.clone(view.directives);
overrides.forEach(function(to, from) {
var srcIndex = directives.indexOf(from);
if (srcIndex == -1) {
throw new exceptions_1.BaseException("Overriden directive " + lang_1.stringify(from) + " not found in the template of " + lang_1.stringify(component));
}
directives[srcIndex] = to;
});
view = new metadata_1.ViewMetadata({
template: view.template,
templateUrl: view.templateUrl,
directives: directives
});
}
var inlineTemplate = this._inlineTemplates.get(component);
if (lang_1.isPresent(inlineTemplate)) {
view = new metadata_1.ViewMetadata({
template: inlineTemplate,
templateUrl: null,
directives: view.directives
});
}
this._viewCache.set(component, view);
return view;
};
MockViewResolver.prototype._checkOverrideable = function(component) {
var cached = this._viewCache.get(component);
if (lang_1.isPresent(cached)) {
throw new exceptions_1.BaseException("The component " + lang_1.stringify(component) + " has already been compiled, its configuration can not be changed");
}
};
MockViewResolver = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], MockViewResolver);
return MockViewResolver;
}(view_resolver_1.ViewResolver));
exports.MockViewResolver = MockViewResolver;
global.define = __define;
return module.exports;
});
System.register("angular2/src/router/location/location_strategy", ["angular2/src/facade/lang", "angular2/core"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var lang_1 = require("angular2/src/facade/lang");
var core_1 = require("angular2/core");
var LocationStrategy = (function() {
function LocationStrategy() {}
return LocationStrategy;
}());
exports.LocationStrategy = LocationStrategy;
exports.APP_BASE_HREF = lang_1.CONST_EXPR(new core_1.OpaqueToken('appBaseHref'));
function normalizeQueryParams(params) {
return (params.length > 0 && params.substring(0, 1) != '?') ? ('?' + params) : params;
}
exports.normalizeQueryParams = normalizeQueryParams;
function joinWithSlash(start, end) {
if (start.length == 0) {
return end;
}
if (end.length == 0) {
return start;
}
var slashes = 0;
if (start.endsWith('/')) {
slashes++;
}
if (end.startsWith('/')) {
slashes++;
}
if (slashes == 2) {
return start + end.substring(1);
}
if (slashes == 1) {
return start + end;
}
return start + '/' + end;
}
exports.joinWithSlash = joinWithSlash;
global.define = __define;
return module.exports;
});
System.register("angular2/src/mock/ng_zone_mock", ["angular2/src/core/di", "angular2/src/core/zone/ng_zone", "angular2/src/facade/async"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var di_1 = require("angular2/src/core/di");
var ng_zone_1 = require("angular2/src/core/zone/ng_zone");
var async_1 = require("angular2/src/facade/async");
var MockNgZone = (function(_super) {
__extends(MockNgZone, _super);
function MockNgZone() {
_super.call(this, {enableLongStackTrace: false});
this._mockOnStable = new async_1.EventEmitter(false);
}
Object.defineProperty(MockNgZone.prototype, "onStable", {
get: function() {
return this._mockOnStable;
},
enumerable: true,
configurable: true
});
MockNgZone.prototype.run = function(fn) {
return fn();
};
MockNgZone.prototype.runOutsideAngular = function(fn) {
return fn();
};
MockNgZone.prototype.simulateZoneExit = function() {
async_1.ObservableWrapper.callNext(this.onStable, null);
};
MockNgZone = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], MockNgZone);
return MockNgZone;
}(ng_zone_1.NgZone));
exports.MockNgZone = MockNgZone;
global.define = __define;
return module.exports;
});
System.register("angular2/src/testing/utils", ["angular2/core", "angular2/src/facade/collection", "angular2/src/platform/dom/dom_adapter", "angular2/src/facade/lang"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var core_1 = require("angular2/core");
var collection_1 = require("angular2/src/facade/collection");
var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter");
var lang_1 = require("angular2/src/facade/lang");
var Log = (function() {
function Log() {
this.logItems = [];
}
Log.prototype.add = function(value) {
this.logItems.push(value);
};
Log.prototype.fn = function(value) {
var _this = this;
return function(a1, a2, a3, a4, a5) {
if (a1 === void 0) {
a1 = null;
}
if (a2 === void 0) {
a2 = null;
}
if (a3 === void 0) {
a3 = null;
}
if (a4 === void 0) {
a4 = null;
}
if (a5 === void 0) {
a5 = null;
}
_this.logItems.push(value);
};
};
Log.prototype.clear = function() {
this.logItems = [];
};
Log.prototype.result = function() {
return this.logItems.join("; ");
};
Log = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [])], Log);
return Log;
}());
exports.Log = Log;
exports.browserDetection = null;
var BrowserDetection = (function() {
function BrowserDetection(ua) {
if (lang_1.isPresent(ua)) {
this._ua = ua;
} else {
this._ua = lang_1.isPresent(dom_adapter_1.DOM) ? dom_adapter_1.DOM.getUserAgent() : '';
}
}
BrowserDetection.setup = function() {
exports.browserDetection = new BrowserDetection(null);
};
Object.defineProperty(BrowserDetection.prototype, "isFirefox", {
get: function() {
return this._ua.indexOf('Firefox') > -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserDetection.prototype, "isAndroid", {
get: function() {
return this._ua.indexOf('Mozilla/5.0') > -1 && this._ua.indexOf('Android') > -1 && this._ua.indexOf('AppleWebKit') > -1 && this._ua.indexOf('Chrome') == -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserDetection.prototype, "isEdge", {
get: function() {
return this._ua.indexOf('Edge') > -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserDetection.prototype, "isIE", {
get: function() {
return this._ua.indexOf('Trident') > -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserDetection.prototype, "isWebkit", {
get: function() {
return this._ua.indexOf('AppleWebKit') > -1 && this._ua.indexOf('Edge') == -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserDetection.prototype, "isIOS7", {
get: function() {
return this._ua.indexOf('iPhone OS 7') > -1 || this._ua.indexOf('iPad OS 7') > -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserDetection.prototype, "isSlow", {
get: function() {
return this.isAndroid || this.isIE || this.isIOS7;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserDetection.prototype, "supportsIntlApi", {
get: function() {
return this._ua.indexOf('Chrome/4') > -1 && this._ua.indexOf('Edge') == -1;
},
enumerable: true,
configurable: true
});
return BrowserDetection;
}());
exports.BrowserDetection = BrowserDetection;
function dispatchEvent(element, eventType) {
dom_adapter_1.DOM.dispatchEvent(element, dom_adapter_1.DOM.createEvent(eventType));
}
exports.dispatchEvent = dispatchEvent;
function el(html) {
return dom_adapter_1.DOM.firstChild(dom_adapter_1.DOM.content(dom_adapter_1.DOM.createTemplate(html)));
}
exports.el = el;
var _RE_SPECIAL_CHARS = ['-', '[', ']', '/', '{', '}', '\\', '(', ')', '*', '+', '?', '.', '^', '$', '|'];
var _ESCAPE_RE = lang_1.RegExpWrapper.create("[\\" + _RE_SPECIAL_CHARS.join('\\') + "]");
function containsRegexp(input) {
return lang_1.RegExpWrapper.create(lang_1.StringWrapper.replaceAllMapped(input, _ESCAPE_RE, function(match) {
return ("\\" + match[0]);
}));
}
exports.containsRegexp = containsRegexp;
function normalizeCSS(css) {
css = lang_1.StringWrapper.replaceAll(css, /\s+/g, ' ');
css = lang_1.StringWrapper.replaceAll(css, /:\s/g, ':');
css = lang_1.StringWrapper.replaceAll(css, /'/g, '"');
css = lang_1.StringWrapper.replaceAll(css, / }/g, '}');
css = lang_1.StringWrapper.replaceAllMapped(css, /url\((\"|\s)(.+)(\"|\s)\)(\s*)/g, function(match) {
return ("url(\"" + match[2] + "\")");
});
css = lang_1.StringWrapper.replaceAllMapped(css, /\[(.+)=([^"\]]+)\]/g, function(match) {
return ("[" + match[1] + "=\"" + match[2] + "\"]");
});
return css;
}
exports.normalizeCSS = normalizeCSS;
var _singleTagWhitelist = ['br', 'hr', 'input'];
function stringifyElement(el) {
var result = '';
if (dom_adapter_1.DOM.isElementNode(el)) {
var tagName = dom_adapter_1.DOM.tagName(el).toLowerCase();
result += "<" + tagName;
var attributeMap = dom_adapter_1.DOM.attributeMap(el);
var keys = [];
attributeMap.forEach(function(v, k) {
return keys.push(k);
});
collection_1.ListWrapper.sort(keys);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var attValue = attributeMap.get(key);
if (!lang_1.isString(attValue)) {
result += " " + key;
} else {
result += " " + key + "=\"" + attValue + "\"";
}
}
result += '>';
var childrenRoot = dom_adapter_1.DOM.templateAwareRoot(el);
var children = lang_1.isPresent(childrenRoot) ? dom_adapter_1.DOM.childNodes(childrenRoot) : [];
for (var j = 0; j < children.length; j++) {
result += stringifyElement(children[j]);
}
if (!collection_1.ListWrapper.contains(_singleTagWhitelist, tagName)) {
result += "</" + tagName + ">";
}
} else if (dom_adapter_1.DOM.isCommentNode(el)) {
result += "<!--" + dom_adapter_1.DOM.nodeValue(el) + "-->";
} else {
result += dom_adapter_1.DOM.getText(el);
}
return result;
}
exports.stringifyElement = stringifyElement;
global.define = __define;
return module.exports;
});
System.register("angular2/src/mock/mock_location_strategy", ["angular2/src/core/di", "angular2/src/facade/async", "angular2/src/router/location/location_strategy"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var di_1 = require("angular2/src/core/di");
var async_1 = require("angular2/src/facade/async");
var location_strategy_1 = require("angular2/src/router/location/location_strategy");
var MockLocationStrategy = (function(_super) {
__extends(MockLocationStrategy, _super);
function MockLocationStrategy() {
_super.call(this);
this.internalBaseHref = '/';
this.internalPath = '/';
this.internalTitle = '';
this.urlChanges = [];
this._subject = new async_1.EventEmitter();
}
MockLocationStrategy.prototype.simulatePopState = function(url) {
this.internalPath = url;
async_1.ObservableWrapper.callEmit(this._subject, new _MockPopStateEvent(this.path()));
};
MockLocationStrategy.prototype.path = function() {
return this.internalPath;
};
MockLocationStrategy.prototype.prepareExternalUrl = function(internal) {
if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) {
return this.internalBaseHref + internal.substring(1);
}
return this.internalBaseHref + internal;
};
MockLocationStrategy.prototype.pushState = function(ctx, title, path, query) {
this.internalTitle = title;
var url = path + (query.length > 0 ? ('?' + query) : '');
this.internalPath = url;
var externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push(externalUrl);
};
MockLocationStrategy.prototype.replaceState = function(ctx, title, path, query) {
this.internalTitle = title;
var url = path + (query.length > 0 ? ('?' + query) : '');
this.internalPath = url;
var externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push('replace: ' + externalUrl);
};
MockLocationStrategy.prototype.onPopState = function(fn) {
async_1.ObservableWrapper.subscribe(this._subject, fn);
};
MockLocationStrategy.prototype.getBaseHref = function() {
return this.internalBaseHref;
};
MockLocationStrategy.prototype.back = function() {
if (this.urlChanges.length > 0) {
this.urlChanges.pop();
var nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : '';
this.simulatePopState(nextUrl);
}
};
MockLocationStrategy.prototype.forward = function() {
throw 'not implemented';
};
MockLocationStrategy = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], MockLocationStrategy);
return MockLocationStrategy;
}(location_strategy_1.LocationStrategy));
exports.MockLocationStrategy = MockLocationStrategy;
var _MockPopStateEvent = (function() {
function _MockPopStateEvent(newUrl) {
this.newUrl = newUrl;
this.pop = true;
this.type = 'popstate';
}
return _MockPopStateEvent;
}());
global.define = __define;
return module.exports;
});
System.register("angular2/src/testing/test_component_builder", ["angular2/core", "angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/testing/utils", "angular2/src/platform/dom/dom_tokens", "angular2/src/platform/dom/dom_adapter", "angular2/src/core/debug/debug_node"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var core_1 = require("angular2/core");
var lang_1 = require("angular2/src/facade/lang");
var collection_1 = require("angular2/src/facade/collection");
var utils_1 = require("angular2/src/testing/utils");
var dom_tokens_1 = require("angular2/src/platform/dom/dom_tokens");
var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter");
var debug_node_1 = require("angular2/src/core/debug/debug_node");
var ComponentFixture = (function() {
function ComponentFixture() {}
return ComponentFixture;
}());
exports.ComponentFixture = ComponentFixture;
var ComponentFixture_ = (function(_super) {
__extends(ComponentFixture_, _super);
function ComponentFixture_(componentRef) {
_super.call(this);
this._componentParentView = componentRef.hostView.internalView;
this.elementRef = this._componentParentView.appElements[0].ref;
this.debugElement = debug_node_1.getDebugNode(this._componentParentView.rootNodesOrAppElements[0].nativeElement);
this.componentInstance = this.debugElement.componentInstance;
this.nativeElement = this.debugElement.nativeElement;
this._componentRef = componentRef;
}
ComponentFixture_.prototype.detectChanges = function() {
this._componentParentView.changeDetector.detectChanges();
this._componentParentView.changeDetector.checkNoChanges();
};
ComponentFixture_.prototype.destroy = function() {
this._componentRef.dispose();
};
return ComponentFixture_;
}(ComponentFixture));
exports.ComponentFixture_ = ComponentFixture_;
var _nextRootElementId = 0;
var TestComponentBuilder = (function() {
function TestComponentBuilder(_injector) {
this._injector = _injector;
this._bindingsOverrides = new Map();
this._directiveOverrides = new Map();
this._templateOverrides = new Map();
this._viewBindingsOverrides = new Map();
this._viewOverrides = new Map();
}
TestComponentBuilder.prototype._clone = function() {
var clone = new TestComponentBuilder(this._injector);
clone._viewOverrides = collection_1.MapWrapper.clone(this._viewOverrides);
clone._directiveOverrides = collection_1.MapWrapper.clone(this._directiveOverrides);
clone._templateOverrides = collection_1.MapWrapper.clone(this._templateOverrides);
return clone;
};
TestComponentBuilder.prototype.overrideTemplate = function(componentType, template) {
var clone = this._clone();
clone._templateOverrides.set(componentType, template);
return clone;
};
TestComponentBuilder.prototype.overrideView = function(componentType, view) {
var clone = this._clone();
clone._viewOverrides.set(componentType, view);
return clone;
};
TestComponentBuilder.prototype.overrideDirective = function(componentType, from, to) {
var clone = this._clone();
var overridesForComponent = clone._directiveOverrides.get(componentType);
if (!lang_1.isPresent(overridesForComponent)) {
clone._directiveOverrides.set(componentType, new Map());
overridesForComponent = clone._directiveOverrides.get(componentType);
}
overridesForComponent.set(from, to);
return clone;
};
TestComponentBuilder.prototype.overrideProviders = function(type, providers) {
var clone = this._clone();
clone._bindingsOverrides.set(type, providers);
return clone;
};
TestComponentBuilder.prototype.overrideBindings = function(type, providers) {
return this.overrideProviders(type, providers);
};
TestComponentBuilder.prototype.overrideViewProviders = function(type, providers) {
var clone = this._clone();
clone._viewBindingsOverrides.set(type, providers);
return clone;
};
TestComponentBuilder.prototype.overrideViewBindings = function(type, providers) {
return this.overrideViewProviders(type, providers);
};
TestComponentBuilder.prototype.createAsync = function(rootComponentType) {
var mockDirectiveResolver = this._injector.get(core_1.DirectiveResolver);
var mockViewResolver = this._injector.get(core_1.ViewResolver);
this._viewOverrides.forEach(function(view, type) {
return mockViewResolver.setView(type, view);
});
this._templateOverrides.forEach(function(template, type) {
return mockViewResolver.setInlineTemplate(type, template);
});
this._directiveOverrides.forEach(function(overrides, component) {
overrides.forEach(function(to, from) {
mockViewResolver.overrideViewDirective(component, from, to);
});
});
this._bindingsOverrides.forEach(function(bindings, type) {
return mockDirectiveResolver.setBindingsOverride(type, bindings);
});
this._viewBindingsOverrides.forEach(function(bindings, type) {
return mockDirectiveResolver.setViewBindingsOverride(type, bindings);
});
var rootElId = "root" + _nextRootElementId++;
var rootEl = utils_1.el("<div id=\"" + rootElId + "\"></div>");
var doc = this._injector.get(dom_tokens_1.DOCUMENT);
var oldRoots = dom_adapter_1.DOM.querySelectorAll(doc, '[id^=root]');
for (var i = 0; i < oldRoots.length; i++) {
dom_adapter_1.DOM.remove(oldRoots[i]);
}
dom_adapter_1.DOM.appendChild(doc.body, rootEl);
var promise = this._injector.get(core_1.DynamicComponentLoader).loadAsRoot(rootComponentType, "#" + rootElId, this._injector);
return promise.then(function(componentRef) {
return new ComponentFixture_(componentRef);
});
};
TestComponentBuilder = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [core_1.Injector])], TestComponentBuilder);
return TestComponentBuilder;
}());
exports.TestComponentBuilder = TestComponentBuilder;
global.define = __define;
return module.exports;
});
System.register("angular2/platform/testing/browser_static", ["angular2/core", "angular2/src/platform/browser_common", "angular2/src/platform/browser/browser_adapter", "angular2/src/animate/animation_builder", "angular2/src/mock/animation_builder_mock", "angular2/src/mock/directive_resolver_mock", "angular2/src/mock/view_resolver_mock", "angular2/src/mock/mock_location_strategy", "angular2/src/router/location/location_strategy", "angular2/src/mock/ng_zone_mock", "angular2/src/platform/browser/xhr_impl", "angular2/compiler", "angular2/src/testing/test_component_builder", "angular2/src/testing/utils", "angular2/platform/common_dom", "angular2/src/facade/lang", "angular2/src/testing/utils"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var core_1 = require("angular2/core");
var browser_common_1 = require("angular2/src/platform/browser_common");
var browser_adapter_1 = require("angular2/src/platform/browser/browser_adapter");
var animation_builder_1 = require("angular2/src/animate/animation_builder");
var animation_builder_mock_1 = require("angular2/src/mock/animation_builder_mock");
var directive_resolver_mock_1 = require("angular2/src/mock/directive_resolver_mock");
var view_resolver_mock_1 = require("angular2/src/mock/view_resolver_mock");
var mock_location_strategy_1 = require("angular2/src/mock/mock_location_strategy");
var location_strategy_1 = require("angular2/src/router/location/location_strategy");
var ng_zone_mock_1 = require("angular2/src/mock/ng_zone_mock");
var xhr_impl_1 = require("angular2/src/platform/browser/xhr_impl");
var compiler_1 = require("angular2/compiler");
var test_component_builder_1 = require("angular2/src/testing/test_component_builder");
var utils_1 = require("angular2/src/testing/utils");
var common_dom_1 = require("angular2/platform/common_dom");
var lang_1 = require("angular2/src/facade/lang");
var utils_2 = require("angular2/src/testing/utils");
function initBrowserTests() {
browser_adapter_1.BrowserDomAdapter.makeCurrent();
utils_1.BrowserDetection.setup();
}
exports.TEST_BROWSER_STATIC_PLATFORM_PROVIDERS = lang_1.CONST_EXPR([core_1.PLATFORM_COMMON_PROVIDERS, new core_1.Provider(core_1.PLATFORM_INITIALIZER, {
useValue: initBrowserTests,
multi: true
})]);
exports.ADDITIONAL_TEST_BROWSER_PROVIDERS = lang_1.CONST_EXPR([new core_1.Provider(core_1.APP_ID, {useValue: 'a'}), common_dom_1.ELEMENT_PROBE_PROVIDERS, new core_1.Provider(core_1.DirectiveResolver, {useClass: directive_resolver_mock_1.MockDirectiveResolver}), new core_1.Provider(core_1.ViewResolver, {useClass: view_resolver_mock_1.MockViewResolver}), utils_2.Log, test_component_builder_1.TestComponentBuilder, new core_1.Provider(core_1.NgZone, {useClass: ng_zone_mock_1.MockNgZone}), new core_1.Provider(location_strategy_1.LocationStrategy, {useClass: mock_location_strategy_1.MockLocationStrategy}), new core_1.Provider(animation_builder_1.AnimationBuilder, {useClass: animation_builder_mock_1.MockAnimationBuilder})]);
exports.TEST_BROWSER_STATIC_APPLICATION_PROVIDERS = lang_1.CONST_EXPR([browser_common_1.BROWSER_APP_COMMON_PROVIDERS, new core_1.Provider(compiler_1.XHR, {useClass: xhr_impl_1.XHRImpl}), exports.ADDITIONAL_TEST_BROWSER_PROVIDERS]);
global.define = __define;
return module.exports;
});
System.register("angular2/platform/testing/browser", ["angular2/platform/testing/browser_static", "angular2/platform/browser", "angular2/src/facade/lang", "angular2/platform/browser"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var browser_static_1 = require("angular2/platform/testing/browser_static");
var browser_1 = require("angular2/platform/browser");
var lang_1 = require("angular2/src/facade/lang");
var browser_2 = require("angular2/platform/browser");
exports.CACHED_TEMPLATE_PROVIDER = browser_2.CACHED_TEMPLATE_PROVIDER;
exports.TEST_BROWSER_PLATFORM_PROVIDERS = lang_1.CONST_EXPR([browser_static_1.TEST_BROWSER_STATIC_PLATFORM_PROVIDERS]);
exports.TEST_BROWSER_APPLICATION_PROVIDERS = lang_1.CONST_EXPR([browser_1.BROWSER_APP_PROVIDERS, browser_static_1.ADDITIONAL_TEST_BROWSER_PROVIDERS]);
global.define = __define;
return module.exports;
});
System.register("angular2/src/mock/location_mock", ["angular2/src/core/di", "angular2/src/facade/async"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var di_1 = require("angular2/src/core/di");
var async_1 = require("angular2/src/facade/async");
var SpyLocation = (function() {
function SpyLocation() {
this.urlChanges = [];
this._path = '';
this._query = '';
this._subject = new async_1.EventEmitter();
this._baseHref = '';
this.platformStrategy = null;
}
SpyLocation.prototype.setInitialPath = function(url) {
this._path = url;
};
SpyLocation.prototype.setBaseHref = function(url) {
this._baseHref = url;
};
SpyLocation.prototype.path = function() {
return this._path;
};
SpyLocation.prototype.simulateUrlPop = function(pathname) {
async_1.ObservableWrapper.callEmit(this._subject, {
'url': pathname,
'pop': true
});
};
SpyLocation.prototype.simulateHashChange = function(pathname) {
this.setInitialPath(pathname);
this.urlChanges.push('hash: ' + pathname);
async_1.ObservableWrapper.callEmit(this._subject, {
'url': pathname,
'pop': true,
'type': 'hashchange'
});
};
SpyLocation.prototype.prepareExternalUrl = function(url) {
if (url.length > 0 && !url.startsWith('/')) {
url = '/' + url;
}
return this._baseHref + url;
};
SpyLocation.prototype.go = function(path, query) {
if (query === void 0) {
query = '';
}
path = this.prepareExternalUrl(path);
if (this._path == path && this._query == query) {
return ;
}
this._path = path;
this._query = query;
var url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push(url);
};
SpyLocation.prototype.replaceState = function(path, query) {
if (query === void 0) {
query = '';
}
path = this.prepareExternalUrl(path);
this._path = path;
this._query = query;
var url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push('replace: ' + url);
};
SpyLocation.prototype.forward = function() {};
SpyLocation.prototype.back = function() {};
SpyLocation.prototype.subscribe = function(onNext, onThrow, onReturn) {
if (onThrow === void 0) {
onThrow = null;
}
if (onReturn === void 0) {
onReturn = null;
}
return async_1.ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn);
};
SpyLocation.prototype.normalize = function(url) {
return null;
};
SpyLocation = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], SpyLocation);
return SpyLocation;
}());
exports.SpyLocation = SpyLocation;
global.define = __define;
return module.exports;
});
System.register("angular2/router/testing", ["angular2/src/mock/mock_location_strategy", "angular2/src/mock/location_mock"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
function __export(m) {
for (var p in m)
if (!exports.hasOwnProperty(p))
exports[p] = m[p];
}
__export(require("angular2/src/mock/mock_location_strategy"));
__export(require("angular2/src/mock/location_mock"));
global.define = __define;
return module.exports;
});
System.register("angular2/src/http/headers", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var lang_1 = require("angular2/src/facade/lang");
var exceptions_1 = require("angular2/src/facade/exceptions");
var collection_1 = require("angular2/src/facade/collection");
var Headers = (function() {
function Headers(headers) {
var _this = this;
if (headers instanceof Headers) {
this._headersMap = headers._headersMap;
return ;
}
this._headersMap = new collection_1.Map();
if (lang_1.isBlank(headers)) {
return ;
}
collection_1.StringMapWrapper.forEach(headers, function(v, k) {
_this._headersMap.set(k, collection_1.isListLikeIterable(v) ? v : [v]);
});
}
Headers.fromResponseHeaderString = function(headersString) {
return headersString.trim().split('\n').map(function(val) {
return val.split(':');
}).map(function(_a) {
var key = _a[0],
parts = _a.slice(1);
return ([key.trim(), parts.join(':').trim()]);
}).reduce(function(headers, _a) {
var key = _a[0],
value = _a[1];
return !headers.set(key, value) && headers;
}, new Headers());
};
Headers.prototype.append = function(name, value) {
var mapName = this._headersMap.get(name);
var list = collection_1.isListLikeIterable(mapName) ? mapName : [];
list.push(value);
this._headersMap.set(name, list);
};
Headers.prototype.delete = function(name) {
this._headersMap.delete(name);
};
Headers.prototype.forEach = function(fn) {
this._headersMap.forEach(fn);
};
Headers.prototype.get = function(header) {
return collection_1.ListWrapper.first(this._headersMap.get(header));
};
Headers.prototype.has = function(header) {
return this._headersMap.has(header);
};
Headers.prototype.keys = function() {
return collection_1.MapWrapper.keys(this._headersMap);
};
Headers.prototype.set = function(header, value) {
var list = [];
if (collection_1.isListLikeIterable(value)) {
var pushValue = value.join(',');
list.push(pushValue);
} else {
list.push(value);
}
this._headersMap.set(header, list);
};
Headers.prototype.values = function() {
return collection_1.MapWrapper.values(this._headersMap);
};
Headers.prototype.toJSON = function() {
var serializableHeaders = {};
this._headersMap.forEach(function(values, name) {
var list = [];
collection_1.iterateListLike(values, function(val) {
return list = collection_1.ListWrapper.concat(list, val.split(','));
});
serializableHeaders[name] = list;
});
return serializableHeaders;
};
Headers.prototype.getAll = function(header) {
var headers = this._headersMap.get(header);
return collection_1.isListLikeIterable(headers) ? headers : [];
};
Headers.prototype.entries = function() {
throw new exceptions_1.BaseException('"entries" method is not implemented on Headers class');
};
return Headers;
}());
exports.Headers = Headers;
global.define = __define;
return module.exports;
});
System.register("angular2/src/http/enums", [], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
(function(RequestMethod) {
RequestMethod[RequestMethod["Get"] = 0] = "Get";
RequestMethod[RequestMethod["Post"] = 1] = "Post";
RequestMethod[RequestMethod["Put"] = 2] = "Put";
RequestMethod[RequestMethod["Delete"] = 3] = "Delete";
RequestMethod[RequestMethod["Options"] = 4] = "Options";
RequestMethod[RequestMethod["Head"] = 5] = "Head";
RequestMethod[RequestMethod["Patch"] = 6] = "Patch";
})(exports.RequestMethod || (exports.RequestMethod = {}));
var RequestMethod = exports.RequestMethod;
(function(ReadyState) {
ReadyState[ReadyState["Unsent"] = 0] = "Unsent";
ReadyState[ReadyState["Open"] = 1] = "Open";
ReadyState[ReadyState["HeadersReceived"] = 2] = "HeadersReceived";
ReadyState[ReadyState["Loading"] = 3] = "Loading";
ReadyState[ReadyState["Done"] = 4] = "Done";
ReadyState[ReadyState["Cancelled"] = 5] = "Cancelled";
})(exports.ReadyState || (exports.ReadyState = {}));
var ReadyState = exports.ReadyState;
(function(ResponseType) {
ResponseType[ResponseType["Basic"] = 0] = "Basic";
ResponseType[ResponseType["Cors"] = 1] = "Cors";
ResponseType[ResponseType["Default"] = 2] = "Default";
ResponseType[ResponseType["Error"] = 3] = "Error";
ResponseType[ResponseType["Opaque"] = 4] = "Opaque";
})(exports.ResponseType || (exports.ResponseType = {}));
var ResponseType = exports.ResponseType;
global.define = __define;
return module.exports;
});
System.register("angular2/src/http/http_utils", ["angular2/src/facade/lang", "angular2/src/http/enums", "angular2/src/facade/exceptions", "angular2/src/facade/lang"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var lang_1 = require("angular2/src/facade/lang");
var enums_1 = require("angular2/src/http/enums");
var exceptions_1 = require("angular2/src/facade/exceptions");
function normalizeMethodName(method) {
if (lang_1.isString(method)) {
var originalMethod = method;
method = method.replace(/(\w)(\w*)/g, function(g0, g1, g2) {
return g1.toUpperCase() + g2.toLowerCase();
});
method = enums_1.RequestMethod[method];
if (typeof method !== 'number')
throw exceptions_1.makeTypeError("Invalid request method. The method \"" + originalMethod + "\" is not supported.");
}
return method;
}
exports.normalizeMethodName = normalizeMethodName;
exports.isSuccess = function(status) {
return (status >= 200 && status < 300);
};
function getResponseURL(xhr) {
if ('responseURL' in xhr) {
return xhr.responseURL;
}
if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
return xhr.getResponseHeader('X-Request-URL');
}
return ;
}
exports.getResponseURL = getResponseURL;
var lang_2 = require("angular2/src/facade/lang");
exports.isJsObject = lang_2.isJsObject;
global.define = __define;
return module.exports;
});
System.register("angular2/src/http/static_request", ["angular2/src/http/headers", "angular2/src/http/http_utils", "angular2/src/facade/lang"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var headers_1 = require("angular2/src/http/headers");
var http_utils_1 = require("angular2/src/http/http_utils");
var lang_1 = require("angular2/src/facade/lang");
var Request = (function() {
function Request(requestOptions) {
var url = requestOptions.url;
this.url = requestOptions.url;
if (lang_1.isPresent(requestOptions.search)) {
var search = requestOptions.search.toString();
if (search.length > 0) {
var prefix = '?';
if (lang_1.StringWrapper.contains(this.url, '?')) {
prefix = (this.url[this.url.length - 1] == '&') ? '' : '&';
}
this.url = url + prefix + search;
}
}
this._body = requestOptions.body;
this.method = http_utils_1.normalizeMethodName(requestOptions.method);
this.headers = new headers_1.Headers(requestOptions.headers);
}
Request.prototype.text = function() {
return lang_1.isPresent(this._body) ? this._body.toString() : '';
};
return Request;
}());
exports.Request = Request;
global.define = __define;
return module.exports;
});
System.register("angular2/src/http/backends/mock_backend", ["angular2/core", "angular2/src/http/static_request", "angular2/src/http/enums", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "rxjs/Subject", "rxjs/subject/ReplaySubject", "rxjs/operator/take"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var core_1 = require("angular2/core");
var static_request_1 = require("angular2/src/http/static_request");
var enums_1 = require("angular2/src/http/enums");
var lang_1 = require("angular2/src/facade/lang");
var exceptions_1 = require("angular2/src/facade/exceptions");
var Subject_1 = require("rxjs/Subject");
var ReplaySubject_1 = require("rxjs/subject/ReplaySubject");
var take_1 = require("rxjs/operator/take");
var MockConnection = (function() {
function MockConnection(req) {
this.response = take_1.take.call(new ReplaySubject_1.ReplaySubject(1), 1);
this.readyState = enums_1.ReadyState.Open;
this.request = req;
}
MockConnection.prototype.mockRespond = function(res) {
if (this.readyState === enums_1.ReadyState.Done || this.readyState === enums_1.ReadyState.Cancelled) {
throw new exceptions_1.BaseException('Connection has already been resolved');
}
this.readyState = enums_1.ReadyState.Done;
this.response.next(res);
this.response.complete();
};
MockConnection.prototype.mockDownload = function(res) {};
MockConnection.prototype.mockError = function(err) {
this.readyState = enums_1.ReadyState.Done;
this.response.error(err);
};
return MockConnection;
}());
exports.MockConnection = MockConnection;
var MockBackend = (function() {
function MockBackend() {
var _this = this;
this.connectionsArray = [];
this.connections = new Subject_1.Subject();
this.connections.subscribe(function(connection) {
return _this.connectionsArray.push(connection);
});
this.pendingConnections = new Subject_1.Subject();
}
MockBackend.prototype.verifyNoPendingRequests = function() {
var pending = 0;
this.pendingConnections.subscribe(function(c) {
return pending++;
});
if (pending > 0)
throw new exceptions_1.BaseException(pending + " pending connections to be resolved");
};
MockBackend.prototype.resolveAllConnections = function() {
this.connections.subscribe(function(c) {
return c.readyState = 4;
});
};
MockBackend.prototype.createConnection = function(req) {
if (!lang_1.isPresent(req) || !(req instanceof static_request_1.Request)) {
throw new exceptions_1.BaseException("createConnection requires an instance of Request, got " + req);
}
var connection = new MockConnection(req);
this.connections.next(connection);
return connection;
};
MockBackend = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [])], MockBackend);
return MockBackend;
}());
exports.MockBackend = MockBackend;
global.define = __define;
return module.exports;
});
System.register("angular2/http/testing", ["angular2/src/http/backends/mock_backend"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
function __export(m) {
for (var p in m)
if (!exports.hasOwnProperty(p))
exports[p] = m[p];
}
__export(require("angular2/src/http/backends/mock_backend"));
global.define = __define;
return module.exports;
});
System.register("angular2/src/testing/fake_async", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var lang_1 = require("angular2/src/facade/lang");
var exceptions_1 = require("angular2/src/facade/exceptions");
var collection_1 = require("angular2/src/facade/collection");
var _scheduler;
var _microtasks = [];
var _pendingPeriodicTimers = [];
var _pendingTimers = [];
var FakeAsyncZoneSpec = (function() {
function FakeAsyncZoneSpec() {
this.name = 'fakeAsync';
this.properties = {'inFakeAsyncZone': true};
}
FakeAsyncZoneSpec.assertInZone = function() {
if (!Zone.current.get('inFakeAsyncZone')) {
throw new Error('The code should be running in the fakeAsync zone to call this function');
}
};
FakeAsyncZoneSpec.prototype.onScheduleTask = function(delegate, current, target, task) {
switch (task.type) {
case 'microTask':
_microtasks.push(task.invoke);
break;
case 'macroTask':
switch (task.source) {
case 'setTimeout':
task.data['handleId'] = _setTimeout(task.invoke, task.data['delay'], task.data['args']);
break;
case 'setInterval':
task.data['handleId'] = _setInterval(task.invoke, task.data['delay'], task.data['args']);
break;
default:
task = delegate.scheduleTask(target, task);
}
break;
case 'eventTask':
task = delegate.scheduleTask(target, task);
break;
}
return task;
};
FakeAsyncZoneSpec.prototype.onCancelTask = function(delegate, current, target, task) {
switch (task.source) {
case 'setTimeout':
return _clearTimeout(task.data['handleId']);
case 'setInterval':
return _clearInterval(task.data['handleId']);
default:
return delegate.scheduleTask(target, task);
}
};
return FakeAsyncZoneSpec;
}());
function fakeAsync(fn) {
if (Zone.current.get('inFakeAsyncZone')) {
throw new Error('fakeAsync() calls can not be nested');
}
var fakeAsyncZone = Zone.current.fork(new FakeAsyncZoneSpec());
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
_scheduler = new jasmine.DelayedFunctionScheduler();
clearPendingTimers();
var res = fakeAsyncZone.run(function() {
var res = fn.apply(void 0, args);
flushMicrotasks();
return res;
});
if (_pendingPeriodicTimers.length > 0) {
throw new exceptions_1.BaseException(_pendingPeriodicTimers.length + " periodic timer(s) still in the queue.");
}
if (_pendingTimers.length > 0) {
throw new exceptions_1.BaseException(_pendingTimers.length + " timer(s) still in the queue.");
}
_scheduler = null;
collection_1.ListWrapper.clear(_microtasks);
return res;
};
}
exports.fakeAsync = fakeAsync;
function clearPendingTimers() {
collection_1.ListWrapper.clear(_microtasks);
collection_1.ListWrapper.clear(_pendingPeriodicTimers);
collection_1.ListWrapper.clear(_pendingTimers);
}
exports.clearPendingTimers = clearPendingTimers;
function tick(millis) {
if (millis === void 0) {
millis = 0;
}
FakeAsyncZoneSpec.assertInZone();
flushMicrotasks();
_scheduler.tick(millis);
}
exports.tick = tick;
function flushMicrotasks() {
FakeAsyncZoneSpec.assertInZone();
while (_microtasks.length > 0) {
var microtask = collection_1.ListWrapper.removeAt(_microtasks, 0);
microtask();
}
}
exports.flushMicrotasks = flushMicrotasks;
function _setTimeout(fn, delay, args) {
var cb = _fnAndFlush(fn);
var id = _scheduler.scheduleFunction(cb, delay, args);
_pendingTimers.push(id);
_scheduler.scheduleFunction(_dequeueTimer(id), delay);
return id;
}
function _clearTimeout(id) {
_dequeueTimer(id);
return _scheduler.removeFunctionWithId(id);
}
function _setInterval(fn, interval) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var cb = _fnAndFlush(fn);
var id = _scheduler.scheduleFunction(cb, interval, args, true);
_pendingPeriodicTimers.push(id);
return id;
}
function _clearInterval(id) {
collection_1.ListWrapper.remove(_pendingPeriodicTimers, id);
return _scheduler.removeFunctionWithId(id);
}
function _fnAndFlush(fn) {
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
fn.apply(lang_1.global, args);
flushMicrotasks();
};
}
function _dequeueTimer(id) {
return function() {
collection_1.ListWrapper.remove(_pendingTimers, id);
};
}
global.define = __define;
return module.exports;
});
System.register("angular2/src/mock/mock_application_ref", ["angular2/src/core/application_ref", "angular2/src/core/di"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
};
var application_ref_1 = require("angular2/src/core/application_ref");
var di_1 = require("angular2/src/core/di");
var MockApplicationRef = (function(_super) {
__extends(MockApplicationRef, _super);
function MockApplicationRef() {
_super.apply(this, arguments);
}
MockApplicationRef.prototype.registerBootstrapListener = function(listener) {};
MockApplicationRef.prototype.registerDisposeListener = function(dispose) {};
MockApplicationRef.prototype.bootstrap = function(componentType, bindings) {
return null;
};
Object.defineProperty(MockApplicationRef.prototype, "injector", {
get: function() {
return null;
},
enumerable: true,
configurable: true
});
;
Object.defineProperty(MockApplicationRef.prototype, "zone", {
get: function() {
return null;
},
enumerable: true,
configurable: true
});
;
MockApplicationRef.prototype.dispose = function() {};
MockApplicationRef.prototype.tick = function() {};
Object.defineProperty(MockApplicationRef.prototype, "componentTypes", {
get: function() {
return null;
},
enumerable: true,
configurable: true
});
;
MockApplicationRef = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], MockApplicationRef);
return MockApplicationRef;
}(application_ref_1.ApplicationRef));
exports.MockApplicationRef = MockApplicationRef;
global.define = __define;
return module.exports;
});
System.register("angular2/src/testing/matchers", ["angular2/src/platform/dom/dom_adapter", "angular2/src/facade/lang", "angular2/src/facade/collection"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter");
var lang_1 = require("angular2/src/facade/lang");
var collection_1 = require("angular2/src/facade/collection");
var _global = (typeof window === 'undefined' ? lang_1.global : window);
exports.expect = _global.expect;
Map.prototype['jasmineToString'] = function() {
var m = this;
if (!m) {
return '' + m;
}
var res = [];
m.forEach(function(v, k) {
res.push(k + ":" + v);
});
return "{ " + res.join(',') + " }";
};
_global.beforeEach(function() {
jasmine.addMatchers({
toEqual: function(util, customEqualityTesters) {
return {compare: function(actual, expected) {
return {pass: util.equals(actual, expected, [compareMap])};
}};
function compareMap(actual, expected) {
if (actual instanceof Map) {
var pass = actual.size === expected.size;
if (pass) {
actual.forEach(function(v, k) {
pass = pass && util.equals(v, expected.get(k));
});
}
return pass;
} else {
return undefined;
}
}
},
toBePromise: function() {
return {compare: function(actual, expectedClass) {
var pass = typeof actual === 'object' && typeof actual.then === 'function';
return {
pass: pass,
get message() {
return 'Expected ' + actual + ' to be a promise';
}
};
}};
},
toBeAnInstanceOf: function() {
return {compare: function(actual, expectedClass) {
var pass = typeof actual === 'object' && actual instanceof expectedClass;
return {
pass: pass,
get message() {
return 'Expected ' + actual + ' to be an instance of ' + expectedClass;
}
};
}};
},
toHaveText: function() {
return {compare: function(actual, expectedText) {
var actualText = elementText(actual);
return {
pass: actualText == expectedText,
get message() {
return 'Expected ' + actualText + ' to be equal to ' + expectedText;
}
};
}};
},
toHaveCssClass: function() {
return {
compare: buildError(false),
negativeCompare: buildError(true)
};
function buildError(isNot) {
return function(actual, className) {
return {
pass: dom_adapter_1.DOM.hasClass(actual, className) == !isNot,
get message() {
return "Expected " + actual.outerHTML + " " + (isNot ? 'not ' : '') + "to contain the CSS class \"" + className + "\"";
}
};
};
}
},
toHaveCssStyle: function() {
return {compare: function(actual, styles) {
var allPassed;
if (lang_1.isString(styles)) {
allPassed = dom_adapter_1.DOM.hasStyle(actual, styles);
} else {
allPassed = !collection_1.StringMapWrapper.isEmpty(styles);
collection_1.StringMapWrapper.forEach(styles, function(style, prop) {
allPassed = allPassed && dom_adapter_1.DOM.hasStyle(actual, prop, style);
});
}
return {
pass: allPassed,
get message() {
var expectedValueStr = lang_1.isString(styles) ? styles : JSON.stringify(styles);
return "Expected " + actual.outerHTML + " " + (!allPassed ? ' ' : 'not ') + "to contain the\n CSS " + (lang_1.isString(styles) ? 'property' : 'styles') + " \"" + expectedValueStr + "\"";
}
};
}};
},
toContainError: function() {
return {compare: function(actual, expectedText) {
var errorMessage = actual.toString();
return {
pass: errorMessage.indexOf(expectedText) > -1,
get message() {
return 'Expected ' + errorMessage + ' to contain ' + expectedText;
}
};
}};
},
toThrowErrorWith: function() {
return {compare: function(actual, expectedText) {
try {
actual();
return {
pass: false,
get message() {
return "Was expected to throw, but did not throw";
}
};
} catch (e) {
var errorMessage = e.toString();
return {
pass: errorMessage.indexOf(expectedText) > -1,
get message() {
return 'Expected ' + errorMessage + ' to contain ' + expectedText;
}
};
}
}};
},
toMatchPattern: function() {
return {
compare: buildError(false),
negativeCompare: buildError(true)
};
function buildError(isNot) {
return function(actual, regex) {
return {
pass: regex.test(actual) == !isNot,
get message() {
return "Expected " + actual + " " + (isNot ? 'not ' : '') + "to match " + regex.toString();
}
};
};
}
},
toImplement: function() {
return {compare: function(actualObject, expectedInterface) {
var objProps = Object.keys(actualObject.constructor.prototype);
var intProps = Object.keys(expectedInterface.prototype);
var missedMethods = [];
intProps.forEach(function(k) {
if (!actualObject.constructor.prototype[k])
missedMethods.push(k);
});
return {
pass: missedMethods.length == 0,
get message() {
return 'Expected ' + actualObject + ' to have the following methods: ' + missedMethods.join(", ");
}
};
}};
}
});
});
function elementText(n) {
var hasNodes = function(n) {
var children = dom_adapter_1.DOM.childNodes(n);
return children && children.length > 0;
};
if (n instanceof Array) {
return n.map(elementText).join("");
}
if (dom_adapter_1.DOM.isCommentNode(n)) {
return '';
}
if (dom_adapter_1.DOM.isElementNode(n) && dom_adapter_1.DOM.tagName(n) == 'CONTENT') {
return elementText(Array.prototype.slice.apply(dom_adapter_1.DOM.getDistributedNodes(n)));
}
if (dom_adapter_1.DOM.hasShadowRoot(n)) {
return elementText(dom_adapter_1.DOM.childNodesAsList(dom_adapter_1.DOM.getShadowRoot(n)));
}
if (hasNodes(n)) {
return elementText(dom_adapter_1.DOM.childNodesAsList(n));
}
return dom_adapter_1.DOM.getText(n);
}
global.define = __define;
return module.exports;
});
System.register("angular2/src/compiler/xhr_mock", ["angular2/src/compiler/xhr", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/async"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var xhr_1 = require("angular2/src/compiler/xhr");
var collection_1 = require("angular2/src/facade/collection");
var lang_1 = require("angular2/src/facade/lang");
var exceptions_1 = require("angular2/src/facade/exceptions");
var async_1 = require("angular2/src/facade/async");
var MockXHR = (function(_super) {
__extends(MockXHR, _super);
function MockXHR() {
_super.apply(this, arguments);
this._expectations = [];
this._definitions = new collection_1.Map();
this._requests = [];
}
MockXHR.prototype.get = function(url) {
var request = new _PendingRequest(url);
this._requests.push(request);
return request.getPromise();
};
MockXHR.prototype.expect = function(url, response) {
var expectation = new _Expectation(url, response);
this._expectations.push(expectation);
};
MockXHR.prototype.when = function(url, response) {
this._definitions.set(url, response);
};
MockXHR.prototype.flush = function() {
if (this._requests.length === 0) {
throw new exceptions_1.BaseException('No pending requests to flush');
}
do {
this._processRequest(this._requests.shift());
} while (this._requests.length > 0);
this.verifyNoOutstandingExpectations();
};
MockXHR.prototype.verifyNoOutstandingExpectations = function() {
if (this._expectations.length === 0)
return ;
var urls = [];
for (var i = 0; i < this._expectations.length; i++) {
var expectation = this._expectations[i];
urls.push(expectation.url);
}
throw new exceptions_1.BaseException("Unsatisfied requests: " + urls.join(', '));
};
MockXHR.prototype._processRequest = function(request) {
var url = request.url;
if (this._expectations.length > 0) {
var expectation = this._expectations[0];
if (expectation.url == url) {
collection_1.ListWrapper.remove(this._expectations, expectation);
request.complete(expectation.response);
return ;
}
}
if (this._definitions.has(url)) {
var response = this._definitions.get(url);
request.complete(lang_1.normalizeBlank(response));
return ;
}
throw new exceptions_1.BaseException("Unexpected request " + url);
};
return MockXHR;
}(xhr_1.XHR));
exports.MockXHR = MockXHR;
var _PendingRequest = (function() {
function _PendingRequest(url) {
this.url = url;
this.completer = async_1.PromiseWrapper.completer();
}
_PendingRequest.prototype.complete = function(response) {
if (lang_1.isBlank(response)) {
this.completer.reject("Failed to load " + this.url, null);
} else {
this.completer.resolve(response);
}
};
_PendingRequest.prototype.getPromise = function() {
return this.completer.promise;
};
return _PendingRequest;
}());
var _Expectation = (function() {
function _Expectation(url, response) {
this.url = url;
this.response = response;
}
return _Expectation;
}());
global.define = __define;
return module.exports;
});
System.register("angular2/src/testing/test_injector", ["angular2/core", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/facade/lang"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var core_1 = require("angular2/core");
var exceptions_1 = require("angular2/src/facade/exceptions");
var collection_1 = require("angular2/src/facade/collection");
var lang_1 = require("angular2/src/facade/lang");
var TestInjector = (function() {
function TestInjector() {
this._instantiated = false;
this._injector = null;
this._providers = [];
this.platformProviders = [];
this.applicationProviders = [];
}
TestInjector.prototype.reset = function() {
this._injector = null;
this._providers = [];
this._instantiated = false;
};
TestInjector.prototype.addProviders = function(providers) {
if (this._instantiated) {
throw new exceptions_1.BaseException('Cannot add providers after test injector is instantiated');
}
this._providers = collection_1.ListWrapper.concat(this._providers, providers);
};
TestInjector.prototype.createInjector = function() {
var rootInjector = core_1.Injector.resolveAndCreate(this.platformProviders);
this._injector = rootInjector.resolveAndCreateChild(collection_1.ListWrapper.concat(this.applicationProviders, this._providers));
this._instantiated = true;
return this._injector;
};
TestInjector.prototype.execute = function(fn) {
var additionalProviders = fn.additionalProviders();
if (additionalProviders.length > 0) {
this.addProviders(additionalProviders);
}
if (!this._instantiated) {
this.createInjector();
}
return fn.execute(this._injector);
};
return TestInjector;
}());
exports.TestInjector = TestInjector;
var _testInjector = null;
function getTestInjector() {
if (_testInjector == null) {
_testInjector = new TestInjector();
}
return _testInjector;
}
exports.getTestInjector = getTestInjector;
function setBaseTestProviders(platformProviders, applicationProviders) {
var testInjector = getTestInjector();
if (testInjector.platformProviders.length > 0 || testInjector.applicationProviders.length > 0) {
throw new exceptions_1.BaseException('Cannot set base providers because it has already been called');
}
testInjector.platformProviders = platformProviders;
testInjector.applicationProviders = applicationProviders;
var injector = testInjector.createInjector();
var inits = injector.getOptional(core_1.PLATFORM_INITIALIZER);
if (lang_1.isPresent(inits)) {
inits.forEach(function(init) {
return init();
});
}
testInjector.reset();
}
exports.setBaseTestProviders = setBaseTestProviders;
function resetBaseTestProviders() {
var testInjector = getTestInjector();
testInjector.platformProviders = [];
testInjector.applicationProviders = [];
testInjector.reset();
}
exports.resetBaseTestProviders = resetBaseTestProviders;
function inject(tokens, fn) {
return new FunctionWithParamTokens(tokens, fn, false);
}
exports.inject = inject;
var InjectSetupWrapper = (function() {
function InjectSetupWrapper(_providers) {
this._providers = _providers;
}
InjectSetupWrapper.prototype.inject = function(tokens, fn) {
return new FunctionWithParamTokens(tokens, fn, false, this._providers);
};
InjectSetupWrapper.prototype.injectAsync = function(tokens, fn) {
return new FunctionWithParamTokens(tokens, fn, true, this._providers);
};
return InjectSetupWrapper;
}());
exports.InjectSetupWrapper = InjectSetupWrapper;
function withProviders(providers) {
return new InjectSetupWrapper(providers);
}
exports.withProviders = withProviders;
function injectAsync(tokens, fn) {
return new FunctionWithParamTokens(tokens, fn, true);
}
exports.injectAsync = injectAsync;
function emptyArray() {
return [];
}
var FunctionWithParamTokens = (function() {
function FunctionWithParamTokens(_tokens, _fn, isAsync, additionalProviders) {
if (additionalProviders === void 0) {
additionalProviders = emptyArray;
}
this._tokens = _tokens;
this._fn = _fn;
this.isAsync = isAsync;
this.additionalProviders = additionalProviders;
}
FunctionWithParamTokens.prototype.execute = function(injector) {
var params = this._tokens.map(function(t) {
return injector.get(t);
});
return lang_1.FunctionWrapper.apply(this._fn, params);
};
FunctionWithParamTokens.prototype.hasToken = function(token) {
return this._tokens.indexOf(token) > -1;
};
return FunctionWithParamTokens;
}());
exports.FunctionWithParamTokens = FunctionWithParamTokens;
global.define = __define;
return module.exports;
});
System.register("angular2/src/testing/testing", ["angular2/src/facade/lang", "angular2/src/testing/test_injector", "angular2/src/testing/test_injector", "angular2/src/testing/matchers"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
var lang_1 = require("angular2/src/facade/lang");
var test_injector_1 = require("angular2/src/testing/test_injector");
var test_injector_2 = require("angular2/src/testing/test_injector");
exports.inject = test_injector_2.inject;
exports.injectAsync = test_injector_2.injectAsync;
var matchers_1 = require("angular2/src/testing/matchers");
exports.expect = matchers_1.expect;
var _global = (typeof window === 'undefined' ? lang_1.global : window);
exports.afterEach = _global.afterEach;
exports.describe = _global.describe;
exports.ddescribe = _global.fdescribe;
exports.fdescribe = _global.fdescribe;
exports.xdescribe = _global.xdescribe;
var jsmBeforeEach = _global.beforeEach;
var jsmIt = _global.it;
var jsmIIt = _global.fit;
var jsmXIt = _global.xit;
var testInjector = test_injector_1.getTestInjector();
jsmBeforeEach(function() {
testInjector.reset();
});
function beforeEachProviders(fn) {
jsmBeforeEach(function() {
var providers = fn();
if (!providers)
return ;
try {
testInjector.addProviders(providers);
} catch (e) {
throw new Error('beforeEachProviders was called after the injector had ' + 'been used in a beforeEach or it block. This invalidates the ' + 'test injector');
}
});
}
exports.beforeEachProviders = beforeEachProviders;
function _isPromiseLike(input) {
return input && !!(input.then);
}
function _it(jsmFn, name, testFn, testTimeOut) {
var timeOut = testTimeOut;
if (testFn instanceof test_injector_1.FunctionWithParamTokens) {
var testFnT_1 = testFn;
jsmFn(name, function(done) {
var returnedTestValue;
try {
returnedTestValue = testInjector.execute(testFnT_1);
} catch (err) {
done.fail(err);
return ;
}
if (testFnT_1.isAsync) {
if (_isPromiseLike(returnedTestValue)) {
returnedTestValue.then(function() {
done();
}, function(err) {
done.fail(err);
});
} else {
done.fail('Error: injectAsync was expected to return a promise, but the ' + ' returned value was: ' + returnedTestValue);
}
} else {
if (!(returnedTestValue === undefined)) {
done.fail('Error: inject returned a value. Did you mean to use injectAsync? Returned ' + 'value was: ' + returnedTestValue);
}
done();
}
}, timeOut);
} else {
jsmFn(name, testFn, timeOut);
}
}
function beforeEach(fn) {
if (fn instanceof test_injector_1.FunctionWithParamTokens) {
var fnT_1 = fn;
jsmBeforeEach(function(done) {
var returnedTestValue;
try {
returnedTestValue = testInjector.execute(fnT_1);
} catch (err) {
done.fail(err);
return ;
}
if (fnT_1.isAsync) {
if (_isPromiseLike(returnedTestValue)) {
returnedTestValue.then(function() {
done();
}, function(err) {
done.fail(err);
});
} else {
done.fail('Error: injectAsync was expected to return a promise, but the ' + ' returned value was: ' + returnedTestValue);
}
} else {
if (!(returnedTestValue === undefined)) {
done.fail('Error: inject returned a value. Did you mean to use injectAsync? Returned ' + 'value was: ' + returnedTestValue);
}
done();
}
});
} else {
if (fn.length === 0) {
jsmBeforeEach(function() {
fn();
});
} else {
jsmBeforeEach(function(done) {
fn(done);
});
}
}
}
exports.beforeEach = beforeEach;
function it(name, fn, timeOut) {
if (timeOut === void 0) {
timeOut = null;
}
return _it(jsmIt, name, fn, timeOut);
}
exports.it = it;
function xit(name, fn, timeOut) {
if (timeOut === void 0) {
timeOut = null;
}
return _it(jsmXIt, name, fn, timeOut);
}
exports.xit = xit;
function iit(name, fn, timeOut) {
if (timeOut === void 0) {
timeOut = null;
}
return _it(jsmIIt, name, fn, timeOut);
}
exports.iit = iit;
function fit(name, fn, timeOut) {
if (timeOut === void 0) {
timeOut = null;
}
return _it(jsmIIt, name, fn, timeOut);
}
exports.fit = fit;
global.define = __define;
return module.exports;
});
System.register("angular2/testing", ["angular2/src/testing/testing", "angular2/src/testing/test_component_builder", "angular2/src/testing/test_injector", "angular2/src/testing/fake_async", "angular2/src/mock/view_resolver_mock", "angular2/src/compiler/xhr_mock", "angular2/src/mock/ng_zone_mock", "angular2/src/mock/mock_application_ref", "angular2/src/mock/directive_resolver_mock"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
"use strict";
function __export(m) {
for (var p in m)
if (!exports.hasOwnProperty(p))
exports[p] = m[p];
}
__export(require("angular2/src/testing/testing"));
var test_component_builder_1 = require("angular2/src/testing/test_component_builder");
exports.ComponentFixture = test_component_builder_1.ComponentFixture;
exports.TestComponentBuilder = test_component_builder_1.TestComponentBuilder;
__export(require("angular2/src/testing/test_injector"));
__export(require("angular2/src/testing/fake_async"));
var view_resolver_mock_1 = require("angular2/src/mock/view_resolver_mock");
exports.MockViewResolver = view_resolver_mock_1.MockViewResolver;
var xhr_mock_1 = require("angular2/src/compiler/xhr_mock");
exports.MockXHR = xhr_mock_1.MockXHR;
var ng_zone_mock_1 = require("angular2/src/mock/ng_zone_mock");
exports.MockNgZone = ng_zone_mock_1.MockNgZone;
var mock_application_ref_1 = require("angular2/src/mock/mock_application_ref");
exports.MockApplicationRef = mock_application_ref_1.MockApplicationRef;
var directive_resolver_mock_1 = require("angular2/src/mock/directive_resolver_mock");
exports.MockDirectiveResolver = directive_resolver_mock_1.MockDirectiveResolver;
global.define = __define;
return module.exports;
});
//# sourceMappingURL=testing.dev.js.map
|
mchiba52/mystocks-angularv2
|
node_modules/angular2/bundles/testing.dev.js
|
JavaScript
|
apache-2.0
| 88,227 |
'use strict';
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _warnOnce = require('./warn-once');
var _warnOnce2 = _interopRequireDefault(_warnOnce);
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Declaration = function (_Node) {
_inherits(Declaration, _Node);
function Declaration(defaults) {
_classCallCheck(this, Declaration);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'decl';
return _this;
}
/* istanbul ignore next */
_createClass(Declaration, [{
key: '_value',
get: function get() {
(0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value');
return this.raws.value;
}
/* istanbul ignore next */
,
set: function set(val) {
(0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value');
this.raws.value = val;
}
/* istanbul ignore next */
}, {
key: '_important',
get: function get() {
(0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important');
return this.raws.important;
}
/* istanbul ignore next */
,
set: function set(val) {
(0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important');
this.raws.important = val;
}
}]);
return Declaration;
}(_node2.default);
exports.default = Declaration;
module.exports = exports['default'];
|
jgcopple/GarySchwantz
|
wp-content/themes/square-child/foundation/node_modules/gulp-autoprefixer/node_modules/postcss/lib/declaration.js
|
JavaScript
|
gpl-2.0
| 3,125 |
/**
* Require unassigned functions to be named inline
*
* Types: `Boolean` or `Object`
*
* Values:
* - `true`
* - `Object`:
* - `allExcept`: array of quoted identifiers
*
* #### Example
*
* ```js
* "requireNamedUnassignedFunctions": { "allExcept": ["describe", "it"] }
* ```
*
* ##### Valid
*
* ```js
* [].forEach(function x() {});
* var y = function() {};
* function z() {}
* it(function () {});
* ```
*
* ##### Invalid
*
* ```js
* [].forEach(function () {});
* before(function () {});
* ```
*/
var assert = require('assert');
var pathval = require('pathval');
function getNodeName(node) {
if (node.type === 'Identifier') {
return node.name;
} else {
return node.value;
}
}
module.exports = function() {};
module.exports.prototype = {
configure: function(options) {
assert(
options === true ||
typeof options === 'object',
this.getOptionName() + ' option requires true value ' +
'or an object with String[] `allExcept` property'
);
// verify first item in `allExcept` property in object (if it's an object)
assert(
typeof options !== 'object' ||
Array.isArray(options.allExcept) &&
typeof options.allExcept[0] === 'string',
'Property `allExcept` in ' + this.getOptionName() + ' should be an array of strings'
);
if (options.allExcept) {
this._allExceptItems = options.allExcept.map(function(item) {
var parts = pathval.parse(item).map(function extractPart(part) {
return part.i !== undefined ? part.i : part.p;
});
return JSON.stringify(parts);
});
}
},
getOptionName: function() {
return 'requireNamedUnassignedFunctions';
},
check: function(file, errors) {
var _this = this;
file.iterateNodesByType('FunctionExpression', function(node) {
var parentElement = node.parentElement;
// If the function has been named via left hand assignment, skip it
// e.g. `var hello = function() {`, `foo.bar = function() {`
if (parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) {
return;
}
// If the function has been named, skip it
// e.g. `[].forEach(function hello() {`
if (node.id !== null) {
return;
}
// If we have exceptions and the function is being invoked, detect whether we excepted it
if (_this._allExceptItems && parentElement.type === 'CallExpression') {
// Determine the path that resolves to our call expression
// We must cover both direct calls (e.g. `it(function() {`) and
// member expressions (e.g. `foo.bar(function() {`)
var memberNode = parentElement.callee;
var canBeRepresented = true;
var fullpathParts = [];
while (memberNode) {
if (memberNode.type.match(/Identifier|Literal/)) {
fullpathParts.unshift(getNodeName(memberNode));
} else if (memberNode.type === 'MemberExpression') {
fullpathParts.unshift(getNodeName(memberNode.property));
} else {
canBeRepresented = false;
break;
}
memberNode = memberNode.object;
}
// If the path is not-dynamic (i.e. can be represented by static parts),
// then check it against our exceptions
if (canBeRepresented) {
var fullpath = JSON.stringify(fullpathParts);
for (var i = 0, l = _this._allExceptItems.length; i < l; i++) {
if (fullpath === _this._allExceptItems[i]) {
return;
}
}
}
}
// Complain that this function must be named
errors.add('Inline functions need to be named', node);
});
}
};
|
oavasquez/ingeneria_software
|
web-project/node_modules/jscs/lib/rules/require-named-unassigned-functions.js
|
JavaScript
|
mit
| 4,284 |
function X2JS(_1){
"use strict";
var _2="1.1.2";
_1=_1||{};
_3();
function _3(){
if(_1.escapeMode===undefined){
_1.escapeMode=true;
}
if(_1.attributePrefix===undefined){
_1.attributePrefix="_";
}
if(_1.arrayAccessForm===undefined){
_1.arrayAccessForm="none";
}
if(_1.emptyNodeForm===undefined){
_1.emptyNodeForm="text";
}
};
var _4={ELEMENT_NODE:1,TEXT_NODE:3,CDATA_SECTION_NODE:4,DOCUMENT_NODE:9};
function _5(_6){
var _7=_6.localName;
if(_7==null){
_7=_6.baseName;
}
if(_7==null||_7==""){
_7=_6.nodeName;
}
return _7;
};
function _8(_9){
return _9.prefix;
};
function _a(_b){
if(typeof (_b)=="string"){
return _b.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/");
}else{
return _b;
}
};
function _c(_d){
return _d.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"\"").replace(/'/g,"'").replace(///g,"/");
};
function _e(_f,_10){
switch(_1.arrayAccessForm){
case "property":
if(!(_f[_10] instanceof Array)){
_f[_10+"_asArray"]=[_f[_10]];
}else{
_f[_10+"_asArray"]=_f[_10];
}
break;
}
};
function _11(_12){
if(_12.nodeType==_4.DOCUMENT_NODE){
var _13=new Object;
var _14=_12.firstChild;
var _15=_5(_14);
_13[_15]=_11(_14);
return _13;
}else{
if(_12.nodeType==_4.ELEMENT_NODE){
var _13=new Object;
_13.__cnt=0;
var _16=_12.childNodes;
for(var _17=0;_17<_16.length;_17++){
var _14=_16.item(_17);
var _15=_5(_14);
_13.__cnt++;
if(_13[_15]==null){
_13[_15]=_11(_14);
_e(_13,_15);
}else{
if(_13[_15]!=null){
if(!(_13[_15] instanceof Array)){
_13[_15]=[_13[_15]];
_e(_13,_15);
}
}
var _18=0;
while(_13[_15][_18]!=null){
_18++;
}
(_13[_15])[_18]=_11(_14);
}
}
for(var _19=0;_19<_12.attributes.length;_19++){
var _1a=_12.attributes.item(_19);
_13.__cnt++;
_13[_1.attributePrefix+_1a.name]=_1a.value;
}
var _1b=_8(_12);
if(_1b!=null&&_1b!=""){
_13.__cnt++;
_13.__prefix=_1b;
}
if(_13["#text"]!=null){
_13.__text=_13["#text"];
if(_13.__text instanceof Array){
_13.__text=_13.__text.join("\n");
}
if(_1.escapeMode){
_13.__text=_c(_13.__text);
}
delete _13["#text"];
if(_1.arrayAccessForm=="property"){
delete _13["#text_asArray"];
}
}
if(_13["#cdata-section"]!=null){
_13.__cdata=_13["#cdata-section"];
delete _13["#cdata-section"];
if(_1.arrayAccessForm=="property"){
delete _13["#cdata-section_asArray"];
}
}
if(_13.__cnt==1&&_13.__text!=null){
_13=_13.__text;
}else{
if(_13.__cnt==0&&_1.emptyNodeForm=="text"){
_13="";
}
}
delete _13.__cnt;
if(_13.__text!=null||_13.__cdata!=null){
_13.toString=function(){
return (this.__text!=null?this.__text:"")+(this.__cdata!=null?this.__cdata:"");
};
}
return _13;
}else{
if(_12.nodeType==_4.TEXT_NODE||_12.nodeType==_4.CDATA_SECTION_NODE){
return _12.nodeValue;
}
}
}
};
function _1c(_1d,_1e,_1f,_20){
var _21="<"+((_1d!=null&&_1d.__prefix!=null)?(_1d.__prefix+":"):"")+_1e;
if(_1f!=null){
for(var _22=0;_22<_1f.length;_22++){
var _23=_1f[_22];
var _24=_1d[_23];
_21+=" "+_23.substr(_1.attributePrefix.length)+"='"+_24+"'";
}
}
if(!_20){
_21+=">";
}else{
_21+="/>";
}
return _21;
};
function _25(_26,_27){
return "</"+(_26.__prefix!=null?(_26.__prefix+":"):"")+_27+">";
};
function _28(str,_29){
return str.indexOf(_29,str.length-_29.length)!==-1;
};
function _2a(_2b,_2c){
if((_1.arrayAccessForm=="property"&&_28(_2c.toString(),("_asArray")))||_2c.toString().indexOf(_1.attributePrefix)==0||_2c.toString().indexOf("__")==0||(_2b[_2c] instanceof Function)){
return true;
}else{
return false;
}
};
function _2d(_2e){
var _2f=0;
if(_2e instanceof Object){
for(var it in _2e){
if(_2a(_2e,it)){
continue;
}
_2f++;
}
}
return _2f;
};
function _30(_31){
var _32=[];
if(_31 instanceof Object){
for(var ait in _31){
if(ait.toString().indexOf("__")==-1&&ait.toString().indexOf(_1.attributePrefix)==0){
_32.push(ait);
}
}
}
return _32;
};
function _33(_34){
var _35="";
if(_34.__cdata!=null){
_35+="<![CDATA["+_34.__cdata+"]]>";
}
if(_34.__text!=null){
if(_1.escapeMode){
_35+=_a(_34.__text);
}else{
_35+=_34.__text;
}
}
return _35;
};
function _36(_37){
var _38="";
if(_37 instanceof Object){
_38+=_33(_37);
}else{
if(_37!=null){
if(_1.escapeMode){
_38+=_a(_37);
}else{
_38+=_37;
}
}
}
return _38;
};
function _39(_3a,_3b,_3c){
var _3d="";
if(_3a.length==0){
_3d+=_1c(_3a,_3b,_3c,true);
}else{
for(var _3e=0;_3e<_3a.length;_3e++){
_3d+=_1c(_3a[_3e],_3b,_30(_3a[_3e]),false);
_3d+=_3f(_3a[_3e]);
_3d+=_25(_3a[_3e],_3b);
}
}
return _3d;
};
function _3f(_40){
var _41="";
var _42=_2d(_40);
if(_42>0){
for(var it in _40){
if(_2a(_40,it)){
continue;
}
var _43=_40[it];
var _44=_30(_43);
if(_43==null||_43==undefined){
_41+=_1c(_43,it,_44,true);
}else{
if(_43 instanceof Object){
if(_43 instanceof Array){
_41+=_39(_43,it,_44);
}else{
var _45=_2d(_43);
if(_45>0||_43.__text!=null||_43.__cdata!=null){
_41+=_1c(_43,it,_44,false);
_41+=_3f(_43);
_41+=_25(_43,it);
}else{
_41+=_1c(_43,it,_44,true);
}
}
}else{
_41+=_1c(_43,it,_44,false);
_41+=_36(_43);
_41+=_25(_43,it);
}
}
}
}
_41+=_36(_40);
return _41;
};
this.parseXmlString=function(_46){
if(_46===undefined){
return null;
}
var _47;
if(window.DOMParser){
var _48=new window.DOMParser();
_47=_48.parseFromString(_46,"text/xml");
}else{
if(_46.indexOf("<?")==0){
_46=_46.substr(_46.indexOf("?>")+2);
}
_47=new ActiveXObject("Microsoft.XMLDOM");
_47.async="false";
_47.loadXML(_46);
}
return _47;
};
this.asArray=function(_49){
if(_49 instanceof Array){
return _49;
}else{
return [_49];
}
};
this.xml2json=function(_4a){
return _11(_4a);
};
this.xml_str2json=function(_4b){
var _4c=this.parseXmlString(_4b);
return this.xml2json(_4c);
};
this.json2xml_str=function(_4d){
return _3f(_4d);
};
this.json2xml=function(_4e){
var _4f=this.json2xml_str(_4e);
return this.parseXmlString(_4f);
};
this.getVersion=function(){
return _2;
};
};
|
retrobot/zurbebay
|
zips/x2js-v1.1.2/xml2json.min.js
|
JavaScript
|
mit
| 5,729 |
'use strict';
var path = require('path');
exports.name = 'cssmin';
//
// Output a config for the furnished block
// The context variable is used both to take the files to be treated
// (inFiles) and to output the one(s) created (outFiles).
// It aslo conveys whether or not the current process is the last of the pipe
//
exports.createConfig = function(context, block) {
var cfg = {files: []};
// FIXME: check context has all the needed info
var outfile = path.join(context.outDir, block.dest);
// Depending whether or not we're the last of the step we're not going to output the same thing
var files = {};
files.dest = outfile;
files.src = [];
context.inFiles.forEach(function(f) { files.src.push(path.join(context.inDir, f));} );
cfg.files.push(files);
context.outFiles = [block.dest];
return cfg;
};
|
frangucc/gamify
|
www/sandbox/pals/node_modules/grunt-usemin/lib/config/cssmin.js
|
JavaScript
|
mit
| 828 |
/*
* jquery.inputmask.numeric.extensions.js
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2014 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 3.1.26
*/
(function (factory) {if (typeof define === 'function' && define.amd) {define(["jquery","./jquery.inputmask"], factory);} else {factory(jQuery);}}/*
Input Mask plugin extensions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 - 2014 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.0
Optional extensions on the jquery.inputmask base
*/
(function ($) {
//number aliases
$.extend($.inputmask.defaults.aliases, {
'numeric': {
mask: function (opts) {
if (opts.repeat !== 0 && isNaN(opts.integerDigits)) {
opts.integerDigits = opts.repeat;
}
opts.repeat = 0;
if (opts.groupSeparator == opts.radixPoint) { //treat equal separator and radixpoint
if (opts.radixPoint == ".")
opts.groupSeparator = ",";
else if (opts.radixPoint == ",")
opts.groupSeparator = ".";
else opts.groupSeparator = "";
}
if (opts.groupSeparator === " ") { //prevent conflict with default skipOptionalPartCharacter
opts.skipOptionalPartCharacter = undefined;
}
opts.autoGroup = opts.autoGroup && opts.groupSeparator != "";
if (opts.autoGroup && isFinite(opts.integerDigits)) {
var seps = Math.floor(opts.integerDigits / opts.groupSize);
var mod = opts.integerDigits % opts.groupSize;
opts.integerDigits += mod == 0 ? seps - 1 : seps;
}
opts.definitions[";"] = opts.definitions["~"]; //clone integer def for decimals
var mask = opts.prefix;
mask += "[+]";
mask += "~{1," + opts.integerDigits + "}";
if (opts.digits != undefined && (isNaN(opts.digits) || parseInt(opts.digits) > 0)) {
if (opts.digitsOptional)
mask += "[" + (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}]";
else mask += (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}";
}
mask += opts.suffix;
return mask;
},
placeholder: "",
greedy: false,
digits: "*", //number of fractionalDigits
digitsOptional: true,
groupSeparator: "",//",", // | "."
radixPoint: ".",
groupSize: 3,
autoGroup: false,
allowPlus: true,
allowMinus: true,
integerDigits: "+", //number of integerDigits
prefix: "",
suffix: "",
rightAlign: true,
decimalProtect: true, //do not allow assumption of decimals input without entering the radixpoint
postFormat: function (buffer, pos, reformatOnly, opts) { //this needs to be removed // this is crap
var needsRefresh = false, charAtPos = buffer[pos];
if (opts.groupSeparator == "" ||
($.inArray(opts.radixPoint, buffer) != -1 && pos >= $.inArray(opts.radixPoint, buffer)) ||
new RegExp('[-\+]').test(charAtPos)
) return { pos: pos };
var cbuf = buffer.slice();
if (charAtPos == opts.groupSeparator) {
cbuf.splice(pos--, 1);
charAtPos = cbuf[pos];
}
if (reformatOnly) cbuf[pos] = "?"; else cbuf.splice(pos, 0, "?"); //set position indicator
var bufVal = cbuf.join('');
if (opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) {
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
needsRefresh = bufVal.indexOf(opts.groupSeparator) == 0;
bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), '');
var radixSplit = bufVal.split(opts.radixPoint);
bufVal = radixSplit[0];
if (bufVal != (opts.prefix + "?0") && bufVal.length >= (opts.groupSize + opts.prefix.length)) {
needsRefresh = true;
var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})');
while (reg.test(bufVal)) {
bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2');
bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator);
}
}
if (radixSplit.length > 1)
bufVal += opts.radixPoint + radixSplit[1];
}
buffer.length = bufVal.length; //align the length
for (var i = 0, l = bufVal.length; i < l; i++) {
buffer[i] = bufVal.charAt(i);
}
var newPos = $.inArray("?", buffer);
if (reformatOnly) buffer[newPos] = charAtPos; else buffer.splice(newPos, 1);
return { pos: newPos, "refreshFromBuffer": needsRefresh };
},
onKeyDown: function (e, buffer, caretPos, opts) {
if (e.keyCode == $.inputmask.keyCode.TAB && opts.placeholder.charAt(0) != "0") {
var radixPosition = $.inArray(opts.radixPoint, buffer);
if (radixPosition != -1 && isFinite(opts.digits)) {
for (var i = 1; i <= opts.digits; i++) {
if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == opts.placeholder.charAt(0)) buffer[radixPosition + i] = "0";
}
return { "refreshFromBuffer": { start: ++radixPosition, end: radixPosition + opts.digits } };
}
} else if (opts.autoGroup && (e.keyCode == $.inputmask.keyCode.DELETE || e.keyCode == $.inputmask.keyCode.BACKSPACE)) {
var rslt = opts.postFormat(buffer, caretPos - 1, true, opts);
rslt.caret = rslt.pos + 1;
return rslt;
}
},
onKeyPress: function (e, buffer, caretPos, opts) {
if (opts.autoGroup /*&& String.fromCharCode(k) == opts.radixPoint*/) {
var rslt = opts.postFormat(buffer, caretPos - 1, true, opts);
rslt.caret = rslt.pos + 1;
return rslt;
}
},
regex: {
integerPart: function (opts) { return new RegExp('[-\+]?\\d+'); }
},
negationhandler: function (chrs, buffer, pos, strict, opts) {
if (!strict && opts.allowMinus && chrs === "-") {
var matchRslt = buffer.join('').match(opts.regex.integerPart(opts));
if (matchRslt.length > 0) {
if (buffer[matchRslt.index] == "+") {
return { "pos": matchRslt.index, "c": "-", "remove": matchRslt.index, "caret": pos };
} else if (buffer[matchRslt.index] == "-") {
return { "remove": matchRslt.index, "caret": pos - 1 };
} else {
return { "pos": matchRslt.index, "c": "-", "caret": pos + 1 };
}
}
}
return false;
},
radixhandler: function (chrs, maskset, pos, strict, opts) {
if (!strict && chrs === opts.radixPoint) {
var radixPos = $.inArray(opts.radixPoint, maskset.buffer), integerValue = maskset.buffer.join('').match(opts.regex.integerPart(opts));
if (radixPos != -1) {
if (maskset["validPositions"][radixPos - 1])
return { "caret": radixPos + 1 };
else return { "pos": integerValue.index, c: integerValue[0], "caret": radixPos + 1 };
}
}
return false;
},
leadingZeroHandler: function (chrs, maskset, pos, strict, opts) {
var matchRslt = maskset.buffer.join('').match(opts.regex.integerPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
if (matchRslt && !strict && (radixPosition == -1 || matchRslt.index < radixPosition)) {
if (matchRslt["0"].indexOf("0") == 0 && pos >= opts.prefix.length) {
if (radixPosition == -1 || (pos <= radixPosition && maskset["validPositions"][radixPosition] == undefined)) {
maskset.buffer.splice(matchRslt.index, 1);
pos = pos > matchRslt.index ? pos - 1 : matchRslt.index;
return { "pos": pos, "remove": matchRslt.index };
} else if (pos > matchRslt.index && pos <= radixPosition) {
maskset.buffer.splice(matchRslt.index, 1);
pos = pos > matchRslt.index ? pos - 1 : matchRslt.index;
return { "pos": pos, "remove": matchRslt.index };
}
} else if (chrs == "0" && pos <= matchRslt.index) {
return false;
}
}
return true;
},
definitions: {
'~': {
validator: function (chrs, maskset, pos, strict, opts) {
var isValid = opts.negationhandler(chrs, maskset.buffer, pos, strict, opts);
if (!isValid) {
isValid = opts.radixhandler(chrs, maskset, pos, strict, opts);
if (!isValid) {
isValid = strict ? new RegExp("[0-9" + $.inputmask.escapeRegex.call(this, opts.groupSeparator) + "]").test(chrs) : new RegExp("[0-9]").test(chrs);
if (isValid === true) {
isValid = opts.leadingZeroHandler(chrs, maskset, pos, strict, opts);
if (isValid === true) {
//handle overwrite when fixed precision
var radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
if (opts.digitsOptional === false && pos > radixPosition && !strict) {
return { "pos": pos, "remove": pos };
} else return { pos: pos };
}
}
}
}
return isValid;
},
cardinality: 1,
prevalidator: null
},
'+': {
validator: function (chrs, maskset, pos, strict, opts) {
var signed = "[";
if (opts.allowMinus === true) signed += "-";
if (opts.allowPlus === true) signed += "\+";
signed += "]";
return new RegExp(signed).test(chrs);
},
cardinality: 1,
prevalidator: null,
placeholder: ''
},
':': {
validator: function (chrs, maskset, pos, strict, opts) {
var isValid = opts.negationhandler(chrs, maskset.buffer, pos, strict, opts);
if (!isValid) {
var radix = "[" + $.inputmask.escapeRegex.call(this, opts.radixPoint) + "]";
isValid = new RegExp(radix).test(chrs);
if (isValid && maskset["validPositions"][pos] && maskset["validPositions"][pos]["match"].placeholder == opts.radixPoint) {
isValid = { "pos": pos, "remove": pos };
}
}
return isValid;
},
cardinality: 1,
prevalidator: null,
placeholder: function (opts) { return opts.radixPoint; }
}
},
insertMode: true,
autoUnmask: false,
onUnMask: function (maskedValue, unmaskedValue, opts) {
var processValue = maskedValue.replace(opts.prefix, "");
processValue = processValue.replace(opts.suffix, "");
processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
//processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
return processValue;
},
isComplete: function (buffer, opts) {
var maskedValue = buffer.join(''), bufClone = buffer.slice();
//verify separator positions
opts.postFormat(bufClone, 0, true, opts);
if (bufClone.join('') != maskedValue) return false;
var processValue = maskedValue.replace(opts.prefix, "");
processValue = processValue.replace(opts.suffix, "");
processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), ".");
return isFinite(processValue);
},
onBeforeMask: function (initialValue, opts) {
if (isFinite(initialValue)) {
return initialValue.toString().replace(".", opts.radixPoint);
} else {
var kommaMatches = initialValue.match(/,/g);
var dotMatches = initialValue.match(/\./g);
if (dotMatches && kommaMatches) {
if (dotMatches.length > kommaMatches.length) {
initialValue = initialValue.replace(/\./g, "");
initialValue = initialValue.replace(",", opts.radixPoint);
} else if (kommaMatches.length > dotMatches.length) {
initialValue = initialValue.replace(/,/g, "");
initialValue = initialValue.replace(".", opts.radixPoint);
}
} else {
initialValue = initialValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), "");
}
return initialValue;
}
}
},
'currency': {
prefix: "$ ",
groupSeparator: ",",
radixPoint: ".",
alias: "numeric",
placeholder: "0",
autoGroup: true,
digits: 2,
digitsOptional: false,
clearMaskOnLostFocus: false,
decimalProtect: true,
},
'decimal': {
alias: "numeric"
},
'integer': {
alias: "numeric",
digits: "0"
}
});
return $.fn.inputmask;
}));
|
froala/cdnjs
|
ajax/libs/jquery.inputmask/3.1.26/inputmask/jquery.inputmask.numeric.extensions.js
|
JavaScript
|
mit
| 16,256 |
import "../arrays/merge";
import "../core/rebind";
import "layout";
d3.layout.hierarchy = function() {
var sort = d3_layout_hierarchySort,
children = d3_layout_hierarchyChildren,
value = d3_layout_hierarchyValue;
// Recursively compute the node depth and value.
// Also converts to a standard hierarchy structure.
function recurse(node, depth, nodes) {
var childs = children.call(hierarchy, node, depth);
node.depth = depth;
nodes.push(node);
if (childs && (n = childs.length)) {
var i = -1,
n,
c = node.children = [],
v = 0,
j = depth + 1,
d;
while (++i < n) {
d = recurse(childs[i], j, nodes);
d.parent = node;
c.push(d);
v += d.value;
}
if (sort) c.sort(sort);
if (value) node.value = v;
} else if (value) {
node.value = +value.call(hierarchy, node, depth) || 0;
}
return node;
}
// Recursively re-evaluates the node value.
function revalue(node, depth) {
var children = node.children,
v = 0;
if (children && (n = children.length)) {
var i = -1,
n,
j = depth + 1;
while (++i < n) v += revalue(children[i], j);
} else if (value) {
v = +value.call(hierarchy, node, depth) || 0;
}
if (value) node.value = v;
return v;
}
function hierarchy(d) {
var nodes = [];
recurse(d, 0, nodes);
return nodes;
}
hierarchy.sort = function(x) {
if (!arguments.length) return sort;
sort = x;
return hierarchy;
};
hierarchy.children = function(x) {
if (!arguments.length) return children;
children = x;
return hierarchy;
};
hierarchy.value = function(x) {
if (!arguments.length) return value;
value = x;
return hierarchy;
};
// Re-evaluates the `value` property for the specified hierarchy.
hierarchy.revalue = function(root) {
revalue(root, 0);
return root;
};
return hierarchy;
};
// A method assignment helper for hierarchy subclasses.
function d3_layout_hierarchyRebind(object, hierarchy) {
d3.rebind(object, hierarchy, "sort", "children", "value");
// Add an alias for nodes and links, for convenience.
object.nodes = object;
object.links = d3_layout_hierarchyLinks;
return object;
}
function d3_layout_hierarchyChildren(d) {
return d.children;
}
function d3_layout_hierarchyValue(d) {
return d.value;
}
function d3_layout_hierarchySort(a, b) {
return b.value - a.value;
}
// Returns an array source+target objects for the specified nodes.
function d3_layout_hierarchyLinks(nodes) {
return d3.merge(nodes.map(function(parent) {
return (parent.children || []).map(function(child) {
return {source: parent, target: child};
});
}));
}
|
spindance/serviced-precomp
|
web/ui/static/thirdparty/d3-3.3.6/src/layout/hierarchy.js
|
JavaScript
|
apache-2.0
| 2,793 |
/*! (C) WebReflection Mit Style License */
(function(e,t,n){if(n in e)return;var r=0,i=e.clearTimeout,s=e.setTimeout,o=Element.prototype,u=t.getOwnPropertyDescriptor,a=t.defineProperty,f=function(){document.dispatchEvent(new CustomEvent("readystatechange"))},l=function(e,t){i(r),r=s(f,10)},c=function(e){var t=u(o,e),n={configurable:t.configurable,enumerable:t.enumerable,get:function(){return t.get.call(this)},set:function(r){delete o[e],this[e]=r,a(o,e,n),l(this)}};a(o,e,n)},h=function(e){var t=u(o,e),n=t.value;t.value=function(){var e=n.apply(this,arguments);return l(this),e},a(o,e,t)};c("innerHTML"),c("innerText"),c("outerHTML"),c("outerText"),c("textContent"),h("appendChild"),h("applyElement"),h("insertAdjacentElement"),h("insertAdjacentHTML"),h("insertAdjacentText"),h("insertBefore"),h("insertData"),h("replaceAdjacentText"),h("replaceChild"),h("removeChild"),e[n]=Element})(window,Object,"HTMLElement");
|
tmthrgd/pagespeed-libraries-cdnjs
|
packages/document-register-element/0.2.2/dre-ie8-upfront-fix.js
|
JavaScript
|
mit
| 919 |
/*
YUI 3.4.1 (build 4118)
Copyright 2011 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('oop', function(Y) {
/**
Adds object inheritance and manipulation utilities to the YUI instance. This
module is required by most YUI components.
@module oop
**/
var L = Y.Lang,
A = Y.Array,
OP = Object.prototype,
CLONE_MARKER = '_~yuim~_',
hasOwn = OP.hasOwnProperty,
toString = OP.toString;
function dispatch(o, f, c, proto, action) {
if (o && o[action] && o !== Y) {
return o[action].call(o, f, c);
} else {
switch (A.test(o)) {
case 1:
return A[action](o, f, c);
case 2:
return A[action](Y.Array(o, 0, true), f, c);
default:
return Y.Object[action](o, f, c, proto);
}
}
}
/**
Augments the _receiver_ with prototype properties from the _supplier_. The
receiver may be a constructor function or an object. The supplier must be a
constructor function.
If the _receiver_ is an object, then the _supplier_ constructor will be called
immediately after _receiver_ is augmented, with _receiver_ as the `this` object.
If the _receiver_ is a constructor function, then all prototype methods of
_supplier_ that are copied to _receiver_ will be sequestered, and the
_supplier_ constructor will not be called immediately. The first time any
sequestered method is called on the _receiver_'s prototype, all sequestered
methods will be immediately copied to the _receiver_'s prototype, the
_supplier_'s constructor will be executed, and finally the newly unsequestered
method that was called will be executed.
This sequestering logic sounds like a bunch of complicated voodoo, but it makes
it cheap to perform frequent augmentation by ensuring that suppliers'
constructors are only called if a supplied method is actually used. If none of
the supplied methods is ever used, then there's no need to take the performance
hit of calling the _supplier_'s constructor.
@method augment
@param {Function|Object} receiver Object or function to be augmented.
@param {Function} supplier Function that supplies the prototype properties with
which to augment the _receiver_.
@param {Boolean} [overwrite=false] If `true`, properties already on the receiver
will be overwritten if found on the supplier's prototype.
@param {String[]} [whitelist] An array of property names. If specified,
only the whitelisted prototype properties will be applied to the receiver, and
all others will be ignored.
@param {Array|any} [args] Argument or array of arguments to pass to the
supplier's constructor when initializing.
@return {Function} Augmented object.
@for YUI
**/
Y.augment = function (receiver, supplier, overwrite, whitelist, args) {
var rProto = receiver.prototype,
sequester = rProto && supplier,
sProto = supplier.prototype,
to = rProto || receiver,
copy,
newPrototype,
replacements,
sequestered,
unsequester;
args = args ? Y.Array(args) : [];
if (sequester) {
newPrototype = {};
replacements = {};
sequestered = {};
copy = function (value, key) {
if (overwrite || !(key in rProto)) {
if (toString.call(value) === '[object Function]') {
sequestered[key] = value;
newPrototype[key] = replacements[key] = function () {
return unsequester(this, value, arguments);
};
} else {
newPrototype[key] = value;
}
}
};
unsequester = function (instance, fn, fnArgs) {
// Unsequester all sequestered functions.
for (var key in sequestered) {
if (hasOwn.call(sequestered, key)
&& instance[key] === replacements[key]) {
instance[key] = sequestered[key];
}
}
// Execute the supplier constructor.
supplier.apply(instance, args);
// Finally, execute the original sequestered function.
return fn.apply(instance, fnArgs);
};
if (whitelist) {
Y.Array.each(whitelist, function (name) {
if (name in sProto) {
copy(sProto[name], name);
}
});
} else {
Y.Object.each(sProto, copy, null, true);
}
}
Y.mix(to, newPrototype || sProto, overwrite, whitelist);
if (!sequester) {
supplier.apply(to, args);
}
return receiver;
};
/**
* Applies object properties from the supplier to the receiver. If
* the target has the property, and the property is an object, the target
* object will be augmented with the supplier's value. If the property
* is an array, the suppliers value will be appended to the target.
* @method aggregate
* @param {function} r the object to receive the augmentation.
* @param {function} s the object that supplies the properties to augment.
* @param {boolean} ov if true, properties already on the receiver
* will be overwritten if found on the supplier.
* @param {string[]} wl a whitelist. If supplied, only properties in
* this list will be applied to the receiver.
* @return {object} the extended object.
*/
Y.aggregate = function(r, s, ov, wl) {
return Y.mix(r, s, ov, wl, 0, true);
};
/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
* Static members will not be inherited.
*
* @method extend
* @param {function} r the object to modify.
* @param {function} s the object to inherit.
* @param {object} px prototype properties to add/override.
* @param {object} sx static properties to add/override.
* @return {object} the extended object.
*/
Y.extend = function(r, s, px, sx) {
if (!s || !r) {
Y.error('extend failed, verify dependencies');
}
var sp = s.prototype, rp = Y.Object(sp);
r.prototype = rp;
rp.constructor = r;
r.superclass = sp;
// assign constructor property
if (s != Object && sp.constructor == OP.constructor) {
sp.constructor = s;
}
// add prototype overrides
if (px) {
Y.mix(rp, px, true);
}
// add object overrides
if (sx) {
Y.mix(r, sx, true);
}
return r;
};
/**
* Executes the supplied function for each item in
* a collection. Supports arrays, objects, and
* NodeLists
* @method each
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {YUI} the YUI instance.
*/
Y.each = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'each');
};
/**
* Executes the supplied function for each item in
* a collection. The operation stops if the function
* returns true. Supports arrays, objects, and
* NodeLists.
* @method some
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {boolean} true if the function ever returns true,
* false otherwise.
*/
Y.some = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'some');
};
/**
* Deep object/array copy. Function clones are actually
* wrappers around the original function.
* Array-like objects are treated as arrays.
* Primitives are returned untouched. Optionally, a
* function can be provided to handle other data types,
* filter keys, validate values, etc.
*
* @method clone
* @param {object} o what to clone.
* @param {boolean} safe if true, objects will not have prototype
* items from the source. If false, they will. In this case, the
* original is initially protected, but the clone is not completely
* immune from changes to the source object prototype. Also, cloned
* prototype items that are deleted from the clone will result
* in the value of the source prototype being exposed. If operating
* on a non-safe clone, items should be nulled out rather than deleted.
* @param {function} f optional function to apply to each item in a
* collection; it will be executed prior to applying the value to
* the new object. Return false to prevent the copy.
* @param {object} c optional execution context for f.
* @param {object} owner Owner object passed when clone is iterating
* an object. Used to set up context for cloned functions.
* @param {object} cloned hash of previously cloned objects to avoid
* multiple clones.
* @return {Array|Object} the cloned object.
*/
Y.clone = function(o, safe, f, c, owner, cloned) {
if (!L.isObject(o)) {
return o;
}
// @todo cloning YUI instances doesn't currently work
if (Y.instanceOf(o, YUI)) {
return o;
}
var o2, marked = cloned || {}, stamp,
yeach = Y.each;
switch (L.type(o)) {
case 'date':
return new Date(o);
case 'regexp':
// if we do this we need to set the flags too
// return new RegExp(o.source);
return o;
case 'function':
// o2 = Y.bind(o, owner);
// break;
return o;
case 'array':
o2 = [];
break;
default:
// #2528250 only one clone of a given object should be created.
if (o[CLONE_MARKER]) {
return marked[o[CLONE_MARKER]];
}
stamp = Y.guid();
o2 = (safe) ? {} : Y.Object(o);
o[CLONE_MARKER] = stamp;
marked[stamp] = o;
}
// #2528250 don't try to clone element properties
if (!o.addEventListener && !o.attachEvent) {
yeach(o, function(v, k) {
if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) {
if (k !== CLONE_MARKER) {
if (k == 'prototype') {
// skip the prototype
// } else if (o[k] === o) {
// this[k] = this;
} else {
this[k] =
Y.clone(v, safe, f, c, owner || o, marked);
}
}
}
}, o2);
}
if (!cloned) {
Y.Object.each(marked, function(v, k) {
if (v[CLONE_MARKER]) {
try {
delete v[CLONE_MARKER];
} catch (e) {
v[CLONE_MARKER] = null;
}
}
}, this);
marked = null;
}
return o2;
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the beginning of the arguments collection the
* supplied to the function.
*
* @method bind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to include before the arguments the
* function is executed with.
* @return {function} the wrapped function.
*/
Y.bind = function(f, c) {
var xargs = arguments.length > 2 ?
Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
xargs.concat(Y.Array(arguments, 0, true)) : arguments;
return fn.apply(c || fn, args);
};
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the end of the arguments the function
* is executed with.
*
* @method rbind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to append to the end of
* arguments collection supplied to the function.
* @return {function} the wrapped function.
*/
Y.rbind = function(f, c) {
var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
Y.Array(arguments, 0, true).concat(xargs) : arguments;
return fn.apply(c || fn, args);
};
};
}, '3.4.1' ,{requires:['yui-base']});
|
zuverza/se
|
sites/all/libraries/yui/build/oop/oop.js
|
JavaScript
|
gpl-2.0
| 12,939 |
tinymce.addI18n('fi',{
"Cut": "Leikkaa",
"Header 2": "Otsikko 2",
"Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Selaimesi ei tue leikekirjan suoraa k\u00e4ytt\u00e4mist\u00e4. Ole hyv\u00e4 ja k\u00e4yt\u00e4 n\u00e4pp\u00e4imist\u00f6n Ctrl+X ja Ctrl+V n\u00e4pp\u00e4inyhdistelmi\u00e4.",
"Div": "Div",
"Paste": "Liit\u00e4",
"Close": "Sulje",
"Font Family": "Fontti",
"Pre": "Esimuotoiltu",
"Align right": "Tasaa oikealle",
"New document": "Uusi dokumentti",
"Blockquote": "Lainauslohko",
"Numbered list": "J\u00e4rjestetty lista",
"Increase indent": "Loitonna",
"Formats": "Muotoilut",
"Headers": "Otsikot",
"Select all": "Valitse kaikki",
"Header 3": "Otsikko 3",
"Blocks": "Lohkot",
"Undo": "Peru",
"Strikethrough": "Yliviivaus",
"Bullet list": "J\u00e4rjest\u00e4m\u00e4t\u00f6n lista",
"Header 1": "Otsikko 1",
"Superscript": "Yl\u00e4indeksi",
"Clear formatting": "Poista muotoilu",
"Font Sizes": "Fonttikoko",
"Subscript": "Alaindeksi",
"Header 6": "Otsikko 6",
"Redo": "Tee uudelleen",
"Paragraph": "Kappale",
"Ok": "Ok",
"Bold": "Lihavointi",
"Code": "Koodi",
"Italic": "Kursivointi",
"Align center": "Keskit\u00e4",
"Header 5": "Otsikko 5",
"Decrease indent": "Sisenn\u00e4",
"Header 4": "Otsikko 4",
"Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "Liitt\u00e4minen on nyt pelk\u00e4n tekstin -tilassa. Sis\u00e4ll\u00f6t liitet\u00e4\u00e4n nyt pelkk\u00e4n\u00e4 tekstin\u00e4, kunnes otat vaihtoehdon pois k\u00e4yt\u00f6st\u00e4.",
"Underline": "Alleviivaus",
"Cancel": "Peruuta",
"Justify": "Tasaa",
"Inline": "Samalla rivill\u00e4",
"Copy": "Kopioi",
"Align left": "Tasaa vasemmalle",
"Visual aids": "Visuaaliset neuvot",
"Lower Greek": "pienet kirjaimet: \u03b1, \u03b2, \u03b3",
"Square": "Neli\u00f6",
"Default": "Oletus",
"Lower Alpha": "pienet kirjaimet: a, b, c",
"Circle": "Pallo",
"Disc": "Ympyr\u00e4",
"Upper Alpha": "isot kirjaimet: A, B, C",
"Upper Roman": "isot kirjaimet: I, II, III",
"Lower Roman": "pienet kirjaimet: i, ii, iii",
"Name": "Nimi",
"Anchor": "Ankkuri",
"You have unsaved changes are you sure you want to navigate away?": "Sinulla on tallentamattomia muutoksia, haluatko varmasti siirty\u00e4 toiselle sivulle?",
"Restore last draft": "Palauta aiempi luonnos",
"Special character": "Erikoismerkki",
"Source code": "L\u00e4hdekoodi",
"Right to left": "Oikealta vasemmalle",
"Left to right": "Vasemmalta oikealle",
"Emoticons": "Hymi\u00f6t",
"Robots": "Robotit",
"Document properties": "Dokumentin ominaisuudet",
"Title": "Otsikko",
"Keywords": "Avainsanat",
"Encoding": "Merkist\u00f6",
"Description": "Kuvaus",
"Author": "Tekij\u00e4",
"Fullscreen": "Koko ruutu",
"Horizontal line": "Vaakasuora viiva",
"Horizontal space": "Horisontaalinen tila",
"Insert\/edit image": "Lis\u00e4\u00e4\/muokkaa kuva",
"General": "Yleiset",
"Advanced": "Lis\u00e4asetukset",
"Source": "L\u00e4hde",
"Border": "Reunus",
"Constrain proportions": "S\u00e4ilyt\u00e4 mittasuhteet",
"Vertical space": "Vertikaalinen tila",
"Image description": "Kuvaus",
"Style": "Tyyli",
"Dimensions": "Mittasuhteet",
"Insert image": "Lis\u00e4\u00e4 kuva",
"Insert date\/time": "Lis\u00e4\u00e4 p\u00e4iv\u00e4m\u00e4\u00e4r\u00e4 tai aika",
"Remove link": "Poista linkki",
"Url": "Osoite",
"Text to display": "N\u00e4ytett\u00e4v\u00e4 teksti",
"Anchors": "Ankkurit",
"Insert link": "Lis\u00e4\u00e4 linkki",
"New window": "Uusi ikkuna",
"None": "Ei mit\u00e4\u00e4n",
"Target": "Kohde",
"Insert\/edit link": "Lis\u00e4\u00e4 tai muokkaa linkki",
"Insert\/edit video": "Lis\u00e4\u00e4 tai muokkaa video",
"Poster": "L\u00e4hett\u00e4j\u00e4",
"Alternative source": "Vaihtoehtoinen l\u00e4hde",
"Paste your embed code below:": "Liit\u00e4 upotuskoodisi alapuolelle:",
"Insert video": "Lis\u00e4\u00e4 video",
"Embed": "Upota",
"Nonbreaking space": "Tyhj\u00e4 merkki (nbsp)",
"Page break": "Sivunvaihto",
"Paste as text": "Liit\u00e4 tekstin\u00e4",
"Preview": "Esikatselu",
"Print": "Tulosta",
"Save": "Tallenna",
"Could not find the specified string.": "Haettua merkkijonoa ei l\u00f6ytynyt.",
"Replace": "Korvaa",
"Next": "Seur.",
"Whole words": "Koko sanat",
"Find and replace": "Etsi ja korvaa",
"Replace with": "Korvaa",
"Find": "Etsi",
"Replace all": "Korvaa kaikki",
"Match case": "Erota isot ja pienet kirjaimet",
"Prev": "Edel.",
"Spellcheck": "Oikolue",
"Finish": "Lopeta",
"Ignore all": "\u00c4l\u00e4 huomioi mit\u00e4\u00e4n",
"Ignore": "\u00c4l\u00e4 huomioi",
"Insert row before": "Lis\u00e4\u00e4 rivi ennen",
"Rows": "Rivit",
"Height": "Korkeus",
"Paste row after": "Liit\u00e4 rivi j\u00e4lkeen",
"Alignment": "Tasaus",
"Column group": "Sarakeryhm\u00e4",
"Row": "Rivi",
"Insert column before": "Lis\u00e4\u00e4 rivi ennen",
"Split cell": "Jaa solu",
"Cell padding": "Solun tyhj\u00e4 tila",
"Cell spacing": "Solun v\u00e4li",
"Row type": "Rivityyppi",
"Insert table": "Lis\u00e4\u00e4 taulukko",
"Body": "Runko",
"Caption": "Seloste",
"Footer": "Alaosa",
"Delete row": "Poista rivi",
"Paste row before": "Liit\u00e4 rivi ennen",
"Scope": "Laajuus",
"Delete table": "Poista taulukko",
"Header cell": "Otsikkosolu",
"Column": "Sarake",
"Cell": "Solu",
"Header": "Otsikko",
"Cell type": "Solun tyyppi",
"Copy row": "Kopioi rivi",
"Row properties": "Rivin ominaisuudet",
"Table properties": "Taulukon ominaisuudet",
"Row group": "Riviryhm\u00e4",
"Right": "Oikea",
"Insert column after": "Lis\u00e4\u00e4 rivi j\u00e4lkeen",
"Cols": "Sarakkeet",
"Insert row after": "Lis\u00e4\u00e4 rivi j\u00e4lkeen",
"Width": "Leveys",
"Cell properties": "Solun ominaisuudet",
"Left": "Vasen",
"Cut row": "Leikkaa rivi",
"Delete column": "Poista sarake",
"Center": "Keskell\u00e4",
"Merge cells": "Yhdist\u00e4 solut",
"Insert template": "Lis\u00e4\u00e4 pohja",
"Templates": "Pohjat",
"Background color": "Taustan v\u00e4ri",
"Text color": "Tekstin v\u00e4ri",
"Show blocks": "N\u00e4yt\u00e4 lohkot",
"Show invisible characters": "N\u00e4yt\u00e4 n\u00e4kym\u00e4tt\u00f6m\u00e4t merkit",
"Words: {0}": "Sanat: {0}",
"Insert": "Lis\u00e4\u00e4",
"File": "Tiedosto",
"Edit": "Muokkaa",
"Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "Rikastetun tekstin alue. Paina ALT-F9 valikkoon. Paina ALT-F10 ty\u00f6kaluriviin. Paina ALT-0 ohjeeseen.",
"Tools": "Ty\u00f6kalut",
"View": "N\u00e4yt\u00e4",
"Table": "Taulukko",
"Format": "Muotoilu"
});
|
criquier/OpenEcoles
|
web/bundles/stfalcontinymce/vendor/tinymce/langs/fi.js
|
JavaScript
|
mit
| 6,439 |
/*!
* FileInput Czech Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['cz'] = {
fileSingle: 'soubor',
filePlural: 'soubory',
browseLabel: 'Vybrat …',
removeLabel: 'Odstranit',
removeTitle: 'Vyฤistit vybranรฉ soubory',
cancelLabel: 'Storno',
cancelTitle: 'Pลeruลกit nahrรกvรกnรญ',
uploadLabel: 'Nahrรกt',
uploadTitle: 'Nahrรกt vybranรฉ soubory',
msgNo: 'Ne',
msgCancelled: 'Zruลกeno',
msgZoomTitle: 'zobrazit podrobnosti',
msgZoomModalHeading: 'Detailnรญ nรกhled',
msgSizeTooLarge: 'Soubor "{name}" (<b>{size} KB</b>): pลekroฤenรญ - maximรกlnรญ povolenรก velikost <b>{maxSize} KB</b>.',
msgFilesTooLess: 'Musรญte vybrat nejmรฉnฤ <b>{n}</b> {files} pro nahrรกnรญ.',
msgFilesTooMany: 'Poฤet vybranรฝch souborลฏ pro nahrรกnรญ <b>({n})</b>: pลekroฤenรญ - maximรกlnรญ povolenรฝ limit <b>{m}</b>.',
msgFileNotFound: 'Soubor "{name}" nebyl nalezen!',
msgFileSecured: 'Zabezpeฤenรญ souboru znemoลพnilo ฤรญst soubor "{name}".',
msgFileNotReadable: 'Soubor "{name}" nenรญ ฤitelnรฝ.',
msgFilePreviewAborted: 'Nรกhled souboru byl pลeruลกen pro "{name}".',
msgFilePreviewError: 'Nastala chyba pลi naฤtenรญ souboru "{name}".',
msgInvalidFileType: 'Neplatnรฝ typ souboru "{name}". Pouze "{types}" souborลฏ jsou podporovรกny.',
msgInvalidFileExtension: 'Neplatnรก extenze souboru "{name}". Pouze "{extensions}" souborลฏ jsou podporovรกny.',
msgUploadAborted: 'Soubor nahrรกvรกnรญ byl pลeruลกen',
msgValidationError: 'Chyba ovฤลenรญ',
msgLoading: 'Nahrรกvรกnรญ souboru {index} z {files} …',
msgProgress: 'Nahrรกvรกnรญ souboru {index} z {files} - {name} - {percent}% dokonฤeno.',
msgSelected: '{n} {files} vybrano',
msgFoldersNotAllowed: 'Tรกhni a pusลฅ pouze soubory! Vynechanรฉ {n} pustฤnรฉ sloลพk(y).',
msgImageWidthSmall: 'ล รญลka image soubor "{name}", musรญ bรฝt alespoล {size} px.',
msgImageHeightSmall: 'Vรฝลกka image soubor "{name}", musรญ bรฝt alespoล {size} px.',
msgImageWidthLarge: 'ล รญลka obrazovรฉho souboru "{name}" nelze pลekroฤit {size} px.',
msgImageHeightLarge: 'Vรฝลกka obrazovรฉho souboru "{name}" nelze pลekroฤit {size} px.',
msgImageResizeError: 'Nelze zรญskat rozmฤry obrรกzku zmฤnit velikost.',
msgImageResizeException: 'Chyba pลi zmฤnฤ velikosti obrรกzku.<pre>{errors}</pre>',
dropZoneTitle: 'Tรกhni a pusลฅ soubory sem …',
fileActionSettings: {
removeTitle: 'Odstranit soubor',
uploadTitle: 'nahrรกt soubor',
indicatorNewTitle: 'Jeลกtฤ nenahrรกl',
indicatorSuccessTitle: 'Nahranรฝ',
indicatorErrorTitle: 'Nahrรกt Chyba',
indicatorLoadingTitle: 'Nahrรกvรกnรญ ...'
}
};
})(window.jQuery);
|
javiomoreno/Cachama
|
web/sb-admin/bower_components/bootstrap-fileinput/js/fileinput_locale_cz.js
|
JavaScript
|
bsd-3-clause
| 3,292 |
/**
@module ember
@submodule ember-htmlbars
*/
import Ember from 'ember-metal/core';
import EmberStringUtils from 'ember-runtime/system/string';
import { SafeString, escapeExpression } from 'htmlbars-util';
/**
Mark a string as safe for unescaped output with Ember templates. If you
return HTML from a helper, use this function to
ensure Ember's rendering layer does not escape the HTML.
```javascript
Ember.String.htmlSafe('<div>someString</div>')
```
@method htmlSafe
@for Ember.String
@static
@return {Handlebars.SafeString} a string that will not be html escaped by Handlebars
@public
*/
function htmlSafe(str) {
if (str === null || str === undefined) {
return '';
}
if (typeof str !== 'string') {
str = '' + str;
}
return new SafeString(str);
}
EmberStringUtils.htmlSafe = htmlSafe;
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) {
String.prototype.htmlSafe = function() {
return htmlSafe(this);
};
}
export {
SafeString,
htmlSafe,
escapeExpression
};
|
udhayam/ember.js
|
packages/ember-htmlbars/lib/utils/string.js
|
JavaScript
|
mit
| 1,043 |
/**
* @license Highmaps JS v5.0.1 (2016-10-26)
*
* (c) 2011-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function(root, factory) {
if (typeof module === 'object' && module.exports) {
module.exports = root.document ?
factory(root) :
factory;
} else {
root.Highcharts = factory(root);
}
}(typeof window !== 'undefined' ? window : this, function(win) {
var Highcharts = (function() {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
/* global window */
var win = window,
doc = win.document;
var SVG_NS = 'http://www.w3.org/2000/svg',
userAgent = (win.navigator && win.navigator.userAgent) || '',
svg = doc && doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
isMS = /(edge|msie|trident)/i.test(userAgent) && !window.opera,
vml = !svg,
isFirefox = /Firefox/.test(userAgent),
hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4; // issue #38
var Highcharts = win.Highcharts ? win.Highcharts.error(16, true) : {
product: 'Highmaps',
version: '5.0.1',
deg2rad: Math.PI * 2 / 360,
doc: doc,
hasBidiBug: hasBidiBug,
hasTouch: doc && doc.documentElement.ontouchstart !== undefined,
isMS: isMS,
isWebKit: /AppleWebKit/.test(userAgent),
isFirefox: isFirefox,
isTouchDevice: /(Mobile|Android|Windows Phone)/.test(userAgent),
SVG_NS: SVG_NS,
idCounter: 0,
chartCount: 0,
seriesTypes: {},
symbolSizes: {},
svg: svg,
vml: vml,
win: win,
charts: [],
marginNames: ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
noop: function() {
return undefined;
}
};
return Highcharts;
}());
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var timers = [];
var charts = H.charts,
doc = H.doc,
win = H.win;
/**
* Provide error messages for debugging, with links to online explanation
*/
H.error = function(code, stop) {
var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
if (stop) {
throw new Error(msg);
}
// else ...
if (win.console) {
console.log(msg); // eslint-disable-line no-console
}
};
/**
* An animator object. One instance applies to one property (attribute or style prop)
* on one element.
*
* @param {object} elem The element to animate. May be a DOM element or a Highcharts SVGElement wrapper.
* @param {object} options Animation options, including duration, easing, step and complete.
* @param {object} prop The property to animate.
*/
H.Fx = function(elem, options, prop) {
this.options = options;
this.elem = elem;
this.prop = prop;
};
H.Fx.prototype = {
/**
* Animating a path definition on SVGElement
* @returns {undefined}
*/
dSetter: function() {
var start = this.paths[0],
end = this.paths[1],
ret = [],
now = this.now,
i = start.length,
startVal;
if (now === 1) { // land on the final path without adjustment points appended in the ends
ret = this.toD;
} else if (i === end.length && now < 1) {
while (i--) {
startVal = parseFloat(start[i]);
ret[i] =
isNaN(startVal) ? // a letter instruction like M or L
start[i] :
now * (parseFloat(end[i] - startVal)) + startVal;
}
} else { // if animation is finished or length not matching, land on right value
ret = end;
}
this.elem.attr('d', ret);
},
/**
* Update the element with the current animation step
* @returns {undefined}
*/
update: function() {
var elem = this.elem,
prop = this.prop, // if destroyed, it is null
now = this.now,
step = this.options.step;
// Animation setter defined from outside
if (this[prop + 'Setter']) {
this[prop + 'Setter']();
// Other animations on SVGElement
} else if (elem.attr) {
if (elem.element) {
elem.attr(prop, now);
}
// HTML styles, raw HTML content like container size
} else {
elem.style[prop] = now + this.unit;
}
if (step) {
step.call(elem, now, this);
}
},
/**
* Run an animation
*/
run: function(from, to, unit) {
var self = this,
timer = function(gotoEnd) {
return timer.stopped ? false : self.step(gotoEnd);
},
i;
this.startTime = +new Date();
this.start = from;
this.end = to;
this.unit = unit;
this.now = this.start;
this.pos = 0;
timer.elem = this.elem;
if (timer() && timers.push(timer) === 1) {
timer.timerId = setInterval(function() {
for (i = 0; i < timers.length; i++) {
if (!timers[i]()) {
timers.splice(i--, 1);
}
}
if (!timers.length) {
clearInterval(timer.timerId);
}
}, 13);
}
},
/**
* Run a single step in the animation
* @param {Boolean} gotoEnd Whether to go to then endpoint of the animation after abort
* @returns {Boolean} True if animation continues
*/
step: function(gotoEnd) {
var t = +new Date(),
ret,
done,
options = this.options,
elem = this.elem,
complete = options.complete,
duration = options.duration,
curAnim = options.curAnim,
i;
if (elem.attr && !elem.element) { // #2616, element including flag is destroyed
ret = false;
} else if (gotoEnd || t >= duration + this.startTime) {
this.now = this.end;
this.pos = 1;
this.update();
curAnim[this.prop] = true;
done = true;
for (i in curAnim) {
if (curAnim[i] !== true) {
done = false;
}
}
if (done && complete) {
complete.call(elem);
}
ret = false;
} else {
this.pos = options.easing((t - this.startTime) / duration);
this.now = this.start + ((this.end - this.start) * this.pos);
this.update();
ret = true;
}
return ret;
},
/**
* Prepare start and end values so that the path can be animated one to one
*/
initPath: function(elem, fromD, toD) {
fromD = fromD || '';
var shift,
startX = elem.startX,
endX = elem.endX,
bezier = fromD.indexOf('C') > -1,
numParams = bezier ? 7 : 3,
fullLength,
slice,
i,
start = fromD.split(' '),
end = toD.slice(), // copy
isArea = elem.isArea,
positionFactor = isArea ? 2 : 1,
reverse;
/**
* In splines make move points have six parameters like bezier curves
*/
function sixify(arr) {
i = arr.length;
while (i--) {
if (arr[i] === 'M' || arr[i] === 'L') {
arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
}
}
}
/**
* Insert an array at the given position of another array
*/
function insertSlice(arr, subArr, index) {
[].splice.apply(
arr, [index, 0].concat(subArr)
);
}
/**
* If shifting points, prepend a dummy point to the end path.
*/
function prepend(arr, other) {
while (arr.length < fullLength) {
// Move to, line to or curve to?
arr[0] = other[fullLength - arr.length];
// Prepend a copy of the first point
insertSlice(arr, arr.slice(0, numParams), 0);
// For areas, the bottom path goes back again to the left, so we need
// to append a copy of the last point.
if (isArea) {
insertSlice(arr, arr.slice(arr.length - numParams), arr.length);
i--;
}
}
arr[0] = 'M';
}
/**
* Copy and append last point until the length matches the end length
*/
function append(arr, other) {
var i = (fullLength - arr.length) / numParams;
while (i > 0 && i--) {
// Pull out the slice that is going to be appended or inserted. In a line graph,
// the positionFactor is 1, and the last point is sliced out. In an area graph,
// the positionFactor is 2, causing the middle two points to be sliced out, since
// an area path starts at left, follows the upper path then turns and follows the
// bottom back.
slice = arr.slice().splice(
(arr.length / positionFactor) - numParams,
numParams * positionFactor
);
// Move to, line to or curve to?
slice[0] = other[fullLength - numParams - (i * numParams)];
// Disable first control point
if (bezier) {
slice[numParams - 6] = slice[numParams - 2];
slice[numParams - 5] = slice[numParams - 1];
}
// Now insert the slice, either in the middle (for areas) or at the end (for lines)
insertSlice(arr, slice, arr.length / positionFactor);
if (isArea) {
i--;
}
}
}
if (bezier) {
sixify(start);
sixify(end);
}
// For sideways animation, find out how much we need to shift to get the start path Xs
// to match the end path Xs.
if (startX && endX) {
for (i = 0; i < startX.length; i++) {
if (startX[i] === endX[0]) { // Moving left, new points coming in on right
shift = i;
break;
} else if (startX[0] === endX[endX.length - startX.length + i]) { // Moving right
shift = i;
reverse = true;
break;
}
}
if (shift === undefined) {
start = [];
}
}
if (start.length && H.isNumber(shift)) {
// The common target length for the start and end array, where both
// arrays are padded in opposite ends
fullLength = end.length + shift * positionFactor * numParams;
if (!reverse) {
prepend(end, start);
append(start, end);
} else {
prepend(start, end);
append(end, start);
}
}
return [start, end];
}
}; // End of Fx prototype
/**
* Extend an object with the members of another
* @param {Object} a The object to be extended
* @param {Object} b The object to add to the first one
*/
H.extend = function(a, b) {
var n;
if (!a) {
a = {};
}
for (n in b) {
a[n] = b[n];
}
return a;
};
/**
* Deep merge two or more objects and return a third object. If the first argument is
* true, the contents of the second object is copied into the first object.
* Previously this function redirected to jQuery.extend(true), but this had two limitations.
* First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
* it copied properties from extended prototypes.
*/
H.merge = function() {
var i,
args = arguments,
len,
ret = {},
doCopy = function(copy, original) {
var value, key;
// An object is replacing a primitive
if (typeof copy !== 'object') {
copy = {};
}
for (key in original) {
if (original.hasOwnProperty(key)) {
value = original[key];
// Copy the contents of objects, but not arrays or DOM nodes
if (H.isObject(value, true) &&
key !== 'renderTo' && typeof value.nodeType !== 'number') {
copy[key] = doCopy(copy[key] || {}, value);
// Primitives and arrays are copied over directly
} else {
copy[key] = original[key];
}
}
}
return copy;
};
// If first argument is true, copy into the existing object. Used in setOptions.
if (args[0] === true) {
ret = args[1];
args = Array.prototype.slice.call(args, 2);
}
// For each argument, extend the return
len = args.length;
for (i = 0; i < len; i++) {
ret = doCopy(ret, args[i]);
}
return ret;
};
/**
* Shortcut for parseInt
* @param {Object} s
* @param {Number} mag Magnitude
*/
H.pInt = function(s, mag) {
return parseInt(s, mag || 10);
};
/**
* Check for string
* @param {Object} s
*/
H.isString = function(s) {
return typeof s === 'string';
};
/**
* Check for object
* @param {Object} obj
* @param {Boolean} strict Also checks that the object is not an array
*/
H.isArray = function(obj) {
var str = Object.prototype.toString.call(obj);
return str === '[object Array]' || str === '[object Array Iterator]';
};
/**
* Check for array
* @param {Object} obj
*/
H.isObject = function(obj, strict) {
return obj && typeof obj === 'object' && (!strict || !H.isArray(obj));
};
/**
* Check for number
* @param {Object} n
*/
H.isNumber = function(n) {
return typeof n === 'number' && !isNaN(n);
};
/**
* Remove last occurence of an item from an array
* @param {Array} arr
* @param {Mixed} item
*/
H.erase = function(arr, item) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
arr.splice(i, 1);
break;
}
}
//return arr;
};
/**
* Returns true if the object is not null or undefined.
* @param {Object} obj
*/
H.defined = function(obj) {
return obj !== undefined && obj !== null;
};
/**
* Set or get an attribute or an object of attributes. Can't use jQuery attr because
* it attempts to set expando properties on the SVG element, which is not allowed.
*
* @param {Object} elem The DOM element to receive the attribute(s)
* @param {String|Object} prop The property or an abject of key-value pairs
* @param {String} value The value if a single property is set
*/
H.attr = function(elem, prop, value) {
var key,
ret;
// if the prop is a string
if (H.isString(prop)) {
// set the value
if (H.defined(value)) {
elem.setAttribute(prop, value);
// get the value
} else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
ret = elem.getAttribute(prop);
}
// else if prop is defined, it is a hash of key/value pairs
} else if (H.defined(prop) && H.isObject(prop)) {
for (key in prop) {
elem.setAttribute(key, prop[key]);
}
}
return ret;
};
/**
* Check if an element is an array, and if not, make it into an array.
*/
H.splat = function(obj) {
return H.isArray(obj) ? obj : [obj];
};
/**
* Set a timeout if the delay is given, otherwise perform the function synchronously
* @param {Function} fn The function to perform
* @param {Number} delay Delay in milliseconds
* @param {Ojbect} context The context
* @returns {Nubmer} An identifier for the timeout
*/
H.syncTimeout = function(fn, delay, context) {
if (delay) {
return setTimeout(fn, delay, context);
}
fn.call(0, context);
};
/**
* Return the first value that is defined.
*/
H.pick = function() {
var args = arguments,
i,
arg,
length = args.length;
for (i = 0; i < length; i++) {
arg = args[i];
if (arg !== undefined && arg !== null) {
return arg;
}
}
};
/**
* Set CSS on a given element
* @param {Object} el
* @param {Object} styles Style object with camel case property names
*/
H.css = function(el, styles) {
if (H.isMS && !H.svg) { // #2686
if (styles && styles.opacity !== undefined) {
styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
}
}
H.extend(el.style, styles);
};
/**
* Utility function to create element with attributes and styles
* @param {Object} tag
* @param {Object} attribs
* @param {Object} styles
* @param {Object} parent
* @param {Object} nopad
*/
H.createElement = function(tag, attribs, styles, parent, nopad) {
var el = doc.createElement(tag),
css = H.css;
if (attribs) {
H.extend(el, attribs);
}
if (nopad) {
css(el, {
padding: 0,
border: 'none',
margin: 0
});
}
if (styles) {
css(el, styles);
}
if (parent) {
parent.appendChild(el);
}
return el;
};
/**
* Extend a prototyped class by new members
* @param {Object} parent
* @param {Object} members
*/
H.extendClass = function(Parent, members) {
var object = function() {};
object.prototype = new Parent();
H.extend(object.prototype, members);
return object;
};
/**
* Pad a string to a given length by adding 0 to the beginning
* @param {Number} number
* @param {Number} length
*/
H.pad = function(number, length, padder) {
return new Array((length || 2) + 1 - String(number).length).join(padder || 0) + number;
};
/**
* Return a length based on either the integer value, or a percentage of a base.
*/
H.relativeLength = function(value, base) {
return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value);
};
/**
* Wrap a method with extended functionality, preserving the original function
* @param {Object} obj The context object that the method belongs to
* @param {String} method The name of the method to extend
* @param {Function} func A wrapper function callback. This function is called with the same arguments
* as the original function, except that the original function is unshifted and passed as the first
* argument.
*/
H.wrap = function(obj, method, func) {
var proceed = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(proceed);
return func.apply(this, args);
};
};
H.getTZOffset = function(timestamp) {
var d = H.Date;
return ((d.hcGetTimezoneOffset && d.hcGetTimezoneOffset(timestamp)) || d.hcTimezoneOffset || 0) * 60000;
};
/**
* Based on http://www.php.net/manual/en/function.strftime.php
* @param {String} format
* @param {Number} timestamp
* @param {Boolean} capitalize
*/
H.dateFormat = function(format, timestamp, capitalize) {
if (!H.defined(timestamp) || isNaN(timestamp)) {
return H.defaultOptions.lang.invalidDate || '';
}
format = H.pick(format, '%Y-%m-%d %H:%M:%S');
var D = H.Date,
date = new D(timestamp - H.getTZOffset(timestamp)),
key, // used in for constuct below
// get the basic time values
hours = date[D.hcGetHours](),
day = date[D.hcGetDay](),
dayOfMonth = date[D.hcGetDate](),
month = date[D.hcGetMonth](),
fullYear = date[D.hcGetFullYear](),
lang = H.defaultOptions.lang,
langWeekdays = lang.weekdays,
shortWeekdays = lang.shortWeekdays,
pad = H.pad,
// List all format keys. Custom formats can be added from the outside.
replacements = H.extend({
// Day
'a': shortWeekdays ? shortWeekdays[day] : langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
'A': langWeekdays[day], // Long weekday, like 'Monday'
'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
'e': pad(dayOfMonth, 2, ' '), // Day of the month, 1 through 31
'w': day,
// Week (none implemented)
//'W': weekNumber(),
// Month
'b': lang.shortMonths[month], // Short month, like 'Jan'
'B': lang.months[month], // Long month, like 'January'
'm': pad(month + 1), // Two digit month number, 01 through 12
// Year
'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
'Y': fullYear, // Four digits year, like 2009
// Time
'H': pad(hours), // Two digits hours in 24h format, 00 through 23
'k': hours, // Hours in 24h format, 0 through 23
'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
'M': pad(date[D.hcGetMinutes]()), // Two digits minutes, 00 through 59
'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
'L': pad(Math.round(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
}, H.dateFormats);
// do the replaces
for (key in replacements) {
while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
format = format.replace(
'%' + key,
typeof replacements[key] === 'function' ?
replacements[key](timestamp) :
replacements[key]
);
}
}
// Optionally capitalize the string and return
return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
};
/**
* Format a single variable. Similar to sprintf, without the % prefix.
*/
H.formatSingle = function(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = H.defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
if (val !== null) {
val = H.numberFormat(
val,
decimals,
lang.decimalPoint,
format.indexOf(',') > -1 ? lang.thousandsSep : ''
);
}
} else {
val = H.dateFormat(format, val);
}
return val;
};
/**
* Format a string according to a subset of the rules of Python's String.format method.
*/
H.format = function(str, ctx) {
var splitter = '{',
isInside = false,
segment,
valueAndFormat,
path,
i,
len,
ret = [],
val,
index;
while (str) {
index = str.indexOf(splitter);
if (index === -1) {
break;
}
segment = str.slice(0, index);
if (isInside) { // we're on the closing bracket looking back
valueAndFormat = segment.split(':');
path = valueAndFormat.shift().split('.'); // get first and leave format
len = path.length;
val = ctx;
// Assign deeper paths
for (i = 0; i < len; i++) {
val = val[path[i]];
}
// Format the replacement
if (valueAndFormat.length) {
val = H.formatSingle(valueAndFormat.join(':'), val);
}
// Push the result and advance the cursor
ret.push(val);
} else {
ret.push(segment);
}
str = str.slice(index + 1); // the rest
isInside = !isInside; // toggle
splitter = isInside ? '}' : '{'; // now look for next matching bracket
}
ret.push(str);
return ret.join('');
};
/**
* Get the magnitude of a number
*/
H.getMagnitude = function(num) {
return Math.pow(10, Math.floor(Math.log(num) / Math.LN10));
};
/**
* Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
* @param {Number} interval
* @param {Array} multiples
* @param {Number} magnitude
* @param {Object} options
*/
H.normalizeTickInterval = function(interval, multiples, magnitude, allowDecimals, preventExceed) {
var normalized,
i,
retInterval = interval;
// round to a tenfold of 1, 2, 2.5 or 5
magnitude = H.pick(magnitude, 1);
normalized = interval / magnitude;
// multiples for a linear scale
if (!multiples) {
multiples = [1, 2, 2.5, 5, 10];
// the allowDecimals option
if (allowDecimals === false) {
if (magnitude === 1) {
multiples = [1, 2, 5, 10];
} else if (magnitude <= 0.1) {
multiples = [1 / magnitude];
}
}
}
// normalize the interval to the nearest multiple
for (i = 0; i < multiples.length; i++) {
retInterval = multiples[i];
if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural
(!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) {
break;
}
}
// multiply back to the correct magnitude
retInterval *= magnitude;
return retInterval;
};
/**
* Utility method that sorts an object array and keeping the order of equal items.
* ECMA script standard does not specify the behaviour when items are equal.
*/
H.stableSort = function(arr, sortFunction) {
var length = arr.length,
sortValue,
i;
// Add index to each item
for (i = 0; i < length; i++) {
arr[i].safeI = i; // stable sort index
}
arr.sort(function(a, b) {
sortValue = sortFunction(a, b);
return sortValue === 0 ? a.safeI - b.safeI : sortValue;
});
// Remove index from items
for (i = 0; i < length; i++) {
delete arr[i].safeI; // stable sort index
}
};
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
H.arrayMin = function(data) {
var i = data.length,
min = data[0];
while (i--) {
if (data[i] < min) {
min = data[i];
}
}
return min;
};
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
H.arrayMax = function(data) {
var i = data.length,
max = data[0];
while (i--) {
if (data[i] > max) {
max = data[i];
}
}
return max;
};
/**
* Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
* It loops all properties and invokes destroy if there is a destroy method. The property is
* then delete'ed.
* @param {Object} The object to destroy properties on
* @param {Object} Exception, do not destroy this property, only delete it.
*/
H.destroyObjectProperties = function(obj, except) {
var n;
for (n in obj) {
// If the object is non-null and destroy is defined
if (obj[n] && obj[n] !== except && obj[n].destroy) {
// Invoke the destroy
obj[n].destroy();
}
// Delete the property from the object.
delete obj[n];
}
};
/**
* Discard an element by moving it to the bin and delete
* @param {Object} The HTML node to discard
*/
H.discardElement = function(element) {
var garbageBin = H.garbageBin;
// create a garbage bin element, not part of the DOM
if (!garbageBin) {
garbageBin = H.createElement('div');
}
// move the node and empty bin
if (element) {
garbageBin.appendChild(element);
}
garbageBin.innerHTML = '';
};
/**
* Fix JS round off float errors
* @param {Number} num
*/
H.correctFloat = function(num, prec) {
return parseFloat(
num.toPrecision(prec || 14)
);
};
/**
* Set the global animation to either a given value, or fall back to the
* given chart's animation option
* @param {Object} animation
* @param {Object} chart
*/
H.setAnimation = function(animation, chart) {
chart.renderer.globalAnimation = H.pick(animation, chart.options.chart.animation, true);
};
/**
* Get the animation in object form, where a disabled animation is always
* returned with duration: 0
*/
H.animObject = function(animation) {
return H.isObject(animation) ? H.merge(animation) : {
duration: animation ? 500 : 0
};
};
/**
* The time unit lookup
*/
H.timeUnits = {
millisecond: 1,
second: 1000,
minute: 60000,
hour: 3600000,
day: 24 * 3600000,
week: 7 * 24 * 3600000,
month: 28 * 24 * 3600000,
year: 364 * 24 * 3600000
};
/**
* Format a number and return a string based on input settings
* @param {Number} number The input number to format
* @param {Number} decimals The amount of decimals
* @param {String} decimalPoint The decimal point, defaults to the one given in the lang options
* @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
*/
H.numberFormat = function(number, decimals, decimalPoint, thousandsSep) {
number = +number || 0;
decimals = +decimals;
var lang = H.defaultOptions.lang,
origDec = (number.toString().split('.')[1] || '').length,
decimalComponent,
strinteger,
thousands,
absNumber = Math.abs(number),
ret;
if (decimals === -1) {
decimals = Math.min(origDec, 20); // Preserve decimals. Not huge numbers (#3793).
} else if (!H.isNumber(decimals)) {
decimals = 2;
}
// A string containing the positive integer component of the number
strinteger = String(H.pInt(absNumber.toFixed(decimals)));
// Leftover after grouping into thousands. Can be 0, 1 or 3.
thousands = strinteger.length > 3 ? strinteger.length % 3 : 0;
// Language
decimalPoint = H.pick(decimalPoint, lang.decimalPoint);
thousandsSep = H.pick(thousandsSep, lang.thousandsSep);
// Start building the return
ret = number < 0 ? '-' : '';
// Add the leftover after grouping into thousands. For example, in the number 42 000 000,
// this line adds 42.
ret += thousands ? strinteger.substr(0, thousands) + thousandsSep : '';
// Add the remaining thousands groups, joined by the thousands separator
ret += strinteger.substr(thousands).replace(/(\d{3})(?=\d)/g, '$1' + thousandsSep);
// Add the decimal point and the decimal component
if (decimals) {
// Get the decimal component, and add power to avoid rounding errors with float numbers (#4573)
decimalComponent = Math.abs(absNumber - strinteger + Math.pow(10, -Math.max(decimals, origDec) - 1));
ret += decimalPoint + decimalComponent.toFixed(decimals).slice(2);
}
return ret;
};
/**
* Easing definition
* @param {Number} pos Current position, ranging from 0 to 1
*/
Math.easeInOutSine = function(pos) {
return -0.5 * (Math.cos(Math.PI * pos) - 1);
};
/**
* Internal method to return CSS value for given element and property
*/
H.getStyle = function(el, prop) {
var style;
// For width and height, return the actual inner pixel size (#4913)
if (prop === 'width') {
return Math.min(el.offsetWidth, el.scrollWidth) -
H.getStyle(el, 'padding-left') -
H.getStyle(el, 'padding-right');
} else if (prop === 'height') {
return Math.min(el.offsetHeight, el.scrollHeight) -
H.getStyle(el, 'padding-top') -
H.getStyle(el, 'padding-bottom');
}
// Otherwise, get the computed style
style = win.getComputedStyle(el, undefined);
return style && H.pInt(style.getPropertyValue(prop));
};
/**
* Return the index of an item in an array, or -1 if not found
*/
H.inArray = function(item, arr) {
return arr.indexOf ? arr.indexOf(item) : [].indexOf.call(arr, item);
};
/**
* Filter an array
*/
H.grep = function(elements, callback) {
return [].filter.call(elements, callback);
};
/**
* Map an array
*/
H.map = function(arr, fn) {
var results = [],
i = 0,
len = arr.length;
for (; i < len; i++) {
results[i] = fn.call(arr[i], arr[i], i, arr);
}
return results;
};
/**
* Get the element's offset position, corrected by overflow:auto.
*/
H.offset = function(el) {
var docElem = doc.documentElement,
box = el.getBoundingClientRect();
return {
top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0)
};
};
/**
* Stop running animation.
* A possible extension to this would be to stop a single property, when
* we want to continue animating others. Then assign the prop to the timer
* in the Fx.run method, and check for the prop here. This would be an improvement
* in all cases where we stop the animation from .attr. Instead of stopping
* everything, we can just stop the actual attributes we're setting.
*/
H.stop = function(el) {
var i = timers.length;
// Remove timers related to this element (#4519)
while (i--) {
if (timers[i].elem === el) {
timers[i].stopped = true; // #4667
}
}
};
/**
* Utility for iterating over an array.
* @param {Array} arr
* @param {Function} fn
*/
H.each = function(arr, fn, ctx) { // modern browsers
return Array.prototype.forEach.call(arr, fn, ctx);
};
/**
* Add an event listener
*/
H.addEvent = function(el, type, fn) {
var events = el.hcEvents = el.hcEvents || {};
function wrappedFn(e) {
e.target = e.srcElement || win; // #2820
fn.call(el, e);
}
// Handle DOM events in modern browsers
if (el.addEventListener) {
el.addEventListener(type, fn, false);
// Handle old IE implementation
} else if (el.attachEvent) {
if (!el.hcEventsIE) {
el.hcEventsIE = {};
}
// Link wrapped fn with original fn, so we can get this in removeEvent
el.hcEventsIE[fn.toString()] = wrappedFn;
el.attachEvent('on' + type, wrappedFn);
}
if (!events[type]) {
events[type] = [];
}
events[type].push(fn);
};
/**
* Remove event added with addEvent
*/
H.removeEvent = function(el, type, fn) {
var events,
hcEvents = el.hcEvents,
index;
function removeOneEvent(type, fn) {
if (el.removeEventListener) {
el.removeEventListener(type, fn, false);
} else if (el.attachEvent) {
fn = el.hcEventsIE[fn.toString()];
el.detachEvent('on' + type, fn);
}
}
function removeAllEvents() {
var types,
len,
n;
if (!el.nodeName) {
return; // break on non-DOM events
}
if (type) {
types = {};
types[type] = true;
} else {
types = hcEvents;
}
for (n in types) {
if (hcEvents[n]) {
len = hcEvents[n].length;
while (len--) {
removeOneEvent(n, hcEvents[n][len]);
}
}
}
}
if (hcEvents) {
if (type) {
events = hcEvents[type] || [];
if (fn) {
index = H.inArray(fn, events);
if (index > -1) {
events.splice(index, 1);
hcEvents[type] = events;
}
removeOneEvent(type, fn);
} else {
removeAllEvents();
hcEvents[type] = [];
}
} else {
removeAllEvents();
el.hcEvents = {};
}
}
};
/**
* Fire an event on a custom object
*/
H.fireEvent = function(el, type, eventArguments, defaultFunction) {
var e,
hcEvents = el.hcEvents,
events,
len,
i,
fn;
eventArguments = eventArguments || {};
if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) {
e = doc.createEvent('Events');
e.initEvent(type, true, true);
//e.target = el;
H.extend(e, eventArguments);
if (el.dispatchEvent) {
el.dispatchEvent(e);
} else {
el.fireEvent(type, e);
}
} else if (hcEvents) {
events = hcEvents[type] || [];
len = events.length;
if (!eventArguments.target) { // We're running a custom event
H.extend(eventArguments, {
// Attach a simple preventDefault function to skip default handler if called.
// The built-in defaultPrevented property is not overwritable (#5112)
preventDefault: function() {
eventArguments.defaultPrevented = true;
},
// Setting target to native events fails with clicking the zoom-out button in Chrome.
target: el,
// If the type is not set, we're running a custom event (#2297). If it is set,
// we're running a browser event, and setting it will cause en error in
// IE8 (#2465).
type: type
});
}
for (i = 0; i < len; i++) {
fn = events[i];
// If the event handler return false, prevent the default handler from executing
if (fn && fn.call(el, eventArguments) === false) {
eventArguments.preventDefault();
}
}
}
// Run the default if not prevented
if (defaultFunction && !eventArguments.defaultPrevented) {
defaultFunction(eventArguments);
}
};
/**
* The global animate method, which uses Fx to create individual animators.
*/
H.animate = function(el, params, opt) {
var start,
unit = '',
end,
fx,
args,
prop;
if (!H.isObject(opt)) { // Number or undefined/null
args = arguments;
opt = {
duration: args[2],
easing: args[3],
complete: args[4]
};
}
if (!H.isNumber(opt.duration)) {
opt.duration = 400;
}
opt.easing = typeof opt.easing === 'function' ? opt.easing : (Math[opt.easing] || Math.easeInOutSine);
opt.curAnim = H.merge(params);
for (prop in params) {
fx = new H.Fx(el, opt, prop);
end = null;
if (prop === 'd') {
fx.paths = fx.initPath(
el,
el.d,
params.d
);
fx.toD = params.d;
start = 0;
end = 1;
} else if (el.attr) {
start = el.attr(prop);
} else {
start = parseFloat(H.getStyle(el, prop)) || 0;
if (prop !== 'opacity') {
unit = 'px';
}
}
if (!end) {
end = params[prop];
}
if (end.match && end.match('px')) {
end = end.replace(/px/g, ''); // #4351
}
fx.run(start, end, unit);
}
};
/**
* The series type factory.
*
* @param {string} type The series type name.
* @param {string} parent The parent series type name.
* @param {object} options The additional default options that is merged with the parent's options.
* @param {object} props The properties (functions and primitives) to set on the new prototype.
* @param {object} pointProps Members for a series-specific Point prototype if needed.
*/
H.seriesType = function(type, parent, options, props, pointProps) { // docs: add to API + extending Highcharts
var defaultOptions = H.getOptions(),
seriesTypes = H.seriesTypes;
// Merge the options
defaultOptions.plotOptions[type] = H.merge(
defaultOptions.plotOptions[parent],
options
);
// Create the class
seriesTypes[type] = H.extendClass(seriesTypes[parent] || function() {}, props);
seriesTypes[type].prototype.type = type;
// Create the point class if needed
if (pointProps) {
seriesTypes[type].prototype.pointClass = H.extendClass(H.Point, pointProps);
}
return seriesTypes[type];
};
/**
* Register Highcharts as a plugin in jQuery
*/
if (win.jQuery) {
win.jQuery.fn.highcharts = function() {
var args = [].slice.call(arguments);
if (this[0]) { // this[0] is the renderTo div
// Create the chart
if (args[0]) {
new H[ // eslint-disable-line no-new
H.isString(args[0]) ? args.shift() : 'Chart' // Constructor defaults to Chart
](this[0], args[0], args[1]);
return this;
}
// When called without parameters or with the return argument, return an existing chart
return charts[H.attr(this[0], 'data-highcharts-chart')];
}
};
}
/**
* Compatibility section to add support for legacy IE. This can be removed if old IE
* support is not needed.
*/
if (doc && !doc.defaultView) {
H.getStyle = function(el, prop) {
var val,
alias = {
width: 'clientWidth',
height: 'clientHeight'
}[prop];
if (el.style[prop]) {
return H.pInt(el.style[prop]);
}
if (prop === 'opacity') {
prop = 'filter';
}
// Getting the rendered width and height
if (alias) {
el.style.zoom = 1;
return Math.max(el[alias] - 2 * H.getStyle(el, 'padding'), 0);
}
val = el.currentStyle[prop.replace(/\-(\w)/g, function(a, b) {
return b.toUpperCase();
})];
if (prop === 'filter') {
val = val.replace(
/alpha\(opacity=([0-9]+)\)/,
function(a, b) {
return b / 100;
}
);
}
return val === '' ? 1 : H.pInt(val);
};
}
if (!Array.prototype.forEach) {
H.each = function(arr, fn, ctx) { // legacy
var i = 0,
len = arr.length;
for (; i < len; i++) {
if (fn.call(ctx, arr[i], i, arr) === false) {
return i;
}
}
};
}
if (!Array.prototype.indexOf) {
H.inArray = function(item, arr) {
var len,
i = 0;
if (arr) {
len = arr.length;
for (; i < len; i++) {
if (arr[i] === item) {
return i;
}
}
}
return -1;
};
}
if (!Array.prototype.filter) {
H.grep = function(elements, fn) {
var ret = [],
i = 0,
length = elements.length;
for (; i < length; i++) {
if (fn(elements[i], i)) {
ret.push(elements[i]);
}
}
return ret;
};
}
//--- End compatibility section ---
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var each = H.each,
isNumber = H.isNumber,
map = H.map,
merge = H.merge,
pInt = H.pInt;
/**
* Handle color operations. The object methods are chainable.
* @param {String} input The input color in either rbga or hex format
*/
H.Color = function(input) {
// Backwards compatibility, allow instanciation without new
if (!(this instanceof H.Color)) {
return new H.Color(input);
}
// Initialize
this.init(input);
};
H.Color.prototype = {
// Collection of parsers. This can be extended from the outside by pushing parsers
// to Highcharts.Color.prototype.parsers.
parsers: [{
// RGBA color
regex: /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,
parse: function(result) {
return [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
}
}, {
// HEX color
regex: /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
parse: function(result) {
return [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
}
}, {
// RGB color
regex: /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,
parse: function(result) {
return [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
}
}],
// Collection of named colors. Can be extended from the outside by adding colors
// to Highcharts.Color.prototype.names.
names: {
white: '#ffffff',
black: '#000000'
},
/**
* Parse the input color to rgba array
* @param {String} input
*/
init: function(input) {
var result,
rgba,
i,
parser;
this.input = input = this.names[input] || input;
// Gradients
if (input && input.stops) {
this.stops = map(input.stops, function(stop) {
return new H.Color(stop[1]);
});
// Solid colors
} else {
i = this.parsers.length;
while (i-- && !rgba) {
parser = this.parsers[i];
result = parser.regex.exec(input);
if (result) {
rgba = parser.parse(result);
}
}
}
this.rgba = rgba || [];
},
/**
* Return the color a specified format
* @param {String} format
*/
get: function(format) {
var input = this.input,
rgba = this.rgba,
ret;
if (this.stops) {
ret = merge(input);
ret.stops = [].concat(ret.stops);
each(this.stops, function(stop, i) {
ret.stops[i] = [ret.stops[i][0], stop.get(format)];
});
// it's NaN if gradient colors on a column chart
} else if (rgba && isNumber(rgba[0])) {
if (format === 'rgb' || (!format && rgba[3] === 1)) {
ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
} else if (format === 'a') {
ret = rgba[3];
} else {
ret = 'rgba(' + rgba.join(',') + ')';
}
} else {
ret = input;
}
return ret;
},
/**
* Brighten the color
* @param {Number} alpha
*/
brighten: function(alpha) {
var i,
rgba = this.rgba;
if (this.stops) {
each(this.stops, function(stop) {
stop.brighten(alpha);
});
} else if (isNumber(alpha) && alpha !== 0) {
for (i = 0; i < 3; i++) {
rgba[i] += pInt(alpha * 255);
if (rgba[i] < 0) {
rgba[i] = 0;
}
if (rgba[i] > 255) {
rgba[i] = 255;
}
}
}
return this;
},
/**
* Set the color's opacity to a given alpha value
* @param {Number} alpha
*/
setOpacity: function(alpha) {
this.rgba[3] = alpha;
return this;
}
};
H.color = function(input) {
return new H.Color(input);
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var color = H.color,
each = H.each,
getTZOffset = H.getTZOffset,
isTouchDevice = H.isTouchDevice,
merge = H.merge,
pick = H.pick,
svg = H.svg,
win = H.win;
/* ****************************************************************************
* Handle the options *
*****************************************************************************/
H.defaultOptions = {
symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
lang: {
loading: 'Loading...',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'
],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
// invalidDate: '',
decimalPoint: '.',
numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
resetZoom: 'Reset zoom',
resetZoomTitle: 'Reset zoom level 1:1',
thousandsSep: ' '
},
global: {
useUTC: true,
//timezoneOffset: 0
},
chart: {
//animation: true,
//alignTicks: false,
//reflow: true,
//className: null,
//events: { load, selection },
//margin: [null],
//marginTop: null,
//marginRight: null,
//marginBottom: null,
//marginLeft: null,
borderRadius: 0,
colorCount: 10,
defaultSeriesType: 'line',
ignoreHiddenSeries: true,
//inverted: false,
spacing: [10, 10, 15, 10],
//spacingTop: 10,
//spacingRight: 10,
//spacingBottom: 15,
//spacingLeft: 10,
//zoomType: ''
resetZoomButton: {
theme: {
zIndex: 20
},
position: {
align: 'right',
x: -10,
//verticalAlign: 'top',
y: 10
}
// relativeTo: 'plot'
},
width: null,
height: null
},
defs: {
dropShadow: { // used by tooltip
tagName: 'filter',
id: 'drop-shadow',
opacity: 0.5,
children: [{
tagName: 'feGaussianBlur',
in: 'SourceAlpha',
stdDeviation: 1
}, {
tagName: 'feOffset',
dx: 1,
dy: 1
}, {
tagName: 'feComponentTransfer',
children: [{
tagName: 'feFuncA',
type: 'linear',
slope: 0.3
}]
}, {
tagName: 'feMerge',
children: [{
tagName: 'feMergeNode'
}, {
tagName: 'feMergeNode',
in: 'SourceGraphic'
}]
}]
},
style: {
tagName: 'style',
textContent: '.highcharts-tooltip{' +
'filter:url(#drop-shadow)' +
'}'
}
},
title: {
text: 'Chart title',
align: 'center',
// floating: false,
margin: 15,
// x: 0,
// verticalAlign: 'top',
// y: null,
widthAdjust: -44
},
subtitle: {
text: '',
align: 'center',
// floating: false
// x: 0,
// verticalAlign: 'top',
// y: null,
widthAdjust: -44
},
plotOptions: {},
labels: {
//items: [],
style: {
//font: defaultFont,
position: 'absolute',
color: '#333333'
}
},
legend: {
enabled: true,
align: 'center',
//floating: false,
layout: 'horizontal',
labelFormatter: function() {
return this.name;
},
//borderWidth: 0,
borderColor: '#999999',
borderRadius: 0,
navigation: {
// animation: true,
// arrowSize: 12
// style: {} // text styles
},
// margin: 20,
// reversed: false,
// backgroundColor: null,
/*style: {
padding: '5px'
},*/
itemCheckboxStyle: {
position: 'absolute',
width: '13px', // for IE precision
height: '13px'
},
// itemWidth: undefined,
squareSymbol: true,
// symbolRadius: 0,
// symbolWidth: 16,
symbolPadding: 5,
verticalAlign: 'bottom',
// width: undefined,
x: 0,
y: 0,
title: {
//text: null
}
},
loading: {
// hideDuration: 100,
// showDuration: 0
},
tooltip: {
enabled: true,
animation: svg,
//crosshairs: null,
borderRadius: 3,
dateTimeLabelFormats: {
millisecond: '%A, %b %e, %H:%M:%S.%L',
second: '%A, %b %e, %H:%M:%S',
minute: '%A, %b %e, %H:%M',
hour: '%A, %b %e, %H:%M',
day: '%A, %b %e, %Y',
week: 'Week from %A, %b %e, %Y',
month: '%B %Y',
year: '%Y'
},
footerFormat: '',
//formatter: defaultFormatter,
/* todo: em font-size when finished comparing against HC4
headerFormat: '<span style="font-size: 0.85em">{point.key}</span><br/>',
*/
padding: 8,
//shape: 'callout',
//shared: false,
snap: isTouchDevice ? 25 : 10,
headerFormat: '<span class="highcharts-header">{point.key}</span><br/>',
pointFormat: '<span class="highcharts-color-{point.colorIndex}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>',
//xDateFormat: '%A, %b %e, %Y',
//valueDecimals: null,
//valuePrefix: '',
//valueSuffix: ''
},
credits: {
enabled: true,
href: 'http://www.highcharts.com',
position: {
align: 'right',
x: -10,
verticalAlign: 'bottom',
y: -5
},
text: 'Highcharts.com'
}
};
/**
* Set the time methods globally based on the useUTC option. Time method can be either
* local time or UTC (default).
*/
function setTimeMethods() {
var globalOptions = H.defaultOptions.global,
Date,
useUTC = globalOptions.useUTC,
GET = useUTC ? 'getUTC' : 'get',
SET = useUTC ? 'setUTC' : 'set';
H.Date = Date = globalOptions.Date || win.Date; // Allow using a different Date class
Date.hcTimezoneOffset = useUTC && globalOptions.timezoneOffset;
Date.hcGetTimezoneOffset = useUTC && globalOptions.getTimezoneOffset;
Date.hcMakeTime = function(year, month, date, hours, minutes, seconds) {
var d;
if (useUTC) {
d = Date.UTC.apply(0, arguments);
d += getTZOffset(d);
} else {
d = new Date(
year,
month,
pick(date, 1),
pick(hours, 0),
pick(minutes, 0),
pick(seconds, 0)
).getTime();
}
return d;
};
each(['Minutes', 'Hours', 'Day', 'Date', 'Month', 'FullYear'], function(s) {
Date['hcGet' + s] = GET + s;
});
each(['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear'], function(s) {
Date['hcSet' + s] = SET + s;
});
}
/**
* Merge the default options with custom options and return the new options structure
* @param {Object} options The new custom options
*/
H.setOptions = function(options) {
// Copy in the default options
H.defaultOptions = merge(true, H.defaultOptions, options);
// Apply UTC
setTimeMethods();
return H.defaultOptions;
};
/**
* Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules
* wasn't enough because the setOptions method created a new object.
*/
H.getOptions = function() {
return H.defaultOptions;
};
// Series defaults
H.defaultPlotOptions = H.defaultOptions.plotOptions;
// set the default time methods
setTimeMethods();
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var SVGElement,
SVGRenderer,
addEvent = H.addEvent,
animate = H.animate,
attr = H.attr,
charts = H.charts,
color = H.color,
css = H.css,
createElement = H.createElement,
defined = H.defined,
deg2rad = H.deg2rad,
destroyObjectProperties = H.destroyObjectProperties,
doc = H.doc,
each = H.each,
extend = H.extend,
erase = H.erase,
grep = H.grep,
hasTouch = H.hasTouch,
isArray = H.isArray,
isFirefox = H.isFirefox,
isMS = H.isMS,
isObject = H.isObject,
isString = H.isString,
isWebKit = H.isWebKit,
merge = H.merge,
noop = H.noop,
pick = H.pick,
pInt = H.pInt,
removeEvent = H.removeEvent,
splat = H.splat,
stop = H.stop,
svg = H.svg,
SVG_NS = H.SVG_NS,
symbolSizes = H.symbolSizes,
win = H.win;
/**
* A wrapper object for SVG elements
*/
SVGElement = H.SVGElement = function() {
return this;
};
SVGElement.prototype = {
// Default base for animation
opacity: 1,
SVG_NS: SVG_NS,
// For labels, these CSS properties are applied to the <text> node directly
textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color',
'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow'
],
/**
* Initialize the SVG renderer
* @param {Object} renderer
* @param {String} nodeName
*/
init: function(renderer, nodeName) {
var wrapper = this;
wrapper.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(wrapper.SVG_NS, nodeName);
wrapper.renderer = renderer;
},
/**
* Animate a given attribute
* @param {Object} params
* @param {Number} options Options include duration, easing, step and complete
* @param {Function} complete Function to perform at the end of animation
*/
animate: function(params, options, complete) {
var animOptions = pick(options, this.renderer.globalAnimation, true);
stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
if (animOptions) {
if (complete) { // allows using a callback with the global animation without overwriting it
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params, null, complete);
}
return this;
},
/**
* Build an SVG gradient out of a common JavaScript configuration object
*/
colorGradient: function(color, prop, elem) {
var renderer = this.renderer,
colorObject,
gradName,
gradAttr,
radAttr,
gradients,
gradientObject,
stops,
stopColor,
stopOpacity,
radialReference,
n,
id,
key = [],
value;
// Apply linear or radial gradients
if (color.linearGradient) {
gradName = 'linearGradient';
} else if (color.radialGradient) {
gradName = 'radialGradient';
}
if (gradName) {
gradAttr = color[gradName];
gradients = renderer.gradients;
stops = color.stops;
radialReference = elem.radialReference;
// Keep < 2.2 kompatibility
if (isArray(gradAttr)) {
color[gradName] = gradAttr = {
x1: gradAttr[0],
y1: gradAttr[1],
x2: gradAttr[2],
y2: gradAttr[3],
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
radAttr = gradAttr; // Save the radial attributes for updating
gradAttr = merge(gradAttr,
renderer.getRadialAttr(radialReference, radAttr), {
gradientUnits: 'userSpaceOnUse'
}
);
}
// Build the unique key to detect whether we need to create a new element (#1282)
for (n in gradAttr) {
if (n !== 'id') {
key.push(n, gradAttr[n]);
}
}
for (n in stops) {
key.push(stops[n]);
}
key = key.join(',');
// Check if a gradient object with the same config object is created within this renderer
if (gradients[key]) {
id = gradients[key].attr('id');
} else {
// Set the id and create the element
gradAttr.id = id = 'highcharts-' + H.idCounter++;
gradients[key] = gradientObject = renderer.createElement(gradName)
.attr(gradAttr)
.add(renderer.defs);
gradientObject.radAttr = radAttr;
// The gradient needs to keep a list of stops to be able to destroy them
gradientObject.stops = [];
each(stops, function(stop) {
var stopObject;
if (stop[1].indexOf('rgba') === 0) {
colorObject = H.color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
}
// Set the reference to the gradient object
value = 'url(' + renderer.url + '#' + id + ')';
elem.setAttribute(prop, value);
elem.gradient = key;
// Allow the color to be concatenated into tooltips formatters etc. (#2995)
color.toString = function() {
return value;
};
}
},
/**
* Apply a polyfill to the text-stroke CSS property, by copying the text element
* and apply strokes to the copy.
*
* Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/
*/
applyTextShadow: function(textShadow) {
var elem = this.element,
tspans,
hasContrast = textShadow.indexOf('contrast') !== -1,
styles = {},
forExport = this.renderer.forExport,
// IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check
// this again with new IE release. In exports, the rendering is passed to PhantomJS.
supports = this.renderer.forExport || (elem.style.textShadow !== undefined && !isMS);
// When the text shadow is set to contrast, use dark stroke for light text and vice versa
if (hasContrast) {
styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill));
}
// Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this,
// it removes the text shadows.
if (isWebKit || forExport) {
styles.textRendering = 'geometricPrecision';
}
/* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/)
if (elem.textContent.indexOf('2.') === 0) {
elem.style['text-shadow'] = 'none';
supports = false;
}
// */
// No reason to polyfill, we've got native support
if (supports) {
this.css(styles); // Apply altered textShadow or textRendering workaround
} else {
this.fakeTS = true; // Fake text shadow
// In order to get the right y position of the clones,
// copy over the y setter
this.ySetter = this.xSetter;
tspans = [].slice.call(elem.getElementsByTagName('tspan'));
each(textShadow.split(/\s?,\s?/g), function(textShadow) {
var firstChild = elem.firstChild,
color,
strokeWidth;
textShadow = textShadow.split(' ');
color = textShadow[textShadow.length - 1];
// Approximately tune the settings to the text-shadow behaviour
strokeWidth = textShadow[textShadow.length - 2];
if (strokeWidth) {
each(tspans, function(tspan, y) {
var clone;
// Let the first line start at the correct X position
if (y === 0) {
tspan.setAttribute('x', elem.getAttribute('x'));
y = elem.getAttribute('y');
tspan.setAttribute('y', y || 0);
if (y === null) {
elem.setAttribute('y', 0);
}
}
// Create the clone and apply shadow properties
clone = tspan.cloneNode(1);
attr(clone, {
'class': 'highcharts-text-shadow',
'fill': color,
'stroke': color,
'stroke-opacity': 1 / Math.max(pInt(strokeWidth), 3),
'stroke-width': strokeWidth,
'stroke-linejoin': 'round'
});
elem.insertBefore(clone, firstChild);
});
}
});
}
},
/**
* Set or get a given attribute
* @param {Object|String} hash
* @param {Mixed|Undefined} val
*/
attr: function(hash, val, complete) {
var key,
value,
element = this.element,
hasSetSymbolSize,
ret = this,
skipAttr,
setter;
// single key-value pair
if (typeof hash === 'string' && val !== undefined) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (typeof hash === 'string') {
ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element);
// setter
} else {
for (key in hash) {
value = hash[key];
skipAttr = false;
if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
if (!hasSetSymbolSize) {
this.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
}
if (this.rotation && (key === 'x' || key === 'y')) {
this.doTransform = true;
}
if (!skipAttr) {
setter = this[key + 'Setter'] || this._defaultSetter;
setter.call(this, value, key, element);
}
}
// Update transform. Do this outside the loop to prevent redundant updating for batch setting
// of attributes.
if (this.doTransform) {
this.updateTransform();
this.doTransform = false;
}
}
// In accordance with animate, run a complete callback
if (complete) {
complete();
}
return ret;
},
/**
* Add a class name to an element
*/
addClass: function(className, replace) {
var currentClassName = this.attr('class') || '';
if (currentClassName.indexOf(className) === -1) {
if (!replace) {
className = (currentClassName + (currentClassName ? ' ' : '') + className).replace(' ', ' ');
}
this.attr('class', className);
}
return this;
},
hasClass: function(className) {
return attr(this.element, 'class').indexOf(className) !== -1;
},
removeClass: function(className) {
attr(this.element, 'class', (attr(this.element, 'class') || '').replace(className, ''));
return this;
},
/**
* If one of the symbol size affecting parameters are changed,
* check all the others only once for each call to an element's
* .attr() method
* @param {Object} hash
*/
symbolAttr: function(hash) {
var wrapper = this;
each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function(key) {
wrapper[key] = pick(hash[key], wrapper[key]);
});
wrapper.attr({
d: wrapper.renderer.symbols[wrapper.symbolName](
wrapper.x,
wrapper.y,
wrapper.width,
wrapper.height,
wrapper
)
});
},
/**
* Apply a clipping path to this object
* @param {String} id
*/
clip: function(clipRect) {
return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : 'none');
},
/**
* Calculate the coordinates needed for drawing a rectangle crisply and return the
* calculated attributes
* @param {Number} strokeWidth
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
crisp: function(rect, strokeWidth) {
var wrapper = this,
key,
attribs = {},
normalizer;
strokeWidth = strokeWidth || rect.strokeWidth || 0;
normalizer = Math.round(strokeWidth) % 2 / 2; // Math.round because strokeWidth can sometimes have roundoff errors
// normalize for crisp edges
rect.x = Math.floor(rect.x || wrapper.x || 0) + normalizer;
rect.y = Math.floor(rect.y || wrapper.y || 0) + normalizer;
rect.width = Math.floor((rect.width || wrapper.width || 0) - 2 * normalizer);
rect.height = Math.floor((rect.height || wrapper.height || 0) - 2 * normalizer);
if (defined(rect.strokeWidth)) {
rect.strokeWidth = strokeWidth;
}
for (key in rect) {
if (wrapper[key] !== rect[key]) { // only set attribute if changed
wrapper[key] = attribs[key] = rect[key];
}
}
return attribs;
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: function(styles) {
var elemWrapper = this,
oldStyles = elemWrapper.styles,
newStyles = {},
elem = elemWrapper.element,
textWidth,
n,
serializedCss = '',
hyphenate,
hasNew = !oldStyles;
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Filter out existing styles to increase performance (#2640)
if (oldStyles) {
for (n in styles) {
if (styles[n] !== oldStyles[n]) {
newStyles[n] = styles[n];
hasNew = true;
}
}
}
if (hasNew) {
textWidth = elemWrapper.textWidth =
(styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) ||
elemWrapper.textWidth; // #3501
// Merge the new styles with the old ones
if (oldStyles) {
styles = extend(
oldStyles,
newStyles
);
}
// store object
elemWrapper.styles = styles;
if (textWidth && (!svg && elemWrapper.renderer.forExport)) {
delete styles.width;
}
// serialize and set style attribute
if (isMS && !svg) {
css(elemWrapper.element, styles);
} else {
hyphenate = function(a, b) {
return '-' + b.toLowerCase();
};
for (n in styles) {
serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
}
attr(elem, 'style', serializedCss); // #1881
}
// Rebuild text after added
if (elemWrapper.added && textWidth) {
elemWrapper.renderer.buildText(elemWrapper);
}
}
return elemWrapper;
},
/**
* Get a computed style
*/
getStyle: function(prop) {
return win.getComputedStyle(this.element || this, '').getPropertyValue(prop);
},
/**
* Get a computed style in pixel values
*/
strokeWidth: function() {
var val = this.getStyle('stroke-width'),
ret,
dummy;
// Read pixel values directly
if (val.indexOf('px') === val.length - 2) {
ret = pInt(val);
// Other values like em, pt etc need to be measured
} else {
dummy = doc.createElementNS(SVG_NS, 'rect');
attr(dummy, {
'width': val,
'stroke-width': 0
});
this.element.parentNode.appendChild(dummy);
ret = dummy.getBBox().width;
dummy.parentNode.removeChild(dummy);
}
return ret;
},
/**
* Add an event listener
* @param {String} eventType
* @param {Function} handler
*/
on: function(eventType, handler) {
var svgElement = this,
element = svgElement.element;
// touch
if (hasTouch && eventType === 'click') {
element.ontouchstart = function(e) {
svgElement.touchEventFired = Date.now();
e.preventDefault();
handler.call(element, e);
};
element.onclick = function(e) {
if (win.navigator.userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
handler.call(element, e);
}
};
} else {
// simplest possible event model for internal use
element['on' + eventType] = handler;
}
return this;
},
/**
* Set the coordinates needed to draw a consistent radial gradient across
* pie slices regardless of positioning inside the chart. The format is
* [centerX, centerY, diameter] in pixels.
*/
setRadialReference: function(coordinates) {
var existingGradient = this.renderer.gradients[this.element.gradient];
this.element.radialReference = coordinates;
// On redrawing objects with an existing gradient, the gradient needs
// to be repositioned (#3801)
if (existingGradient && existingGradient.radAttr) {
existingGradient.animate(
this.renderer.getRadialAttr(
coordinates,
existingGradient.radAttr
)
);
}
return this;
},
/**
* Move an object and its children by x and y values
* @param {Number} x
* @param {Number} y
*/
translate: function(x, y) {
return this.attr({
translateX: x,
translateY: y
});
},
/**
* Invert a group, rotate and flip
*/
invert: function(inverted) {
var wrapper = this;
wrapper.inverted = inverted;
wrapper.updateTransform();
return wrapper;
},
/**
* Private method to update the transform attribute based on internal
* properties
*/
updateTransform: function() {
var wrapper = this,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
scaleX = wrapper.scaleX,
scaleY = wrapper.scaleY,
inverted = wrapper.inverted,
rotation = wrapper.rotation,
element = wrapper.element,
transform;
// flipping affects translate as adjustment for flipping around the group's axis
if (inverted) {
translateX += wrapper.attr('width');
translateY += wrapper.attr('height');
}
// Apply translate. Nearly all transformed elements have translation, so instead
// of checking for translate = 0, do it always (#1767, #1846).
transform = ['translate(' + translateX + ',' + translateY + ')'];
// apply rotation
if (inverted) {
transform.push('rotate(90) scale(-1,1)');
} else if (rotation) { // text rotation
transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')');
// Delete bBox memo when the rotation changes
//delete wrapper.bBox;
}
// apply scale
if (defined(scaleX) || defined(scaleY)) {
transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
}
if (transform.length) {
element.setAttribute('transform', transform.join(' '));
}
},
/**
* Bring the element to the front
*/
toFront: function() {
var element = this.element;
element.parentNode.appendChild(element);
return this;
},
/**
* Break down alignment options like align, verticalAlign, x and y
* to x and y relative to the chart.
*
* @param {Object} alignOptions
* @param {Boolean} alignByTranslate
* @param {String[Object} box The box to align to, needs a width and height. When the
* box is a string, it refers to an object in the Renderer. For example, when
* box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
* x and y properties.
*
*/
align: function(alignOptions, alignByTranslate, box) {
var align,
vAlign,
x,
y,
attribs = {},
alignTo,
renderer = this.renderer,
alignedObjects = renderer.alignedObjects,
alignFactor,
vAlignFactor;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) { // boxes other than renderer handle this internally
this.alignTo = alignTo = box || 'renderer';
erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
alignedObjects.push(this);
box = null; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(box, renderer[alignTo], renderer);
// Assign variables
align = alignOptions.align;
vAlign = alignOptions.verticalAlign;
x = (box.x || 0) + (alignOptions.x || 0); // default: left align
y = (box.y || 0) + (alignOptions.y || 0); // default: top align
// Align
if (align === 'right') {
alignFactor = 1;
} else if (align === 'center') {
alignFactor = 2;
}
if (alignFactor) {
x += (box.width - (alignOptions.width || 0)) / alignFactor;
}
attribs[alignByTranslate ? 'translateX' : 'x'] = Math.round(x);
// Vertical align
if (vAlign === 'bottom') {
vAlignFactor = 1;
} else if (vAlign === 'middle') {
vAlignFactor = 2;
}
if (vAlignFactor) {
y += (box.height - (alignOptions.height || 0)) / vAlignFactor;
}
attribs[alignByTranslate ? 'translateY' : 'y'] = Math.round(y);
// Animate only if already placed
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
this.alignAttr = attribs;
return this;
},
/**
* Get the bounding box (width, height, x and y) for the element
*/
getBBox: function(reload, rot) {
var wrapper = this,
bBox, // = wrapper.bBox,
renderer = wrapper.renderer,
width,
height,
rotation,
rad,
element = wrapper.element,
styles = wrapper.styles,
fontSize,
textStr = wrapper.textStr,
textShadow,
elemStyle = element.style,
toggleTextShadowShim,
cache = renderer.cache,
cacheKeys = renderer.cacheKeys,
cacheKey;
rotation = pick(rot, wrapper.rotation);
rad = rotation * deg2rad;
fontSize = element && SVGElement.prototype.getStyle.call(element, 'font-size');
if (textStr !== undefined) {
cacheKey =
// Since numbers are monospaced, and numerical labels appear a lot in a chart,
// we assume that a label of n characters has the same bounding box as others
// of the same length.
textStr.toString().replace(/[0-9]/g, '0') +
// Properties that affect bounding box
['', rotation || 0, fontSize, element.style.width].join(',');
}
if (cacheKey && !reload) {
bBox = cache[cacheKey];
}
// No cache found
if (!bBox) {
// SVG elements
if (element.namespaceURI === wrapper.SVG_NS || renderer.forExport) {
try { // Fails in Firefox if the container has display: none.
// When the text shadow shim is used, we need to hide the fake shadows
// to get the correct bounding box (#3872)
toggleTextShadowShim = this.fakeTS && function(display) {
each(element.querySelectorAll('.highcharts-text-shadow'), function(tspan) {
tspan.style.display = display;
});
};
// Workaround for #3842, Firefox reporting wrong bounding box for shadows
if (isFirefox && elemStyle.textShadow) {
textShadow = elemStyle.textShadow;
elemStyle.textShadow = '';
} else if (toggleTextShadowShim) {
toggleTextShadowShim('none');
}
bBox = element.getBBox ?
// SVG: use extend because IE9 is not allowed to change width and height in case
// of rotation (below)
extend({}, element.getBBox()) :
// Legacy IE in export mode
{
width: element.offsetWidth,
height: element.offsetHeight
};
// #3842
if (textShadow) {
elemStyle.textShadow = textShadow;
} else if (toggleTextShadowShim) {
toggleTextShadowShim('');
}
} catch (e) {}
// If the bBox is not set, the try-catch block above failed. The other condition
// is for Opera that returns a width of -Infinity on hidden elements.
if (!bBox || bBox.width < 0) {
bBox = {
width: 0,
height: 0
};
}
// VML Renderer or useHTML within SVG
} else {
bBox = wrapper.htmlGetBBox();
}
// True SVG elements as well as HTML elements in modern browsers using the .useHTML option
// need to compensated for rotation
if (renderer.isSVG) {
width = bBox.width;
height = bBox.height;
// Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568)
if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') {
bBox.height = height = 14;
}
// Adjust for rotated text
if (rotation) {
bBox.width = Math.abs(height * Math.sin(rad)) + Math.abs(width * Math.cos(rad));
bBox.height = Math.abs(height * Math.cos(rad)) + Math.abs(width * Math.sin(rad));
}
}
// Cache it. When loading a chart in a hidden iframe in Firefox and IE/Edge, the
// bounding box height is 0, so don't cache it (#5620).
if (cacheKey && bBox.height > 0) {
// Rotate (#4681)
while (cacheKeys.length > 250) {
delete cache[cacheKeys.shift()];
}
if (!cache[cacheKey]) {
cacheKeys.push(cacheKey);
}
cache[cacheKey] = bBox;
}
}
return bBox;
},
/**
* Show the element
*/
show: function(inherit) {
return this.attr({
visibility: inherit ? 'inherit' : 'visible'
});
},
/**
* Hide the element
*/
hide: function() {
return this.attr({
visibility: 'hidden'
});
},
fadeOut: function(duration) {
var elemWrapper = this;
elemWrapper.animate({
opacity: 0
}, {
duration: duration || 150,
complete: function() {
elemWrapper.attr({
y: -9999
}); // #3088, assuming we're only using this for tooltips
}
});
},
/**
* Add the element
* @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
* to append the element to the renderer.box.
*/
add: function(parent) {
var renderer = this.renderer,
element = this.element,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// Mark as added
this.added = true;
// If we're adding to renderer root, or other elements in the group
// have a z index, we need to handle it
if (!parent || parent.handleZ || this.zIndex) {
inserted = this.zIndexSetter();
}
// If zIndex is not handled, append at the end
if (!inserted) {
(parent ? parent.element : renderer.box).appendChild(element);
}
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
},
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function(element) {
var parentNode = element.parentNode;
if (parentNode) {
parentNode.removeChild(element);
}
},
/**
* Destroy the element and element wrapper
*/
destroy: function() {
var wrapper = this,
element = wrapper.element || {},
parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
grandParent,
key,
i;
// remove events
element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
stop(wrapper); // stop running animations
if (wrapper.clipPath) {
wrapper.clipPath = wrapper.clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if (wrapper.stops) {
for (i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper.safeRemoveChild(element);
// In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697).
while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) {
grandParent = parentToClean.parentGroup;
wrapper.safeRemoveChild(parentToClean.div);
delete parentToClean.div;
parentToClean = grandParent;
}
// remove from alignObjects
if (wrapper.alignTo) {
erase(wrapper.renderer.alignedObjects, wrapper);
}
for (key in wrapper) {
delete wrapper[key];
}
return null;
},
xGetter: function(key) {
if (this.element.nodeName === 'circle') {
if (key === 'x') {
key = 'cx';
} else if (key === 'y') {
key = 'cy';
}
}
return this._defaultGetter(key);
},
/**
* Get the current value of an attribute or pseudo attribute, used mainly
* for animation.
*/
_defaultGetter: function(key) {
var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
},
dSetter: function(value, key, element) {
if (value && value.join) { // join path
value = value.join(' ');
}
if (/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
element.setAttribute(key, value);
this[key] = value;
},
alignSetter: function(value) {
var convert = {
left: 'start',
center: 'middle',
right: 'end'
};
this.element.setAttribute('text-anchor', convert[value]);
},
opacitySetter: function(value, key, element) {
this[key] = value;
element.setAttribute(key, value);
},
titleSetter: function(value) {
var titleNode = this.element.getElementsByTagName('title')[0];
if (!titleNode) {
titleNode = doc.createElementNS(this.SVG_NS, 'title');
this.element.appendChild(titleNode);
}
// Remove text content if it exists
if (titleNode.firstChild) {
titleNode.removeChild(titleNode.firstChild);
}
titleNode.appendChild(
doc.createTextNode(
(String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895
)
);
},
textSetter: function(value) {
if (value !== this.textStr) {
// Delete bBox memo when the text changes
delete this.bBox;
this.textStr = value;
if (this.added) {
this.renderer.buildText(this);
}
}
},
fillSetter: function(value, key, element) {
if (typeof value === 'string') {
element.setAttribute(key, value);
} else if (value) {
this.colorGradient(value, key, element);
}
},
visibilitySetter: function(value, key, element) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909)
if (value === 'inherit') {
element.removeAttribute(key);
} else {
element.setAttribute(key, value);
}
},
zIndexSetter: function(value, key) {
var renderer = this.renderer,
parentGroup = this.parentGroup,
parentWrapper = parentGroup || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
otherElement,
otherZIndex,
element = this.element,
inserted,
run = this.added,
i;
if (defined(value)) {
element.zIndex = value; // So we can read it for other elements in the group
value = +value;
if (this[key] === value) { // Only update when needed (#3865)
run = false;
}
this[key] = value;
}
// Insert according to this and other elements' zIndex. Before .add() is called,
// nothing is done. Then on add, or by later calls to zIndexSetter, the node
// is placed on the right place in the DOM.
if (run) {
value = this.zIndex;
if (value && parentGroup) {
parentGroup.handleZ = true;
}
childNodes = parentNode.childNodes;
for (i = 0; i < childNodes.length && !inserted; i++) {
otherElement = childNodes[i];
otherZIndex = otherElement.zIndex;
if (otherElement !== element && (
// Insert before the first element with a higher zIndex
pInt(otherZIndex) > value ||
// If no zIndex given, insert before the first element with a zIndex
(!defined(value) && defined(otherZIndex)) ||
// Negative zIndex versus no zIndex:
// On all levels except the highest. If the parent is <svg>,
// then we don't want to put items before <desc> or <defs>
(value < 0 && !defined(otherZIndex) && parentNode !== renderer.box)
)) {
parentNode.insertBefore(element, otherElement);
inserted = true;
}
}
if (!inserted) {
parentNode.appendChild(element);
}
}
return inserted;
},
_defaultSetter: function(value, key, element) {
element.setAttribute(key, value);
}
};
// Some shared setters and getters
SVGElement.prototype.yGetter = SVGElement.prototype.xGetter;
SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter =
SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter =
SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function(value, key) {
this[key] = value;
this.doTransform = true;
};
/**
* The default SVG renderer
*/
SVGRenderer = H.SVGRenderer = function() {
this.init.apply(this, arguments);
};
SVGRenderer.prototype = {
Element: SVGElement,
SVG_NS: SVG_NS,
/**
* Initialize the SVGRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
* @param {Boolean} forExport
*/
init: function(container, width, height, style, forExport, allowHTML) {
var renderer = this,
boxWrapper,
element,
desc;
boxWrapper = renderer.createElement('svg')
.attr({
'version': '1.1',
'class': 'highcharts-root'
});
element = boxWrapper.element;
container.appendChild(element);
// For browsers other than IE, add the namespace attribute (#1978)
if (container.innerHTML.indexOf('xmlns') === -1) {
attr(element, 'xmlns', this.SVG_NS);
}
// object properties
renderer.isSVG = true;
renderer.box = element;
renderer.boxWrapper = boxWrapper;
renderer.alignedObjects = [];
// Page url used for internal references. #24, #672, #1070
renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
win.location.href
.replace(/#.*?$/, '') // remove the hash
.replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
.replace(/ /g, '%20') : // replace spaces (needed for Safari only)
'';
// Add description
desc = this.createElement('desc').add();
desc.element.appendChild(doc.createTextNode('Created with Highmaps 5.0.1'));
renderer.defs = this.createElement('defs').add();
renderer.allowHTML = allowHTML;
renderer.forExport = forExport;
renderer.gradients = {}; // Object where gradient SvgElements are stored
renderer.cache = {}; // Cache for numerical bounding boxes
renderer.cacheKeys = [];
renderer.imgCount = 0;
renderer.setSize(width, height, false);
// Issue 110 workaround:
// In Firefox, if a div is positioned by percentage, its pixel position may land
// between pixels. The container itself doesn't display this, but an SVG element
// inside this container will be drawn at subpixel precision. In order to draw
// sharp lines, this must be compensated for. This doesn't seem to work inside
// iframes though (like in jsFiddle).
var subPixelFix, rect;
if (isFirefox && container.getBoundingClientRect) {
renderer.subPixelFix = subPixelFix = function() {
css(container, {
left: 0,
top: 0
});
rect = container.getBoundingClientRect();
css(container, {
left: (Math.ceil(rect.left) - rect.left) + 'px',
top: (Math.ceil(rect.top) - rect.top) + 'px'
});
};
// run the fix now
subPixelFix();
// run it on resize
addEvent(win, 'resize', subPixelFix);
}
},
/**
* General method for adding a definition. Can be used for gradients, fills, filters etc.
*
* @return SVGElement The inserted node
*/
definition: function(def) {
var ren = this;
function recurse(config, parent) {
var ret;
each(splat(config), function(item) {
var node = ren.createElement(item.tagName),
key,
attr = {};
// Set attributes
for (key in item) {
if (key !== 'tagName' && key !== 'children' && key !== 'textContent') {
attr[key] = item[key];
}
}
node.attr(attr);
// Add to the tree
node.add(parent || ren.defs);
// Add text content
if (item.textContent) {
node.element.appendChild(doc.createTextNode(item.textContent));
}
// Recurse
recurse(item.children || [], node);
ret = node;
});
// Return last node added (on top level it's the only one)
return ret;
}
return recurse(def);
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none. #608.
*/
isHidden: function() {
return !this.boxWrapper.getBBox().width;
},
/**
* Destroys the renderer and its allocated members.
*/
destroy: function() {
var renderer = this,
rendererDefs = renderer.defs;
renderer.box = null;
renderer.boxWrapper = renderer.boxWrapper.destroy();
// Call destroy on all gradient elements
destroyObjectProperties(renderer.gradients || {});
renderer.gradients = null;
// Defs are null in VMLRenderer
// Otherwise, destroy them here.
if (rendererDefs) {
renderer.defs = rendererDefs.destroy();
}
// Remove sub pixel fix handler
// We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
// See issue #982
if (renderer.subPixelFix) {
removeEvent(win, 'resize', renderer.subPixelFix);
}
renderer.alignedObjects = null;
return null;
},
/**
* Create a wrapper for an SVG element
* @param {Object} nodeName
*/
createElement: function(nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
},
/**
* Dummy function for plugins
*/
draw: noop,
/**
* Get converted radial gradient attributes
*/
getRadialAttr: function(radialReference, gradAttr) {
return {
cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
r: gradAttr.r * radialReference[2]
};
},
/**
* Parse a simple HTML string into SVG tspans
*
* @param {Object} textNode The parent text SVG node
*/
buildText: function(wrapper) {
var textNode = wrapper.element,
renderer = this,
forExport = renderer.forExport,
textStr = pick(wrapper.textStr, '').toString(),
hasMarkup = textStr.indexOf('<') !== -1,
lines,
childNodes = textNode.childNodes,
clsRegex,
styleRegex,
hrefRegex,
wasTooLong,
parentX = attr(textNode, 'x'),
textStyles = wrapper.styles,
width = wrapper.textWidth,
textLineHeight = textStyles && textStyles.lineHeight,
textShadow = textStyles && textStyles.textShadow,
ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
i = childNodes.length,
tempParent = width && !wrapper.added && this.box,
getLineHeight = function(tspan) {
var fontSizeStyle;
return textLineHeight ?
pInt(textLineHeight) :
renderer.fontMetrics(
fontSizeStyle,
tspan
).h;
},
unescapeAngleBrackets = function(inputStr) {
return inputStr.replace(/</g, '<').replace(/>/g, '>');
};
/// remove old text
while (i--) {
textNode.removeChild(childNodes[i]);
}
// Skip tspans, add text directly to text node. The forceTSpan is a hook
// used in text outline hack.
if (!hasMarkup && !textShadow && !ellipsis && !width && textStr.indexOf(' ') === -1) {
textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr)));
// Complex strings, add more logic
} else {
clsRegex = /<.*class="([^"]+)".*>/;
styleRegex = /<.*style="([^"]+)".*>/;
hrefRegex = /<.*href="(http[^"]+)".*>/;
if (tempParent) {
tempParent.appendChild(textNode); // attach it to the DOM to read offset width
}
if (hasMarkup) {
lines = textStr
.replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
.replace(/<(i|em)>/g, '<span style="font-style:italic">')
.replace(/<a/g, '<span')
.replace(/<\/(b|strong|i|em|a)>/g, '</span>')
.split(/<br.*?>/g);
} else {
lines = [textStr];
}
// Trim empty lines (#5261)
lines = grep(lines, function(line) {
return line !== '';
});
// build the lines
each(lines, function buildTextLines(line, lineNo) {
var spans,
spanNo = 0;
line = line
.replace(/^\s+|\s+$/g, '') // Trim to prevent useless/costly process on the spaces (#5258)
.replace(/<span/g, '|||<span')
.replace(/<\/span>/g, '</span>|||');
spans = line.split('|||');
each(spans, function buildTextSpans(span) {
if (span !== '' || spans.length === 1) {
var attributes = {},
tspan = doc.createElementNS(renderer.SVG_NS, 'tspan'),
spanCls,
spanStyle; // #390
if (clsRegex.test(span)) {
spanCls = span.match(clsRegex)[1];
attr(tspan, 'class', spanCls);
}
if (styleRegex.test(span)) {
spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
attr(tspan, 'style', spanStyle);
}
if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
css(tspan, {
cursor: 'pointer'
});
}
span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' ');
// Nested tags aren't supported, and cause crash in Safari (#1596)
if (span !== ' ') {
// add the text node
tspan.appendChild(doc.createTextNode(span));
if (!spanNo) { // first span in a line, align it to the left
if (lineNo && parentX !== null) {
attributes.x = parentX;
}
} else {
attributes.dx = 0; // #16
}
// add attributes
attr(tspan, attributes);
// Append it
textNode.appendChild(tspan);
// first span on subsequent line, add the line height
if (!spanNo && lineNo) {
// allow getting the right offset height in exporting in IE
if (!svg && forExport) {
css(tspan, {
display: 'block'
});
}
// Set the line height based on the font size of either
// the text element or the tspan element
attr(
tspan,
'dy',
getLineHeight(tspan)
);
}
/*if (width) {
renderer.breakText(wrapper, width);
}*/
// Check width and apply soft breaks or ellipsis
if (width) {
var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
noWrap = textStyles.whiteSpace === 'nowrap',
hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && !noWrap),
tooLong,
actualWidth,
rest = [],
dy = getLineHeight(tspan),
rotation = wrapper.rotation,
wordStr = span, // for ellipsis
cursor = wordStr.length, // binary search cursor
bBox;
while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) {
wrapper.rotation = 0; // discard rotation when computing box
bBox = wrapper.getBBox(true);
actualWidth = bBox.width;
// Old IE cannot measure the actualWidth for SVG elements (#2314)
if (!svg && renderer.forExport) {
actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
}
tooLong = actualWidth > width;
// For ellipsis, do a binary search for the correct string length
if (wasTooLong === undefined) {
wasTooLong = tooLong; // First time
}
if (ellipsis && wasTooLong) {
cursor /= 2;
if (wordStr === '' || (!tooLong && cursor < 0.5)) {
words = []; // All ok, break out
} else {
wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * Math.ceil(cursor));
words = [wordStr + (width > 3 ? '\u2026' : '')];
tspan.removeChild(tspan.firstChild);
}
// Looping down, this is the first word sequence that is not too long,
// so we can move on to build the next line.
} else if (!tooLong || words.length === 1) {
words = rest;
rest = [];
if (words.length && !noWrap) {
tspan = doc.createElementNS(SVG_NS, 'tspan');
attr(tspan, {
dy: dy,
x: parentX
});
if (spanStyle) { // #390
attr(tspan, 'style', spanStyle);
}
textNode.appendChild(tspan);
}
if (actualWidth > width) { // a single word is pressing it out
width = actualWidth;
}
} else { // append to existing line tspan
tspan.removeChild(tspan.firstChild);
rest.unshift(words.pop());
}
if (words.length) {
tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
}
}
wrapper.rotation = rotation;
}
spanNo++;
}
}
});
});
if (wasTooLong) {
wrapper.attr('title', wrapper.textStr);
}
if (tempParent) {
tempParent.removeChild(textNode); // attach it to the DOM to read offset width
}
// Apply the text shadow
if (textShadow && wrapper.applyTextShadow) {
wrapper.applyTextShadow(textShadow);
}
}
},
/*
breakText: function (wrapper, width) {
var bBox = wrapper.getBBox(),
node = wrapper.element,
textLength = node.textContent.length,
pos = Math.round(width * textLength / bBox.width), // try this position first, based on average character width
increment = 0,
finalPos;
if (bBox.width > width) {
while (finalPos === undefined) {
textLength = node.getSubStringLength(0, pos);
if (textLength <= width) {
if (increment === -1) {
finalPos = pos;
} else {
increment = 1;
}
} else {
if (increment === 1) {
finalPos = pos - 1;
} else {
increment = -1;
}
}
pos += increment;
}
}
console.log('width', width, 'stringWidth', node.getSubStringLength(0, finalPos))
},
*/
/**
* Returns white for dark colors and black for bright colors
*/
getContrast: function(rgba) {
rgba = color(rgba).rgba;
return rgba[0] + rgba[1] + rgba[2] > 2 * 255 ? '#000000' : '#FFFFFF';
},
/**
* Create a button with preset states
* @param {String} text
* @param {Number} x
* @param {Number} y
* @param {Function} callback
* @param {Object} normalState
* @param {Object} hoverState
* @param {Object} pressedState
*/
button: function(text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
curState = 0;
// Default, non-stylable attributes
label.attr(merge({
'padding': 8,
'r': 2
}, normalState));
// Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function() {
if (curState !== 3) {
label.setState(1);
}
});
addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function() {
if (curState !== 3) {
label.setState(curState);
}
});
label.setState = function(state) {
// Hover state is temporary, don't record it
if (state !== 1) {
label.state = curState = state;
}
// Update visuals
label.removeClass(/highcharts-button-(normal|hover|pressed|disabled)/)
.addClass('highcharts-button-' + ['normal', 'hover', 'pressed', 'disabled'][state || 0]);
};
return label
.on('click', function(e) {
if (curState !== 3) {
callback.call(label, e);
}
});
},
/**
* Make a straight line crisper by not spilling out to neighbour pixels
* @param {Array} points
* @param {Number} width
*/
crispLine: function(points, width) {
// points format: ['M', 0, 0, 'L', 100, 0]
// normalize to a crisp line
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave the same.
points[1] = points[4] = Math.round(points[1]) - (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = Math.round(points[2]) + (width % 2 / 2);
}
return points;
},
/**
* Draw a path
* @param {Array} path An SVG path in array form
*/
path: function(path) {
var attribs = {
};
if (isArray(path)) {
attribs.d = path;
} else if (isObject(path)) { // attributes
extend(attribs, path);
}
return this.createElement('path').attr(attribs);
},
/**
* Draw and return an SVG circle
* @param {Number} x The x position
* @param {Number} y The y position
* @param {Number} r The radius
*/
circle: function(x, y, r) {
var attribs = isObject(x) ? x : {
x: x,
y: y,
r: r
},
wrapper = this.createElement('circle');
// Setting x or y translates to cx and cy
wrapper.xSetter = wrapper.ySetter = function(value, key, element) {
element.setAttribute('c' + key, value);
};
return wrapper.attr(attribs);
},
/**
* Draw and return an arc
* @param {Number} x X position
* @param {Number} y Y position
* @param {Number} r Radius
* @param {Number} innerR Inner radius like used in donut charts
* @param {Number} start Starting angle
* @param {Number} end Ending angle
*/
arc: function(x, y, r, innerR, start, end) {
var arc;
if (isObject(x)) {
y = x.y;
r = x.r;
innerR = x.innerR;
start = x.start;
end = x.end;
x = x.x;
}
// Arcs are defined as symbols for the ability to set
// attributes in attr and animate
arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
innerR: innerR || 0,
start: start || 0,
end: end || 0
});
arc.r = r; // #959
return arc;
},
/**
* Draw and return a rectangle
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Number} width
* @param {Number} height
* @param {Number} r Border corner radius
* @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
*/
rect: function(x, y, width, height, r, strokeWidth) {
r = isObject(x) ? x.r : r;
var wrapper = this.createElement('rect'),
attribs = isObject(x) ? x : x === undefined ? {} : {
x: x,
y: y,
width: Math.max(width, 0),
height: Math.max(height, 0)
};
if (r) {
attribs.r = r;
}
wrapper.rSetter = function(value, key, element) {
attr(element, {
rx: value,
ry: value
});
};
return wrapper.attr(attribs);
},
/**
* Resize the box and re-align all aligned elements
* @param {Object} width
* @param {Object} height
* @param {Boolean} animate
*
*/
setSize: function(width, height, animate) {
var renderer = this,
alignedObjects = renderer.alignedObjects,
i = alignedObjects.length;
renderer.width = width;
renderer.height = height;
renderer.boxWrapper.animate({
width: width,
height: height
}, {
step: function() {
this.attr({
viewBox: '0 0 ' + this.attr('width') + ' ' + this.attr('height')
});
},
duration: pick(animate, true) ? undefined : 0
});
while (i--) {
alignedObjects[i].align();
}
},
/**
* Create a group
* @param {String} name The group will be given a class name of 'highcharts-{name}'.
* This can be used for styling and scripting.
*/
g: function(name) {
var elem = this.createElement('g');
return name ? elem.attr({
'class': 'highcharts-' + name
}) : elem;
},
/**
* Display an image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function(src, x, y, width, height) {
var attribs = {
preserveAspectRatio: 'none'
},
elemWrapper;
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// set the href in the xlink namespace
if (elemWrapper.element.setAttributeNS) {
elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
'href', src);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under, requries regex shim to fix later
elemWrapper.element.setAttribute('hc-svg-href', src);
}
return elemWrapper;
},
/**
* Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
*
* @param {Object} symbol
* @param {Object} x
* @param {Object} y
* @param {Object} radius
* @param {Object} options
*/
symbol: function(symbol, x, y, width, height, options) {
var ren = this,
obj,
// get the symbol definition function
symbolFn = this.symbols[symbol],
// check if there's a path defined for this symbol
path = defined(x) && symbolFn && symbolFn(
Math.round(x),
Math.round(y),
width,
height,
options
),
imageRegex = /^url\((.*?)\)$/,
imageSrc,
centerImage;
if (symbolFn) {
obj = this.path(path);
// expando properties for use in animate and attr
extend(obj, {
symbolName: symbol,
x: x,
y: y,
width: width,
height: height
});
if (options) {
extend(obj, options);
}
// image symbols
} else if (imageRegex.test(symbol)) {
imageSrc = symbol.match(imageRegex)[1];
// Create the image synchronously, add attribs async
obj = this.image(imageSrc);
// The image width is not always the same as the symbol width. The
// image may be centered within the symbol, as is the case when
// image shapes are used as label backgrounds, for example in flags.
obj.imgwidth = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].width,
options && options.width
);
obj.imgheight = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].height,
options && options.height
);
/**
* Set the size and position
*/
centerImage = function() {
obj.attr({
width: obj.width,
height: obj.height
});
};
/**
* Width and height setters that take both the image's physical size
* and the label size into consideration, and translates the image
* to center within the label.
*/
each(['width', 'height'], function(key) {
obj[key + 'Setter'] = function(value, key) {
var attribs = {},
imgSize = this['img' + key],
trans = key === 'width' ? 'translateX' : 'translateY';
this[key] = value;
if (defined(imgSize)) {
if (this.element) {
this.element.setAttribute(key, imgSize);
}
if (!this.alignByTranslate) {
attribs[trans] = ((this[key] || 0) - imgSize) / 2;
this.attr(attribs);
}
}
};
});
if (defined(x)) {
obj.attr({
x: x,
y: y
});
}
obj.isImg = true;
if (defined(obj.imgwidth) && defined(obj.imgheight)) {
centerImage();
} else {
// Initialize image to be 0 size so export will still function if there's no cached sizes.
obj.attr({
width: 0,
height: 0
});
// Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
// the created element must be assigned to a variable in order to load (#292).
createElement('img', {
onload: function() {
var chart = charts[ren.chartIndex];
// Special case for SVGs on IE11, the width is not accessible until the image is
// part of the DOM (#2854).
if (this.width === 0) {
css(this, {
position: 'absolute',
top: '-999em'
});
doc.body.appendChild(this);
}
// Center the image
symbolSizes[imageSrc] = { // Cache for next
width: this.width,
height: this.height
};
obj.imgwidth = this.width;
obj.imgheight = this.height;
if (obj.element) {
centerImage();
}
// Clean up after #2854 workaround.
if (this.parentNode) {
this.parentNode.removeChild(this);
}
// Fire the load event when all external images are loaded
ren.imgCount--;
if (!ren.imgCount && chart && chart.onload) {
chart.onload();
}
},
src: imageSrc
});
this.imgCount++;
}
}
return obj;
},
/**
* An extendable collection of functions for defining symbol paths.
*/
symbols: {
'circle': function(x, y, w, h) {
var cpw = 0.166 * w;
return [
'M', x + w / 2, y,
'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
'Z'
];
},
'square': function(x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w, y + h,
x, y + h,
'Z'
];
},
'triangle': function(x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h,
x, y + h,
'Z'
];
},
'triangle-down': function(x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w / 2, y + h,
'Z'
];
},
'diamond': function(x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2,
'Z'
];
},
'arc': function(x, y, w, h, options) {
var start = options.start,
radius = options.r || w || h,
end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
innerRadius = options.innerR,
open = options.open,
cosStart = Math.cos(start),
sinStart = Math.sin(start),
cosEnd = Math.cos(end),
sinEnd = Math.sin(end),
longArc = options.end - start < Math.PI ? 0 : 1;
return [
'M',
x + radius * cosStart,
y + radius * sinStart,
'A', // arcTo
radius, // x radius
radius, // y radius
0, // slanting
longArc, // long or short arc
1, // clockwise
x + radius * cosEnd,
y + radius * sinEnd,
open ? 'M' : 'L',
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A', // arcTo
innerRadius, // x radius
innerRadius, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
x + innerRadius * cosStart,
y + innerRadius * sinStart,
open ? '' : 'Z' // close
];
},
/**
* Callout shape used for default tooltips, also used for rounded rectangles in VML
*/
callout: function(x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = Math.min((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-right corner
];
if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
} else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
path.splice(33, 3,
'L', x, anchorY + halfDistance,
x - arrowLength, anchorY,
x, anchorY - halfDistance,
x, y + r
);
} else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
path.splice(23, 3,
'L', anchorX + halfDistance, y + h,
anchorX, y + h + arrowLength,
anchorX - halfDistance, y + h,
x + r, y + h
);
} else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
path.splice(3, 3,
'L', anchorX - halfDistance, y,
anchorX, y - arrowLength,
anchorX + halfDistance, y,
w - r, y
);
}
return path;
}
},
/**
* Define a clipping rectangle
* @param {String} id
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function(x, y, width, height) {
var wrapper,
id = 'highcharts-' + H.idCounter++,
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
wrapper.count = 0;
return wrapper;
},
/**
* Add text to the SVG object
* @param {String} str
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Boolean} useHTML Use HTML to render the text
*/
text: function(str, x, y, useHTML) {
// declare variables
var renderer = this,
fakeSVG = !svg && renderer.forExport,
wrapper,
attribs = {};
if (useHTML && (renderer.allowHTML || !renderer.forExport)) {
return renderer.html(str, x, y);
}
attribs.x = Math.round(x || 0); // X is always needed for line-wrap logic
if (y) {
attribs.y = Math.round(y);
}
if (str || str === 0) {
attribs.text = str;
}
wrapper = renderer.createElement('text')
.attr(attribs);
// Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
if (fakeSVG) {
wrapper.css({
position: 'absolute'
});
}
if (!useHTML) {
wrapper.xSetter = function(value, key, element) {
var tspans = element.getElementsByTagName('tspan'),
tspan,
parentVal = element.getAttribute(key),
i;
for (i = 0; i < tspans.length; i++) {
tspan = tspans[i];
// If the x values are equal, the tspan represents a linebreak
if (tspan.getAttribute(key) === parentVal) {
tspan.setAttribute(key, value);
}
}
element.setAttribute(key, value);
};
}
return wrapper;
},
/**
* Utility to return the baseline offset and total line height from the font size
*/
fontMetrics: function(fontSize, elem) { // eslint-disable-line no-unused-vars
var lineHeight,
baseline;
fontSize = elem && SVGElement.prototype.getStyle.call(elem, 'font-size');
fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12;
// Empirical values found by comparing font size and bounding box height.
// Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
lineHeight = fontSize < 24 ? fontSize + 3 : Math.round(fontSize * 1.2);
baseline = Math.round(lineHeight * 0.8);
return {
h: lineHeight,
b: baseline,
f: fontSize
};
},
/**
* Correct X and Y positioning of a label for rotation (#1764)
*/
rotCorr: function(baseline, rotation, alterY) {
var y = baseline;
if (rotation && alterY) {
y = Math.max(y * Math.cos(rotation * deg2rad), 4);
}
return {
x: (-baseline / 3) * Math.sin(rotation * deg2rad),
y: y
};
},
/**
* Add a label, a text item that can hold a colored or gradient background
* as well as a border and shadow.
* @param {string} str
* @param {Number} x
* @param {Number} y
* @param {String} shape
* @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
* coordinates it should be pinned to
* @param {Number} anchorY
* @param {Boolean} baseline Whether to position the label relative to the text baseline,
* like renderer.text, or to the upper border of the rectangle.
* @param {String} className Class name for the group
*/
label: function(str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
var renderer = this,
wrapper = renderer.g(className !== 'button' && 'label'),
text = wrapper.text = renderer.text('', 0, 0, useHTML)
.attr({
zIndex: 1
}),
box,
bBox,
alignFactor = 0,
padding = 3,
paddingLeft = 0,
width,
height,
wrapperX,
wrapperY,
textAlign,
deferredAttr = {},
strokeWidth,
baselineOffset,
hasBGImage = /^url\((.*?)\)$/.test(shape),
needsBox = hasBGImage,
getCrispAdjust,
updateBoxSize,
updateTextPadding,
boxAttr;
if (className) {
wrapper.addClass('highcharts-' + className);
}
needsBox = true; // for styling
getCrispAdjust = function() {
return box.strokeWidth() % 2 / 2;
};
/**
* This function runs after the label is added to the DOM (when the bounding box is
* available), and after the text of the label is updated to detect the new bounding
* box and reflect it in the border box.
*/
updateBoxSize = function() {
var style = text.element.style,
crispAdjust,
attribs = {};
bBox = (width === undefined || height === undefined || textAlign) && defined(text.textStr) &&
text.getBBox(); //#3295 && 3514 box failure when string equals 0
wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
wrapper.height = (height || bBox.height || 0) + 2 * padding;
// Update the label-scoped y offset
baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b;
if (needsBox) {
// Create the border box if it is not already present
if (!box) {
wrapper.box = box = renderer.symbols[shape] || hasBGImage ? // Symbol definition exists (#5324)
renderer.symbol(shape) :
renderer.rect();
box.addClass(
(className === 'button' ? '' : 'highcharts-label-box') + // Don't use label className for buttons
(className ? ' highcharts-' + className + '-box' : '')
);
box.add(wrapper);
crispAdjust = getCrispAdjust();
attribs.x = crispAdjust;
attribs.y = (baseline ? -baselineOffset : 0) + crispAdjust;
}
// Apply the box attributes
attribs.width = Math.round(wrapper.width);
attribs.height = Math.round(wrapper.height);
box.attr(extend(attribs, deferredAttr));
deferredAttr = {};
}
};
/**
* This function runs after setting text or padding, but only if padding is changed
*/
updateTextPadding = function() {
var textX = paddingLeft + padding,
textY;
// determin y based on the baseline
textY = baseline ? 0 : baselineOffset;
// compensate for alignment
if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) {
textX += {
center: 0.5,
right: 1
}[textAlign] * (width - bBox.width);
}
// update if anything changed
if (textX !== text.x || textY !== text.y) {
text.attr('x', textX);
if (textY !== undefined) {
text.attr('y', textY);
}
}
// record current values
text.x = textX;
text.y = textY;
};
/**
* Set a box attribute, or defer it if the box is not yet created
* @param {Object} key
* @param {Object} value
*/
boxAttr = function(key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
};
/**
* After the text element is added, get the desired size of the border box
* and add it before the text in the DOM.
*/
wrapper.onAdd = function() {
text.add(wrapper);
wrapper.attr({
text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value
x: x,
y: y
});
if (box && defined(anchorX)) {
wrapper.attr({
anchorX: anchorX,
anchorY: anchorY
});
}
};
/*
* Add specific attribute setters.
*/
// only change local variables
wrapper.widthSetter = function(value) {
width = value;
};
wrapper.heightSetter = function(value) {
height = value;
};
wrapper['text-alignSetter'] = function(value) {
textAlign = value;
};
wrapper.paddingSetter = function(value) {
if (defined(value) && value !== padding) {
padding = wrapper.padding = value;
updateTextPadding();
}
};
wrapper.paddingLeftSetter = function(value) {
if (defined(value) && value !== paddingLeft) {
paddingLeft = value;
updateTextPadding();
}
};
// change local variable and prevent setting attribute on the group
wrapper.alignSetter = function(value) {
value = {
left: 0,
center: 0.5,
right: 1
}[value];
if (value !== alignFactor) {
alignFactor = value;
if (bBox) { // Bounding box exists, means we're dynamically changing
wrapper.attr({
x: wrapperX
}); // #5134
}
}
};
// apply these to the box and the text alike
wrapper.textSetter = function(value) {
if (value !== undefined) {
text.textSetter(value);
}
updateBoxSize();
updateTextPadding();
};
// apply these to the box but not to the text
wrapper['stroke-widthSetter'] = function(value, key) {
if (value) {
needsBox = true;
}
strokeWidth = this['stroke-width'] = value;
boxAttr(key, value);
};
wrapper.rSetter = function(value, key) {
boxAttr(key, value);
};
wrapper.anchorXSetter = function(value, key) {
anchorX = value;
boxAttr(key, Math.round(value) - getCrispAdjust() - wrapperX);
};
wrapper.anchorYSetter = function(value, key) {
anchorY = value;
boxAttr(key, value - wrapperY);
};
// rename attributes
wrapper.xSetter = function(value) {
wrapper.x = value; // for animation getter
if (alignFactor) {
value -= alignFactor * ((width || bBox.width) + 2 * padding);
}
wrapperX = Math.round(value);
wrapper.attr('translateX', wrapperX);
};
wrapper.ySetter = function(value) {
wrapperY = wrapper.y = Math.round(value);
wrapper.attr('translateY', wrapperY);
};
// Redirect certain methods to either the box or the text
var baseCss = wrapper.css;
return extend(wrapper, {
/**
* Pick up some properties and apply them to the text instead of the wrapper
*/
css: function(styles) {
if (styles) {
var textStyles = {};
styles = merge(styles); // create a copy to avoid altering the original object (#537)
each(wrapper.textProps, function(prop) {
if (styles[prop] !== undefined) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
}
return baseCss.call(wrapper, styles);
},
/**
* Return the bounding box of the box, not the group
*/
getBBox: function() {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
},
/**
* Destroy and release memory.
*/
destroy: function() {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
}
});
}
}; // end SVGRenderer
// general renderer
H.Renderer = SVGRenderer;
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var attr = H.attr,
createElement = H.createElement,
css = H.css,
defined = H.defined,
each = H.each,
extend = H.extend,
isFirefox = H.isFirefox,
isMS = H.isMS,
isWebKit = H.isWebKit,
pInt = H.pInt,
SVGElement = H.SVGElement,
SVGRenderer = H.SVGRenderer,
win = H.win,
wrap = H.wrap;
// extend SvgElement for useHTML option
extend(SVGElement.prototype, {
/**
* Apply CSS to HTML elements. This is used in text within SVG rendering and
* by the VML renderer
*/
htmlCss: function(styles) {
var wrapper = this,
element = wrapper.element,
textWidth = styles && element.tagName === 'SPAN' && styles.width;
if (textWidth) {
delete styles.width;
wrapper.textWidth = textWidth;
wrapper.updateTransform();
}
if (styles && styles.textOverflow === 'ellipsis') {
styles.whiteSpace = 'nowrap';
styles.overflow = 'hidden';
}
wrapper.styles = extend(wrapper.styles, styles);
css(wrapper.element, styles);
return wrapper;
},
/**
* VML and useHTML method for calculating the bounding box based on offsets
* @param {Boolean} refresh Whether to force a fresh value from the DOM or to
* use the cached value
*
* @return {Object} A hash containing values for x, y, width and height
*/
htmlGetBBox: function() {
var wrapper = this,
element = wrapper.element;
// faking getBBox in exported SVG in legacy IE
// faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
if (element.nodeName === 'text') {
element.style.position = 'absolute';
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
},
/**
* VML override private method to update elements based on internal
* properties based on SVG transform
*/
htmlUpdateTransform: function() {
// aligning non added elements is expensive
if (!this.added) {
this.alignOnAdd = true;
return;
}
var wrapper = this,
renderer = wrapper.renderer,
elem = wrapper.element,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
x = wrapper.x || 0,
y = wrapper.y || 0,
align = wrapper.textAlign || 'left',
alignCorrection = {
left: 0,
center: 0.5,
right: 1
}[align],
styles = wrapper.styles;
// apply translate
css(elem, {
marginLeft: translateX,
marginTop: translateY
});
// apply inversion
if (wrapper.inverted) { // wrapper is a group
each(elem.childNodes, function(child) {
renderer.invertChild(child, elem);
});
}
if (elem.tagName === 'SPAN') {
var rotation = wrapper.rotation,
baseline,
textWidth = pInt(wrapper.textWidth),
whiteSpace = styles && styles.whiteSpace,
currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(',');
if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
baseline = renderer.fontMetrics(elem.style.fontSize).b;
// Renderer specific handling of span rotation
if (defined(rotation)) {
wrapper.setSpanRotation(rotation, alignCorrection, baseline);
}
// Reset multiline/ellipsis in order to read width (#4928, #5417)
css(elem, {
width: '',
whiteSpace: whiteSpace || 'nowrap'
});
// Update textWidth
if (elem.offsetWidth > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
css(elem, {
width: textWidth + 'px',
display: 'block',
whiteSpace: whiteSpace || 'normal' // #3331
});
}
wrapper.getSpanCorrection(elem.offsetWidth, baseline, alignCorrection, rotation, align);
}
// apply position with correction
css(elem, {
left: (x + (wrapper.xCorr || 0)) + 'px',
top: (y + (wrapper.yCorr || 0)) + 'px'
});
// force reflow in webkit to apply the left and top on useHTML element (#1249)
if (isWebKit) {
baseline = elem.offsetHeight; // assigned to baseline for lint purpose
}
// record current text transform
wrapper.cTT = currentTextTransform;
}
},
/**
* Set the rotation of an individual HTML span
*/
setSpanRotation: function(rotation, alignCorrection, baseline) {
var rotationStyle = {},
cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : win.opera ? '-o-transform' : '';
rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px';
css(this.element, rotationStyle);
},
/**
* Get the correction in X and Y positioning as the element is rotated.
*/
getSpanCorrection: function(width, baseline, alignCorrection) {
this.xCorr = -width * alignCorrection;
this.yCorr = -baseline;
}
});
// Extend SvgRenderer for useHTML option.
extend(SVGRenderer.prototype, {
/**
* Create HTML text node. This is used by the VML renderer as well as the SVG
* renderer through the useHTML option.
*
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
html: function(str, x, y) {
var wrapper = this.createElement('span'),
element = wrapper.element,
renderer = wrapper.renderer,
isSVG = renderer.isSVG,
addSetters = function(element, style) {
// These properties are set as attributes on the SVG group, and as
// identical CSS properties on the div. (#3542)
each(['opacity', 'visibility'], function(prop) {
wrap(element, prop + 'Setter', function(proceed, value, key, elem) {
proceed.call(this, value, key, elem);
style[key] = value;
});
});
};
// Text setter
wrapper.textSetter = function(value) {
if (value !== element.innerHTML) {
delete this.bBox;
}
element.innerHTML = this.textStr = value;
wrapper.htmlUpdateTransform();
};
// Add setters for the element itself (#4938)
if (isSVG) { // #4938, only for HTML within SVG
addSetters(wrapper, wrapper.element.style);
}
// Various setters which rely on update transform
wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function(value, key) {
if (key === 'align') {
key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
}
wrapper[key] = value;
wrapper.htmlUpdateTransform();
};
// Set the default attributes
wrapper
.attr({
text: str,
x: Math.round(x),
y: Math.round(y)
})
.css({
position: 'absolute'
});
// Keep the whiteSpace style outside the wrapper.styles collection
element.style.whiteSpace = 'nowrap';
// Use the HTML specific .css method
wrapper.css = wrapper.htmlCss;
// This is specific for HTML within SVG
if (isSVG) {
wrapper.add = function(svgGroupWrapper) {
var htmlGroup,
container = renderer.box.parentNode,
parentGroup,
parents = [];
this.parentGroup = svgGroupWrapper;
// Create a mock group to hold the HTML elements
if (svgGroupWrapper) {
htmlGroup = svgGroupWrapper.div;
if (!htmlGroup) {
// Read the parent chain into an array and read from top down
parentGroup = svgGroupWrapper;
while (parentGroup) {
parents.push(parentGroup);
// Move up to the next parent group
parentGroup = parentGroup.parentGroup;
}
// Ensure dynamically updating position when any parent is translated
each(parents.reverse(), function(parentGroup) {
var htmlGroupStyle,
cls = attr(parentGroup.element, 'class');
if (cls) {
cls = {
className: cls
};
} // else null
// Create a HTML div and append it to the parent div to emulate
// the SVG group structure
htmlGroup = parentGroup.div = parentGroup.div || createElement('div', cls, {
position: 'absolute',
left: (parentGroup.translateX || 0) + 'px',
top: (parentGroup.translateY || 0) + 'px',
display: parentGroup.display,
opacity: parentGroup.opacity, // #5075
pointerEvents: parentGroup.styles && parentGroup.styles.pointerEvents // #5595
}, htmlGroup || container); // the top group is appended to container
// Shortcut
htmlGroupStyle = htmlGroup.style;
// Set listeners to update the HTML div's position whenever the SVG group
// position is changed
extend(parentGroup, {
translateXSetter: function(value, key) {
htmlGroupStyle.left = value + 'px';
parentGroup[key] = value;
parentGroup.doTransform = true;
},
translateYSetter: function(value, key) {
htmlGroupStyle.top = value + 'px';
parentGroup[key] = value;
parentGroup.doTransform = true;
}
});
addSetters(parentGroup, htmlGroupStyle);
});
}
} else {
htmlGroup = container;
}
htmlGroup.appendChild(element);
// Shared with VML:
wrapper.added = true;
if (wrapper.alignOnAdd) {
wrapper.htmlUpdateTransform();
}
return wrapper;
};
}
return wrapper;
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var correctFloat = H.correctFloat,
defined = H.defined,
destroyObjectProperties = H.destroyObjectProperties,
isNumber = H.isNumber,
merge = H.merge,
pick = H.pick,
stop = H.stop,
deg2rad = H.deg2rad;
/**
* The Tick class
*/
H.Tick = function(axis, pos, type, noLabel) {
this.axis = axis;
this.pos = pos;
this.type = type || '';
this.isNew = true;
if (!type && !noLabel) {
this.addLabel();
}
};
H.Tick.prototype = {
/**
* Write the tick label
*/
addLabel: function() {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
categories = axis.categories,
names = axis.names,
pos = tick.pos,
labelOptions = options.labels,
str,
tickPositions = axis.tickPositions,
isFirst = pos === tickPositions[0],
isLast = pos === tickPositions[tickPositions.length - 1],
value = categories ?
pick(categories[pos], names[pos], pos) :
pos,
label = tick.label,
tickPositionInfo = tickPositions.info,
dateTimeLabelFormat;
// Set the datetime label format. If a higher rank is set for this position, use that. If not,
// use the general format.
if (axis.isDatetimeAxis && tickPositionInfo) {
dateTimeLabelFormat =
options.dateTimeLabelFormats[
tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName
];
}
// set properties for access in render method
tick.isFirst = isFirst;
tick.isLast = isLast;
// get the string
str = axis.labelFormatter.call({
axis: axis,
chart: chart,
isFirst: isFirst,
isLast: isLast,
dateTimeLabelFormat: dateTimeLabelFormat,
value: axis.isLog ? correctFloat(axis.lin2log(value)) : value
});
// prepare CSS
//css = width && { width: Math.max(1, Math.round(width - 2 * (labelOptions.padding || 10))) + 'px' };
// first call
if (!defined(label)) {
tick.label = label =
defined(str) && labelOptions.enabled ?
chart.renderer.text(
str,
0,
0,
labelOptions.useHTML
)
.add(axis.labelGroup):
null;
tick.labelLength = label && label.getBBox().width; // Un-rotated length
tick.rotation = 0; // Base value to detect change for new calls to getBBox
// update
} else if (label) {
label.attr({
text: str
});
}
},
/**
* Get the offset height or width of the label
*/
getLabelSize: function() {
return this.label ?
this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
0;
},
/**
* Handle the label overflow by adjusting the labels to the left and right edge, or
* hide them if they collide into the neighbour label.
*/
handleOverflow: function(xy) {
var axis = this.axis,
pxPos = xy.x,
chartWidth = axis.chart.chartWidth,
spacing = axis.chart.spacing,
leftBound = pick(axis.labelLeft, Math.min(axis.pos, spacing[3])),
rightBound = pick(axis.labelRight, Math.max(axis.pos + axis.len, chartWidth - spacing[1])),
label = this.label,
rotation = this.rotation,
factor = {
left: 0,
center: 0.5,
right: 1
}[axis.labelAlign],
labelWidth = label.getBBox().width,
slotWidth = axis.getSlotWidth(),
modifiedSlotWidth = slotWidth,
xCorrection = factor,
goRight = 1,
leftPos,
rightPos,
textWidth,
css = {};
// Check if the label overshoots the chart spacing box. If it does, move it.
// If it now overshoots the slotWidth, add ellipsis.
if (!rotation) {
leftPos = pxPos - factor * labelWidth;
rightPos = pxPos + (1 - factor) * labelWidth;
if (leftPos < leftBound) {
modifiedSlotWidth = xy.x + modifiedSlotWidth * (1 - factor) - leftBound;
} else if (rightPos > rightBound) {
modifiedSlotWidth = rightBound - xy.x + modifiedSlotWidth * factor;
goRight = -1;
}
modifiedSlotWidth = Math.min(slotWidth, modifiedSlotWidth); // #4177
if (modifiedSlotWidth < slotWidth && axis.labelAlign === 'center') {
xy.x += goRight * (slotWidth - modifiedSlotWidth - xCorrection *
(slotWidth - Math.min(labelWidth, modifiedSlotWidth)));
}
// If the label width exceeds the available space, set a text width to be
// picked up below. Also, if a width has been set before, we need to set a new
// one because the reported labelWidth will be limited by the box (#3938).
if (labelWidth > modifiedSlotWidth || (axis.autoRotation && (label.styles || {}).width)) {
textWidth = modifiedSlotWidth;
}
// Add ellipsis to prevent rotated labels to be clipped against the edge of the chart
} else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) {
textWidth = Math.round(pxPos / Math.cos(rotation * deg2rad) - leftBound);
} else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) {
textWidth = Math.round((chartWidth - pxPos) / Math.cos(rotation * deg2rad));
}
if (textWidth) {
css.width = textWidth;
if (!(axis.options.labels.style || {}).textOverflow) {
css.textOverflow = 'ellipsis';
}
label.css(css);
}
},
/**
* Get the x and y position for ticks and labels
*/
getPosition: function(horiz, pos, tickmarkOffset, old) {
var axis = this.axis,
chart = axis.chart,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
return {
x: horiz ?
axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset +
(axis.opposite ?
((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left :
0
),
y: horiz ?
cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
};
},
/**
* Get the x, y position of the tick label
*/
getLabelPosition: function(x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
var axis = this.axis,
transA = axis.transA,
reversed = axis.reversed,
staggerLines = axis.staggerLines,
rotCorr = axis.tickRotCorr || {
x: 0,
y: 0
},
yOffset = labelOptions.y,
line;
if (!defined(yOffset)) {
if (axis.side === 0) {
yOffset = label.rotation ? -8 : -label.getBBox().height;
} else if (axis.side === 2) {
yOffset = rotCorr.y + 8;
} else {
// #3140, #3140
yOffset = Math.cos(label.rotation * deg2rad) * (rotCorr.y - label.getBBox(false, 0).height / 2);
}
}
x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ?
tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
y = y + yOffset - (tickmarkOffset && !horiz ?
tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
// Correct for staggered labels
if (staggerLines) {
line = (index / (step || 1) % staggerLines);
if (axis.opposite) {
line = staggerLines - line - 1;
}
y += line * (axis.labelOffset / staggerLines);
}
return {
x: x,
y: Math.round(y)
};
},
/**
* Extendible method to return the path of the marker
*/
getMarkPath: function(x, y, tickLength, tickWidth, horiz, renderer) {
return renderer.crispLine([
'M',
x,
y,
'L',
x + (horiz ? 0 : -tickLength),
y + (horiz ? tickLength : 0)
], tickWidth);
},
/**
* Put everything in place
*
* @param index {Number}
* @param old {Boolean} Use old coordinates to prepare an animation into new position
*/
render: function(index, old, opacity) {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
renderer = chart.renderer,
horiz = axis.horiz,
type = tick.type,
label = tick.label,
pos = tick.pos,
labelOptions = options.labels,
gridLine = tick.gridLine,
tickPrefix = type ? type + 'Tick' : 'tick',
tickSize = axis.tickSize(tickPrefix),
gridLinePath,
mark = tick.mark,
isNewMark = !mark,
step = labelOptions.step,
attribs = {},
show = true,
tickmarkOffset = axis.tickmarkOffset,
xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
x = xy.x,
y = xy.y,
reverseCrisp = ((horiz && x === axis.pos + axis.len) ||
(!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
opacity = pick(opacity, 1);
this.isActive = true;
// Create the grid line
if (!gridLine) {
if (!type) {
attribs.zIndex = 1;
}
if (old) {
attribs.opacity = 0;
}
tick.gridLine = gridLine = renderer.path()
.attr(attribs)
.addClass('highcharts-' + (type ? type + '-' : '') + 'grid-line')
.add(axis.gridGroup);
}
// If the parameter 'old' is set, the current call will be followed
// by another call, therefore do not do any animations this time
if (!old && gridLine) {
gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLine.strokeWidth() * reverseCrisp, old, true);
if (gridLinePath) {
gridLine[tick.isNew ? 'attr' : 'animate']({
d: gridLinePath,
opacity: opacity
});
}
}
// create the tick mark
if (tickSize) {
// negate the length
if (axis.opposite) {
tickSize[0] = -tickSize[0];
}
// First time, create it
if (isNewMark) {
tick.mark = mark = renderer.path()
.addClass('highcharts-' + (type ? type + '-' : '') + 'tick')
.add(axis.axisGroup);
}
mark[isNewMark ? 'attr' : 'animate']({
d: tick.getMarkPath(x, y, tickSize[0], mark.strokeWidth() * reverseCrisp, horiz, renderer),
opacity: opacity
});
}
// the label is created on init - now move it into place
if (label && isNumber(x)) {
label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
// Apply show first and show last. If the tick is both first and last, it is
// a single centered tick, in which case we show the label anyway (#2100).
if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
(tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
show = false;
// Handle label overflow and show or hide accordingly
} else if (horiz && !axis.isRadial && !labelOptions.step &&
!labelOptions.rotation && !old && opacity !== 0) {
tick.handleOverflow(xy);
}
// apply step
if (step && index % step) {
// show those indices dividable by step
show = false;
}
// Set the new position, and show or hide
if (show && isNumber(xy.y)) {
xy.opacity = opacity;
label[tick.isNew ? 'attr' : 'animate'](xy);
} else {
stop(label); // #5332
label.attr('y', -9999); // #1338
}
tick.isNew = false;
}
},
/**
* Destructor for the tick prototype
*/
destroy: function() {
destroyObjectProperties(this, this.axis);
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
defined = H.defined,
destroyObjectProperties = H.destroyObjectProperties,
each = H.each,
erase = H.erase,
merge = H.merge,
pick = H.pick;
/*
* The object wrapper for plot lines and plot bands
* @param {Object} options
*/
H.PlotLineOrBand = function(axis, options) {
this.axis = axis;
if (options) {
this.options = options;
this.id = options.id;
}
};
H.PlotLineOrBand.prototype = {
/**
* Render the plot line or plot band. If it is already existing,
* move it.
*/
render: function() {
var plotLine = this,
axis = plotLine.axis,
horiz = axis.horiz,
options = plotLine.options,
optionsLabel = options.label,
label = plotLine.label,
to = options.to,
from = options.from,
value = options.value,
isBand = defined(from) && defined(to),
isLine = defined(value),
svgElem = plotLine.svgElem,
isNew = !svgElem,
path = [],
addEvent,
eventType,
color = options.color,
zIndex = pick(options.zIndex, 0),
events = options.events,
attribs = {
'class': 'highcharts-plot-' + (isBand ? 'band ' : 'line ') + (options.className || '')
},
groupAttribs = {},
renderer = axis.chart.renderer,
groupName = isBand ? 'bands' : 'lines',
group,
log2lin = axis.log2lin;
// logarithmic conversion
if (axis.isLog) {
from = log2lin(from);
to = log2lin(to);
value = log2lin(value);
}
// Grouping and zIndex
groupAttribs.zIndex = zIndex;
groupName += '-' + zIndex;
group = axis[groupName];
if (!group) {
axis[groupName] = group = renderer.g('plot-' + groupName)
.attr(groupAttribs).add();
}
// Create the path
if (isNew) {
plotLine.svgElem = svgElem =
renderer
.path()
.attr(attribs).add(group);
}
// Set the path or return
if (isLine) {
path = axis.getPlotLinePath(value, svgElem.strokeWidth());
} else if (isBand) { // plot band
path = axis.getPlotBandPath(from, to, options);
} else {
return;
}
// common for lines and bands
if (isNew && path && path.length) {
svgElem.attr({
d: path
});
// events
if (events) {
addEvent = function(eventType) {
svgElem.on(eventType, function(e) {
events[eventType].apply(plotLine, [e]);
});
};
for (eventType in events) {
addEvent(eventType);
}
}
} else if (svgElem) {
if (path) {
svgElem.show();
svgElem.animate({
d: path
});
} else {
svgElem.hide();
if (label) {
plotLine.label = label = label.destroy();
}
}
}
// the plot band/line label
if (optionsLabel && defined(optionsLabel.text) && path && path.length &&
axis.width > 0 && axis.height > 0 && !path.flat) {
// apply defaults
optionsLabel = merge({
align: horiz && isBand && 'center',
x: horiz ? !isBand && 4 : 10,
verticalAlign: !horiz && isBand && 'middle',
y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
rotation: horiz && !isBand && 90
}, optionsLabel);
this.renderLabel(optionsLabel, path, isBand, zIndex);
} else if (label) { // move out of sight
label.hide();
}
// chainable
return plotLine;
},
/**
* Render and align label for plot line or band.
*/
renderLabel: function(optionsLabel, path, isBand, zIndex) {
var plotLine = this,
label = plotLine.label,
renderer = plotLine.axis.chart.renderer,
attribs,
xs,
ys,
x,
y;
// add the SVG element
if (!label) {
attribs = {
align: optionsLabel.textAlign || optionsLabel.align,
rotation: optionsLabel.rotation,
'class': 'highcharts-plot-' + (isBand ? 'band' : 'line') + '-label ' + (optionsLabel.className || '')
};
attribs.zIndex = zIndex;
plotLine.label = label = renderer.text(
optionsLabel.text,
0,
0,
optionsLabel.useHTML
)
.attr(attribs)
.add();
}
// get the bounding box and align the label
// #3000 changed to better handle choice between plotband or plotline
xs = [path[1], path[4], (isBand ? path[6] : path[1])];
ys = [path[2], path[5], (isBand ? path[7] : path[2])];
x = arrayMin(xs);
y = arrayMin(ys);
label.align(optionsLabel, false, {
x: x,
y: y,
width: arrayMax(xs) - x,
height: arrayMax(ys) - y
});
label.show();
},
/**
* Remove the plot line or band
*/
destroy: function() {
// remove it from the lookup
erase(this.axis.plotLinesAndBands, this);
delete this.axis;
destroyObjectProperties(this);
}
};
/**
* Object with members for extending the Axis prototype
* @todo Extend directly instead of adding object to Highcharts first
*/
H.AxisPlotLineOrBandExtension = {
/**
* Create the path for a plot band
*/
getPlotBandPath: function(from, to) {
var toPath = this.getPlotLinePath(to, null, null, true),
path = this.getPlotLinePath(from, null, null, true);
if (path && toPath) {
// Flat paths don't need labels (#3836)
path.flat = path.toString() === toPath.toString();
path.push(
toPath[4],
toPath[5],
toPath[1],
toPath[2]
);
} else { // outside the axis area
path = null;
}
return path;
},
addPlotBand: function(options) {
return this.addPlotBandOrLine(options, 'plotBands');
},
addPlotLine: function(options) {
return this.addPlotBandOrLine(options, 'plotLines');
},
/**
* Add a plot band or plot line after render time
*
* @param options {Object} The plotBand or plotLine configuration object
*/
addPlotBandOrLine: function(options, coll) {
var obj = new H.PlotLineOrBand(this, options).render(),
userOptions = this.userOptions;
if (obj) { // #2189
// Add it to the user options for exporting and Axis.update
if (coll) {
userOptions[coll] = userOptions[coll] || [];
userOptions[coll].push(options);
}
this.plotLinesAndBands.push(obj);
}
return obj;
},
/**
* Remove a plot band or plot line from the chart by id
* @param {Object} id
*/
removePlotBandOrLine: function(id) {
var plotLinesAndBands = this.plotLinesAndBands,
options = this.options,
userOptions = this.userOptions,
i = plotLinesAndBands.length;
while (i--) {
if (plotLinesAndBands[i].id === id) {
plotLinesAndBands[i].destroy();
}
}
each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function(arr) {
i = arr.length;
while (i--) {
if (arr[i].id === id) {
erase(arr, arr[i]);
}
}
});
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animObject = H.animObject,
arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
AxisPlotLineOrBandExtension = H.AxisPlotLineOrBandExtension,
color = H.color,
correctFloat = H.correctFloat,
defaultOptions = H.defaultOptions,
defined = H.defined,
deg2rad = H.deg2rad,
destroyObjectProperties = H.destroyObjectProperties,
each = H.each,
error = H.error,
extend = H.extend,
fireEvent = H.fireEvent,
format = H.format,
getMagnitude = H.getMagnitude,
grep = H.grep,
inArray = H.inArray,
isArray = H.isArray,
isNumber = H.isNumber,
isString = H.isString,
merge = H.merge,
normalizeTickInterval = H.normalizeTickInterval,
pick = H.pick,
PlotLineOrBand = H.PlotLineOrBand,
removeEvent = H.removeEvent,
splat = H.splat,
syncTimeout = H.syncTimeout,
Tick = H.Tick;
/**
* Create a new axis object
* @param {Object} chart
* @param {Object} options
*/
H.Axis = function() {
this.init.apply(this, arguments);
};
H.Axis.prototype = {
/**
* Default options for the X axis - the Y axis has extended defaults
*/
defaultOptions: {
// allowDecimals: null,
// alternateGridColor: null,
// categories: [],
dateTimeLabelFormats: {
millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
},
endOnTick: false,
// reversed: false,
labels: {
enabled: true,
// rotation: 0,
// align: 'center',
// step: null,
x: 0
//y: undefined
/*formatter: function () {
return this.value;
},*/
},
//linkedTo: null,
//max: undefined,
//min: undefined,
minPadding: 0.01,
maxPadding: 0.01,
//minRange: null,
//minorTickInterval: null,
minorTickLength: 2,
minorTickPosition: 'outside', // inside or outside
//opposite: false,
//offset: 0,
//plotBands: [{
// events: {},
// zIndex: 1,
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//plotLines: [{
// events: {}
// dashStyle: {}
// zIndex:
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//reversed: false,
// showFirstLabel: true,
// showLastLabel: true,
startOfWeek: 1,
startOnTick: false,
//tickInterval: null,
tickLength: 10,
tickmarkPlacement: 'between', // on or between
tickPixelInterval: 100,
tickPosition: 'outside',
title: {
//text: null,
align: 'middle', // low, middle or high
//margin: 0 for horizontal, 10 for vertical axes,
//rotation: 0,
//side: 'outside',
//x: 0,
//y: 0
},
type: 'linear', // linear, logarithmic or datetime
//visible: true
},
/**
* This options set extends the defaultOptions for Y axes
*/
defaultYAxisOptions: {
endOnTick: true,
tickPixelInterval: 72,
showLastLabel: true,
labels: {
x: -8
},
maxPadding: 0.05,
minPadding: 0.05,
startOnTick: true,
title: {
rotation: 270,
text: 'Values'
},
stackLabels: {
enabled: false,
//align: dynamic,
//y: dynamic,
//x: dynamic,
//verticalAlign: dynamic,
//textAlign: dynamic,
//rotation: 0,
formatter: function() {
return H.numberFormat(this.total, -1);
}
}
},
/**
* These options extend the defaultOptions for left axes
*/
defaultLeftAxisOptions: {
labels: {
x: -15
},
title: {
rotation: 270
}
},
/**
* These options extend the defaultOptions for right axes
*/
defaultRightAxisOptions: {
labels: {
x: 15
},
title: {
rotation: 90
}
},
/**
* These options extend the defaultOptions for bottom axes
*/
defaultBottomAxisOptions: {
labels: {
autoRotation: [-45],
x: 0
// overflow: undefined,
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* These options extend the defaultOptions for top axes
*/
defaultTopAxisOptions: {
labels: {
autoRotation: [-45],
x: 0
// overflow: undefined
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* Initialize the axis
*/
init: function(chart, userOptions) {
var isXAxis = userOptions.isX,
axis = this;
axis.chart = chart;
// Flag, is the axis horizontal
axis.horiz = chart.inverted ? !isXAxis : isXAxis;
// Flag, isXAxis
axis.isXAxis = isXAxis;
axis.coll = axis.coll || (isXAxis ? 'xAxis' : 'yAxis');
axis.opposite = userOptions.opposite; // needed in setOptions
axis.side = userOptions.side || (axis.horiz ?
(axis.opposite ? 0 : 2) : // top : bottom
(axis.opposite ? 1 : 3)); // right : left
axis.setOptions(userOptions);
var options = this.options,
type = options.type,
isDatetimeAxis = type === 'datetime';
axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
// Flag, stagger lines or not
axis.userOptions = userOptions;
//axis.axisTitleMargin = undefined,// = options.title.margin,
axis.minPixelPadding = 0;
axis.reversed = options.reversed;
axis.visible = options.visible !== false;
axis.zoomEnabled = options.zoomEnabled !== false;
// Initial categories
axis.hasNames = type === 'category' || options.categories === true;
axis.categories = options.categories || axis.hasNames;
axis.names = axis.names || []; // Preserve on update (#3830)
// Elements
//axis.axisGroup = undefined;
//axis.gridGroup = undefined;
//axis.axisTitle = undefined;
//axis.axisLine = undefined;
// Shorthand types
axis.isLog = type === 'logarithmic';
axis.isDatetimeAxis = isDatetimeAxis;
// Flag, if axis is linked to another axis
axis.isLinked = defined(options.linkedTo);
// Linked axis.
//axis.linkedParent = undefined;
// Tick positions
//axis.tickPositions = undefined; // array containing predefined positions
// Tick intervals
//axis.tickInterval = undefined;
//axis.minorTickInterval = undefined;
// Major ticks
axis.ticks = {};
axis.labelEdge = [];
// Minor ticks
axis.minorTicks = {};
// List of plotLines/Bands
axis.plotLinesAndBands = [];
// Alternate bands
axis.alternateBands = {};
// Axis metrics
//axis.left = undefined;
//axis.top = undefined;
//axis.width = undefined;
//axis.height = undefined;
//axis.bottom = undefined;
//axis.right = undefined;
//axis.transA = undefined;
//axis.transB = undefined;
//axis.oldTransA = undefined;
axis.len = 0;
//axis.oldMin = undefined;
//axis.oldMax = undefined;
//axis.oldUserMin = undefined;
//axis.oldUserMax = undefined;
//axis.oldAxisLength = undefined;
axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
axis.range = options.range;
axis.offset = options.offset || 0;
// Dictionary for stacks
axis.stacks = {};
axis.oldStacks = {};
axis.stacksTouched = 0;
// Min and max in the data
//axis.dataMin = undefined,
//axis.dataMax = undefined,
// The axis range
axis.max = null;
axis.min = null;
// User set min and max
//axis.userMin = undefined,
//axis.userMax = undefined,
// Crosshair options
axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false);
// Run Axis
var eventType,
events = axis.options.events;
// Register
if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
if (isXAxis) { // #2713
chart.axes.splice(chart.xAxis.length, 0, axis);
} else {
chart.axes.push(axis);
}
chart[axis.coll].push(axis);
}
axis.series = axis.series || []; // populated by Series
// inverted charts have reversed xAxes as default
if (chart.inverted && isXAxis && axis.reversed === undefined) {
axis.reversed = true;
}
axis.removePlotBand = axis.removePlotBandOrLine;
axis.removePlotLine = axis.removePlotBandOrLine;
// register event listeners
for (eventType in events) {
addEvent(axis, eventType, events[eventType]);
}
// extend logarithmic axis
if (axis.isLog) {
axis.val2lin = axis.log2lin;
axis.lin2val = axis.lin2log;
}
},
/**
* Merge and set options
*/
setOptions: function(userOptions) {
this.options = merge(
this.defaultOptions,
this.coll === 'yAxis' && this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
this.defaultBottomAxisOptions, this.defaultLeftAxisOptions
][this.side],
merge(
defaultOptions[this.coll], // if set in setOptions (#1053)
userOptions
)
);
},
/**
* The default label formatter. The context is a special config object for the label.
*/
defaultLabelFormatter: function() {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = H.dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
while (i-- && ret === undefined) {
multi = Math.pow(1000, i + 1);
if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null && value !== 0) { // #5480
ret = H.numberFormat(value / multi, -1) + numericSymbols[i];
}
}
}
if (ret === undefined) {
if (Math.abs(value) >= 10000) { // add thousands separators
ret = H.numberFormat(value, -1);
} else { // small numbers
ret = H.numberFormat(value, -1, undefined, ''); // #2466
}
}
return ret;
},
/**
* Get the minimum and maximum for the series of each axis
*/
getSeriesExtremes: function() {
var axis = this,
chart = axis.chart;
axis.hasVisibleSeries = false;
// Reset properties in case we're redrawing (#3353)
axis.dataMin = axis.dataMax = axis.threshold = null;
axis.softThreshold = !axis.isXAxis;
if (axis.buildStacks) {
axis.buildStacks();
}
// loop through this axis' series
each(axis.series, function(series) {
if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
var seriesOptions = series.options,
xData,
threshold = seriesOptions.threshold,
seriesDataMin,
seriesDataMax;
axis.hasVisibleSeries = true;
// Validate threshold in logarithmic axes
if (axis.isLog && threshold <= 0) {
threshold = null;
}
// Get dataMin and dataMax for X axes
if (axis.isXAxis) {
xData = series.xData;
if (xData.length) {
// If xData contains values which is not numbers, then filter them out.
// To prevent performance hit, we only do this after we have already
// found seriesDataMin because in most cases all data is valid. #5234.
seriesDataMin = arrayMin(xData);
if (!isNumber(seriesDataMin) && !(seriesDataMin instanceof Date)) { // Date for #5010
xData = grep(xData, function(x) {
return isNumber(x);
});
seriesDataMin = arrayMin(xData); // Do it again with valid data
}
axis.dataMin = Math.min(pick(axis.dataMin, xData[0]), seriesDataMin);
axis.dataMax = Math.max(pick(axis.dataMax, xData[0]), arrayMax(xData));
}
// Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
} else {
// Get this particular series extremes
series.getExtremes();
seriesDataMax = series.dataMax;
seriesDataMin = series.dataMin;
// Get the dataMin and dataMax so far. If percentage is used, the min and max are
// always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
// doesn't have active y data, we continue with nulls
if (defined(seriesDataMin) && defined(seriesDataMax)) {
axis.dataMin = Math.min(pick(axis.dataMin, seriesDataMin), seriesDataMin);
axis.dataMax = Math.max(pick(axis.dataMax, seriesDataMax), seriesDataMax);
}
// Adjust to threshold
if (defined(threshold)) {
axis.threshold = threshold;
}
// If any series has a hard threshold, it takes precedence
if (!seriesOptions.softThreshold || axis.isLog) {
axis.softThreshold = false;
}
}
}
});
},
/**
* Translate from axis value to pixel position on the chart, or back
*
*/
translate: function(val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this.linkedParent || this, // #1417
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
doPostTranslate = (axis.isOrdinal || axis.isBroken || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axis.len;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * (axis.sector || axis.len);
}
// From pixels to value
if (backwards) { // reverse translation
val = val * sign + cvsOffset;
val -= minPixelPadding;
returnValue = val / localA + localMin; // from chart pixel to value
if (doPostTranslate) { // log and ordinal axes
returnValue = axis.lin2val(returnValue);
}
// From value to pixels
} else {
if (doPostTranslate) { // log and ordinal axes
val = axis.val2lin(val);
}
if (pointPlacement === 'between') {
pointPlacement = 0.5;
}
returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
(isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
}
return returnValue;
},
/**
* Utility method to translate an axis value to pixel position.
* @param {Number} value A value in terms of axis units
* @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
* or just the axis/pane itself.
*/
toPixels: function(value, paneCoordinates) {
return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
},
/*
* Utility method to translate a pixel position in to an axis value
* @param {Number} pixel The pixel value coordinate
* @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
* axis/pane itself.
*/
toValue: function(pixel, paneCoordinates) {
return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
},
/**
* Create the path for a plot line that goes from the given value on
* this axis, across the plot to the opposite side
* @param {Number} value
* @param {Number} lineWidth Used for calculation crisp line
* @param {Number] old Use old coordinates (for resizing and rescaling)
*/
getPlotLinePath: function(value, lineWidth, old, force, translatedValue) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB,
/**
* Check if x is between a and b. If not, either move to a/b or skip,
* depending on the force parameter.
*/
between = function(x, a, b) {
if (x < a || x > b) {
if (force) {
x = Math.min(Math.max(a, x), b);
} else {
skip = true;
}
}
return x;
};
translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
x1 = x2 = Math.round(translatedValue + transB);
y1 = y2 = Math.round(cHeight - translatedValue - transB);
if (!isNumber(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
x1 = x2 = between(x1, axisLeft, axisLeft + axis.width);
} else {
x1 = axisLeft;
x2 = cWidth - axis.right;
y1 = y2 = between(y1, axisTop, axisTop + axis.height);
}
return skip && !force ?
null :
chart.renderer.crispLine(['M', x1, y1, 'L', x2, y2], lineWidth || 1);
},
/**
* Set the tick positions of a linear axis to round values like whole tens or every five.
*/
getLinearTickPositions: function(tickInterval, min, max) {
var pos,
lastPos,
roundedMin = correctFloat(Math.floor(min / tickInterval) * tickInterval),
roundedMax = correctFloat(Math.ceil(max / tickInterval) * tickInterval),
tickPositions = [];
// For single points, add a tick regardless of the relative position (#2662)
if (min === max && isNumber(min)) {
return [min];
}
// Populate the intermediate values
pos = roundedMin;
while (pos <= roundedMax) {
// Place the tick on the rounded value
tickPositions.push(pos);
// Always add the raw tickInterval, not the corrected one.
pos = correctFloat(pos + tickInterval);
// If the interval is not big enough in the current min - max range to actually increase
// the loop variable, we need to break out to prevent endless loop. Issue #619
if (pos === lastPos) {
break;
}
// Record the last value
lastPos = pos;
}
return tickPositions;
},
/**
* Return the minor tick positions. For logarithmic axes, reuse the same logic
* as for major ticks.
*/
getMinorTickPositions: function() {
var axis = this,
options = axis.options,
tickPositions = axis.tickPositions,
minorTickInterval = axis.minorTickInterval,
minorTickPositions = [],
pos,
i,
pointRangePadding = axis.pointRangePadding || 0,
min = axis.min - pointRangePadding, // #1498
max = axis.max + pointRangePadding, // #1498
range = max - min,
len;
// If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them.
if (range && range / minorTickInterval < axis.len / 3) { // #3875
if (axis.isLog) {
len = tickPositions.length;
for (i = 1; i < len; i++) {
minorTickPositions = minorTickPositions.concat(
axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
);
}
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
axis.getTimeTicks(
axis.normalizeTimeTickInterval(minorTickInterval),
min,
max,
options.startOfWeek
)
);
} else {
for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) {
minorTickPositions.push(pos);
}
}
}
if (minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks
axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498
}
return minorTickPositions;
},
/**
* Adjust the min and max for the minimum range. Keep in mind that the series data is
* not yet processed, so we don't have information on data cropping and grouping, or
* updated axis.pointRange or series.pointRange. The data can't be processed until
* we have finally established min and max.
*/
adjustForMinRange: function() {
var axis = this,
options = axis.options,
min = axis.min,
max = axis.max,
zoomOffset,
spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
closestDataRange,
i,
distance,
xData,
loopLength,
minArgs,
maxArgs,
minRange;
// Set the automatic minimum range based on the closest point distance
if (axis.isXAxis && axis.minRange === undefined && !axis.isLog) {
if (defined(options.min) || defined(options.max)) {
axis.minRange = null; // don't do this again
} else {
// Find the closest distance between raw data points, as opposed to
// closestPointRange that applies to processed points (cropped and grouped)
each(axis.series, function(series) {
xData = series.xData;
loopLength = series.xIncrement ? 1 : xData.length - 1;
for (i = loopLength; i > 0; i--) {
distance = xData[i] - xData[i - 1];
if (closestDataRange === undefined || distance < closestDataRange) {
closestDataRange = distance;
}
}
});
axis.minRange = Math.min(closestDataRange * 5, axis.dataMax - axis.dataMin);
}
}
// if minRange is exceeded, adjust
if (max - min < axis.minRange) {
minRange = axis.minRange;
zoomOffset = (minRange - max + min) / 2;
// if min and max options have been set, don't go beyond it
minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
if (spaceAvailable) { // if space is available, stay within the data range
minArgs[2] = axis.isLog ? axis.log2lin(axis.dataMin) : axis.dataMin;
}
min = arrayMax(minArgs);
maxArgs = [min + minRange, pick(options.max, min + minRange)];
if (spaceAvailable) { // if space is availabe, stay within the data range
maxArgs[2] = axis.isLog ? axis.log2lin(axis.dataMax) : axis.dataMax;
}
max = arrayMin(maxArgs);
// now if the max is adjusted, adjust the min back
if (max - min < minRange) {
minArgs[0] = max - minRange;
minArgs[1] = pick(options.min, max - minRange);
min = arrayMax(minArgs);
}
}
// Record modified extremes
axis.min = min;
axis.max = max;
},
/**
* Find the closestPointRange across all series
*/
getClosest: function() {
var ret;
if (this.categories) {
ret = 1;
} else {
each(this.series, function(series) {
var seriesClosest = series.closestPointRange;
if (!series.noSharedTooltip && defined(seriesClosest)) {
ret = defined(ret) ?
Math.min(ret, seriesClosest) :
seriesClosest;
}
});
}
return ret;
},
/**
* When a point name is given and no x, search for the name in the existing categories,
* or if categories aren't provided, search names or create a new category (#2522).
*/
nameToX: function(point) {
var explicitCategories = isArray(this.categories),
names = explicitCategories ? this.categories : this.names,
nameX = point.options.x,
x;
point.series.requireSorting = false;
if (!defined(nameX)) {
nameX = this.options.uniqueNames === false ?
point.series.autoIncrement() :
inArray(point.name, names);
}
if (nameX === -1) { // The name is not found in currenct categories
if (!explicitCategories) {
x = names.length;
}
} else {
x = nameX;
}
// Write the last point's name to the names array
this.names[x] = point.name;
return x;
},
/**
* When changes have been done to series data, update the axis.names.
*/
updateNames: function() {
var axis = this;
if (this.names.length > 0) {
this.names.length = 0;
this.minRange = undefined;
each(this.series || [], function(series) {
// When adding a series, points are not yet generated
if (!series.points || series.isDirtyData) {
series.processData();
series.generatePoints();
}
each(series.points, function(point, i) {
var x;
if (point.options && point.options.x === undefined) {
x = axis.nameToX(point);
if (x !== point.x) {
point.x = x;
series.xData[i] = x;
}
}
});
});
}
},
/**
* Update translation information
*/
setAxisTranslation: function(saveOld) {
var axis = this,
range = axis.max - axis.min,
pointRange = axis.axisPointRange || 0,
closestPointRange,
minPointOffset = 0,
pointRangePadding = 0,
linkedParent = axis.linkedParent,
ordinalCorrection,
hasCategories = !!axis.categories,
transA = axis.transA,
isXAxis = axis.isXAxis;
// Adjust translation for padding. Y axis with categories need to go through the same (#1784).
if (isXAxis || hasCategories || pointRange) {
if (linkedParent) {
minPointOffset = linkedParent.minPointOffset;
pointRangePadding = linkedParent.pointRangePadding;
} else {
// Get the closest points
closestPointRange = axis.getClosest();
each(axis.series, function(series) {
var seriesPointRange = hasCategories ?
1 :
(isXAxis ?
pick(series.options.pointRange, closestPointRange, 0) :
(axis.axisPointRange || 0)), // #2806
pointPlacement = series.options.pointPlacement;
pointRange = Math.max(pointRange, seriesPointRange);
if (!axis.single) {
// minPointOffset is the value padding to the left of the axis in order to make
// room for points with a pointRange, typically columns. When the pointPlacement option
// is 'between' or 'on', this padding does not apply.
minPointOffset = Math.max(
minPointOffset,
isString(pointPlacement) ? 0 : seriesPointRange / 2
);
// Determine the total padding needed to the length of the axis to make room for the
// pointRange. If the series' pointPlacement is 'on', no padding is added.
pointRangePadding = Math.max(
pointRangePadding,
pointPlacement === 'on' ? 0 : seriesPointRange
);
}
});
}
// Record minPointOffset and pointRangePadding
ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
// pointRange means the width reserved for each point, like in a column chart
axis.pointRange = Math.min(pointRange, range);
// closestPointRange means the closest distance between points. In columns
// it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
// is some other value
if (isXAxis) {
axis.closestPointRange = closestPointRange;
}
}
// Secondary values
if (saveOld) {
axis.oldTransA = transA;
}
axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
axis.minPixelPadding = transA * minPointOffset;
},
minFromRange: function() {
return this.max - this.range;
},
/**
* Set the tick positions to round values and optionally extend the extremes
* to the nearest tick
*/
setTickInterval: function(secondPass) {
var axis = this,
chart = axis.chart,
options = axis.options,
isLog = axis.isLog,
log2lin = axis.log2lin,
isDatetimeAxis = axis.isDatetimeAxis,
isXAxis = axis.isXAxis,
isLinked = axis.isLinked,
maxPadding = options.maxPadding,
minPadding = options.minPadding,
length,
linkedParentExtremes,
tickIntervalOption = options.tickInterval,
minTickInterval,
tickPixelIntervalOption = options.tickPixelInterval,
categories = axis.categories,
threshold = axis.threshold,
softThreshold = axis.softThreshold,
thresholdMin,
thresholdMax,
hardMin,
hardMax;
if (!isDatetimeAxis && !categories && !isLinked) {
this.getTickAmount();
}
// Min or max set either by zooming/setExtremes or initial options
hardMin = pick(axis.userMin, options.min);
hardMax = pick(axis.userMax, options.max);
// Linked axis gets the extremes from the parent axis
if (isLinked) {
axis.linkedParent = chart[axis.coll][options.linkedTo];
linkedParentExtremes = axis.linkedParent.getExtremes();
axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
if (options.type !== axis.linkedParent.options.type) {
error(11, 1); // Can't link axes of different type
}
// Initial min and max from the extreme data values
} else {
// Adjust to hard threshold
if (!softThreshold && defined(threshold)) {
if (axis.dataMin >= threshold) {
thresholdMin = threshold;
minPadding = 0;
} else if (axis.dataMax <= threshold) {
thresholdMax = threshold;
maxPadding = 0;
}
}
axis.min = pick(hardMin, thresholdMin, axis.dataMin);
axis.max = pick(hardMax, thresholdMax, axis.dataMax);
}
if (isLog) {
if (!secondPass && Math.min(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
error(10, 1); // Can't plot negative values on log axis
}
// The correctFloat cures #934, float errors on full tens. But it
// was too aggressive for #4360 because of conversion back to lin,
// therefore use precision 15.
axis.min = correctFloat(log2lin(axis.min), 15);
axis.max = correctFloat(log2lin(axis.max), 15);
}
// handle zoomed range
if (axis.range && defined(axis.max)) {
axis.userMin = axis.min = hardMin = Math.max(axis.min, axis.minFromRange()); // #618
axis.userMax = hardMax = axis.max;
axis.range = null; // don't use it when running setExtremes
}
// Hook for Highstock Scroller. Consider combining with beforePadding.
fireEvent(axis, 'foundExtremes');
// Hook for adjusting this.min and this.max. Used by bubble series.
if (axis.beforePadding) {
axis.beforePadding();
}
// adjust min and max for the minimum range
axis.adjustForMinRange();
// Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
// into account, we do this after computing tick interval (#1337).
if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
length = axis.max - axis.min;
if (length) {
if (!defined(hardMin) && minPadding) {
axis.min -= length * minPadding;
}
if (!defined(hardMax) && maxPadding) {
axis.max += length * maxPadding;
}
}
}
// Handle options for floor, ceiling, softMin and softMax
if (isNumber(options.floor)) {
axis.min = Math.max(axis.min, options.floor);
} else if (isNumber(options.softMin)) {
axis.min = Math.min(axis.min, options.softMin);
}
if (isNumber(options.ceiling)) {
axis.max = Math.min(axis.max, options.ceiling);
} else if (isNumber(options.softMax)) {
axis.max = Math.max(axis.max, options.softMax);
}
// When the threshold is soft, adjust the extreme value only if
// the data extreme and the padded extreme land on either side of the threshold. For example,
// a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the
// default minPadding and startOnTick options. This is prevented by the softThreshold
// option.
if (softThreshold && defined(axis.dataMin)) {
threshold = threshold || 0;
if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) {
axis.min = threshold;
} else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) {
axis.max = threshold;
}
}
// get tickInterval
if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
axis.tickInterval = 1;
} else if (isLinked && !tickIntervalOption &&
tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval;
} else {
axis.tickInterval = pick(
tickIntervalOption,
this.tickAmount ? ((axis.max - axis.min) / Math.max(this.tickAmount - 1, 1)) : undefined,
categories ? // for categoried axis, 1 is default, for linear axis use tickPix
1 :
// don't let it be more than the data range
(axis.max - axis.min) * tickPixelIntervalOption / Math.max(axis.len, tickPixelIntervalOption)
);
}
// Now we're finished detecting min and max, crop and group series data. This
// is in turn needed in order to find tick positions in ordinal axes.
if (isXAxis && !secondPass) {
each(axis.series, function(series) {
series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
});
}
// set the translation factor used in translate function
axis.setAxisTranslation(true);
// hook for ordinal axes and radial axes
if (axis.beforeSetTickPositions) {
axis.beforeSetTickPositions();
}
// hook for extensions, used in Highstock ordinal axes
if (axis.postProcessTickInterval) {
axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
}
// In column-like charts, don't cramp in more ticks than there are points (#1943, #4184)
if (axis.pointRange && !tickIntervalOption) {
axis.tickInterval = Math.max(axis.pointRange, axis.tickInterval);
}
// Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange);
if (!tickIntervalOption && axis.tickInterval < minTickInterval) {
axis.tickInterval = minTickInterval;
}
// for linear axes, get magnitude and normalize the interval
if (!isDatetimeAxis && !isLog && !tickIntervalOption) {
axis.tickInterval = normalizeTickInterval(
axis.tickInterval,
null,
getMagnitude(axis.tickInterval),
// If the tick interval is between 0.5 and 5 and the axis max is in the order of
// thousands, chances are we are dealing with years. Don't allow decimals. #3363.
pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount
);
}
// Prevent ticks from getting so close that we can't draw the labels
if (!this.tickAmount) {
axis.tickInterval = axis.unsquish();
}
this.setTickPositions();
},
/**
* Now we have computed the normalized tickInterval, get the tick positions
*/
setTickPositions: function() {
var options = this.options,
tickPositions,
tickPositionsOption = options.tickPositions,
tickPositioner = options.tickPositioner,
startOnTick = options.startOnTick,
endOnTick = options.endOnTick,
single;
// Set the tickmarkOffset
this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' &&
this.tickInterval === 1) ? 0.5 : 0; // #3202
// get minorTickInterval
this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ?
this.tickInterval / 5 : options.minorTickInterval;
// Find the tick positions
this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565)
if (!tickPositions) {
if (this.isDatetimeAxis) {
tickPositions = this.getTimeTicks(
this.normalizeTimeTickInterval(this.tickInterval, options.units),
this.min,
this.max,
options.startOfWeek,
this.ordinalPositions,
this.closestPointRange,
true
);
} else if (this.isLog) {
tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max);
} else {
tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max);
}
// Too dense ticks, keep only the first and last (#4477)
if (tickPositions.length > this.len) {
tickPositions = [tickPositions[0], tickPositions.pop()];
}
this.tickPositions = tickPositions;
// Run the tick positioner callback, that allows modifying auto tick positions.
if (tickPositioner) {
tickPositioner = tickPositioner.apply(this, [this.min, this.max]);
if (tickPositioner) {
this.tickPositions = tickPositions = tickPositioner;
}
}
}
if (!this.isLinked) {
// reset min/max or remove extremes based on start/end on tick
this.trimTicks(tickPositions, startOnTick, endOnTick);
// When there is only one point, or all points have the same value on this axis, then min
// and max are equal and tickPositions.length is 0 or 1. In this case, add some padding
// in order to center the point, but leave it with one tick. #1337.
if (this.min === this.max && defined(this.min) && !this.tickAmount) {
// Substract half a unit (#2619, #2846, #2515, #3390)
single = true;
this.min -= 0.5;
this.max += 0.5;
}
this.single = single;
if (!tickPositionsOption && !tickPositioner) {
this.adjustTickAmount();
}
}
},
/**
* Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max
*/
trimTicks: function(tickPositions, startOnTick, endOnTick) {
var roundedMin = tickPositions[0],
roundedMax = tickPositions[tickPositions.length - 1],
minPointOffset = this.minPointOffset || 0;
if (startOnTick) {
this.min = roundedMin;
} else {
while (this.min - minPointOffset > tickPositions[0]) {
tickPositions.shift();
}
}
if (endOnTick) {
this.max = roundedMax;
} else {
while (this.max + minPointOffset < tickPositions[tickPositions.length - 1]) {
tickPositions.pop();
}
}
// If no tick are left, set one tick in the middle (#3195)
if (tickPositions.length === 0 && defined(roundedMin)) {
tickPositions.push((roundedMax + roundedMin) / 2);
}
},
/**
* Check if there are multiple axes in the same pane
* @returns {Boolean} There are other axes
*/
alignToOthers: function() {
var others = {}, // Whether there is another axis to pair with this one
hasOther,
options = this.options;
if (this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) {
each(this.chart[this.coll], function(axis) {
var otherOptions = axis.options,
horiz = axis.horiz,
key = [
horiz ? otherOptions.left : otherOptions.top,
otherOptions.width,
otherOptions.height,
otherOptions.pane
].join(',');
if (axis.series.length) { // #4442
if (others[key]) {
hasOther = true; // #4201
} else {
others[key] = 1;
}
}
});
}
return hasOther;
},
/**
* Set the max ticks of either the x and y axis collection
*/
getTickAmount: function() {
var options = this.options,
tickAmount = options.tickAmount,
tickPixelInterval = options.tickPixelInterval;
if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial &&
!this.isLog && options.startOnTick && options.endOnTick) {
tickAmount = 2;
}
if (!tickAmount && this.alignToOthers()) {
// Add 1 because 4 tick intervals require 5 ticks (including first and last)
tickAmount = Math.ceil(this.len / tickPixelInterval) + 1;
}
// For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This
// prevents the axis from adding ticks that are too far away from the data extremes.
if (tickAmount < 4) {
this.finalTickAmt = tickAmount;
tickAmount = 5;
}
this.tickAmount = tickAmount;
},
/**
* When using multiple axes, adjust the number of ticks to match the highest
* number of ticks in that group
*/
adjustTickAmount: function() {
var tickInterval = this.tickInterval,
tickPositions = this.tickPositions,
tickAmount = this.tickAmount,
finalTickAmt = this.finalTickAmt,
currentTickAmount = tickPositions && tickPositions.length,
i,
len;
if (currentTickAmount < tickAmount) {
while (tickPositions.length < tickAmount) {
tickPositions.push(correctFloat(
tickPositions[tickPositions.length - 1] + tickInterval
));
}
this.transA *= (currentTickAmount - 1) / (tickAmount - 1);
this.max = tickPositions[tickPositions.length - 1];
// We have too many ticks, run second pass to try to reduce ticks
} else if (currentTickAmount > tickAmount) {
this.tickInterval *= 2;
this.setTickPositions();
}
// The finalTickAmt property is set in getTickAmount
if (defined(finalTickAmt)) {
i = len = tickPositions.length;
while (i--) {
if (
(finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick
(finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last
) {
tickPositions.splice(i, 1);
}
}
this.finalTickAmt = undefined;
}
},
/**
* Set the scale based on data min and max, user set min and max or options
*
*/
setScale: function() {
var axis = this,
isDirtyData,
isDirtyAxisLength;
axis.oldMin = axis.min;
axis.oldMax = axis.max;
axis.oldAxisLength = axis.len;
// set the new axisLength
axis.setAxisSize();
//axisLength = horiz ? axisWidth : axisHeight;
isDirtyAxisLength = axis.len !== axis.oldAxisLength;
// is there new data?
each(axis.series, function(series) {
if (series.isDirtyData || series.isDirty ||
series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
isDirtyData = true;
}
});
// do we really need to go through all this?
if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax || axis.alignToOthers()) {
if (axis.resetStacks) {
axis.resetStacks();
}
axis.forceRedraw = false;
// get data extremes if needed
axis.getSeriesExtremes();
// get fixed positions based on tickInterval
axis.setTickInterval();
// record old values to decide whether a rescale is necessary later on (#540)
axis.oldUserMin = axis.userMin;
axis.oldUserMax = axis.userMax;
// Mark as dirty if it is not already set to dirty and extremes have changed. #595.
if (!axis.isDirty) {
axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
}
} else if (axis.cleanStacks) {
axis.cleanStacks();
}
},
/**
* Set the extremes and optionally redraw
* @param {Number} newMin
* @param {Number} newMax
* @param {Boolean} redraw
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
* @param {Object} eventArguments
*
*/
setExtremes: function(newMin, newMax, redraw, animation, eventArguments) {
var axis = this,
chart = axis.chart;
redraw = pick(redraw, true); // defaults to true
each(axis.series, function(serie) {
delete serie.kdTree;
});
// Extend the arguments with min and max
eventArguments = extend(eventArguments, {
min: newMin,
max: newMax
});
// Fire the event
fireEvent(axis, 'setExtremes', eventArguments, function() { // the default event handler
axis.userMin = newMin;
axis.userMax = newMax;
axis.eventArgs = eventArguments;
if (redraw) {
chart.redraw(animation);
}
});
},
/**
* Overridable method for zooming chart. Pulled out in a separate method to allow overriding
* in stock charts.
*/
zoom: function(newMin, newMax) {
var dataMin = this.dataMin,
dataMax = this.dataMax,
options = this.options,
min = Math.min(dataMin, pick(options.min, dataMin)),
max = Math.max(dataMax, pick(options.max, dataMax));
if (newMin !== this.min || newMax !== this.max) { // #5790
// Prevent pinch zooming out of range. Check for defined is for #1946. #1734.
if (!this.allowZoomOutside) {
if (defined(dataMin) && newMin <= min) {
newMin = min;
}
if (defined(dataMax) && newMax >= max) {
newMax = max;
}
}
// In full view, displaying the reset zoom button is not required
this.displayBtn = newMin !== undefined || newMax !== undefined;
// Do it
this.setExtremes(
newMin,
newMax,
false,
undefined, {
trigger: 'zoom'
}
);
}
return true;
},
/**
* Update the axis metrics
*/
setAxisSize: function() {
var chart = this.chart,
options = this.options,
offsetLeft = options.offsetLeft || 0,
offsetRight = options.offsetRight || 0,
horiz = this.horiz,
width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight),
height = pick(options.height, chart.plotHeight),
top = pick(options.top, chart.plotTop),
left = pick(options.left, chart.plotLeft + offsetLeft),
percentRegex = /%$/;
// Check for percentage based input values. Rounding fixes problems with
// column overflow and plot line filtering (#4898, #4899)
if (percentRegex.test(height)) {
height = Math.round(parseFloat(height) / 100 * chart.plotHeight);
}
if (percentRegex.test(top)) {
top = Math.round(parseFloat(top) / 100 * chart.plotHeight + chart.plotTop);
}
// Expose basic values to use in Series object and navigator
this.left = left;
this.top = top;
this.width = width;
this.height = height;
this.bottom = chart.chartHeight - height - top;
this.right = chart.chartWidth - width - left;
// Direction agnostic properties
this.len = Math.max(horiz ? width : height, 0); // Math.max fixes #905
this.pos = horiz ? left : top; // distance from SVG origin
},
/**
* Get the actual axis extremes
*/
getExtremes: function() {
var axis = this,
isLog = axis.isLog,
lin2log = axis.lin2log;
return {
min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
dataMin: axis.dataMin,
dataMax: axis.dataMax,
userMin: axis.userMin,
userMax: axis.userMax
};
},
/**
* Get the zero plane either based on zero or on the min or max value.
* Used in bar and area plots
*/
getThreshold: function(threshold) {
var axis = this,
isLog = axis.isLog,
lin2log = axis.lin2log,
realMin = isLog ? lin2log(axis.min) : axis.min,
realMax = isLog ? lin2log(axis.max) : axis.max;
if (threshold === null) {
threshold = realMin;
} else if (realMin > threshold) {
threshold = realMin;
} else if (realMax < threshold) {
threshold = realMax;
}
return axis.translate(threshold, 0, 1, 0, 1);
},
/**
* Compute auto alignment for the axis label based on which side the axis is on
* and the given rotation for the label
*/
autoLabelAlign: function(rotation) {
var ret,
angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
if (angle > 15 && angle < 165) {
ret = 'right';
} else if (angle > 195 && angle < 345) {
ret = 'left';
} else {
ret = 'center';
}
return ret;
},
/**
* Get the tick length and width for the axis.
* @param {String} prefix 'tick' or 'minorTick'
* @returns {Array} An array of tickLength and tickWidth
*/
tickSize: function(prefix) {
var options = this.options,
tickLength = options[prefix + 'Length'],
tickWidth = pick(options[prefix + 'Width'], prefix === 'tick' && this.isXAxis ? 1 : 0); // X axis defaults to 1
if (tickWidth && tickLength) {
// Negate the length
if (options[prefix + 'Position'] === 'inside') {
tickLength = -tickLength;
}
return [tickLength, tickWidth];
}
},
/**
* Return the size of the labels
*/
labelMetrics: function() {
return this.chart.renderer.fontMetrics(
this.options.labels.style && this.options.labels.style.fontSize,
this.ticks[0] && this.ticks[0].label
);
},
/**
* Prevent the ticks from getting so close we can't draw the labels. On a horizontal
* axis, this is handled by rotating the labels, removing ticks and adding ellipsis.
* On a vertical axis remove ticks and add ellipsis.
*/
unsquish: function() {
var labelOptions = this.options.labels,
horiz = this.horiz,
tickInterval = this.tickInterval,
newTickInterval = tickInterval,
slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval),
rotation,
rotationOption = labelOptions.rotation,
labelMetrics = this.labelMetrics(),
step,
bestScore = Number.MAX_VALUE,
autoRotation,
// Return the multiple of tickInterval that is needed to avoid collision
getStep = function(spaceNeeded) {
var step = spaceNeeded / (slotSize || 1);
step = step > 1 ? Math.ceil(step) : 1;
return step * tickInterval;
};
if (horiz) {
autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971
defined(rotationOption) ? [rotationOption] :
slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation
);
if (autoRotation) {
// Loop over the given autoRotation options, and determine which gives the best score. The
// best score is that with the lowest number of steps and a rotation closest to horizontal.
each(autoRotation, function(rot) {
var score;
if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891
step = getStep(Math.abs(labelMetrics.h / Math.sin(deg2rad * rot)));
score = step + Math.abs(rot / 360);
if (score < bestScore) {
bestScore = score;
rotation = rot;
newTickInterval = step;
}
}
});
}
} else if (!labelOptions.step) { // #4411
newTickInterval = getStep(labelMetrics.h);
}
this.autoRotation = autoRotation;
this.labelRotation = pick(rotation, rotationOption);
return newTickInterval;
},
/**
* Get the general slot width for this axis. This may change between the pre-render (from Axis.getOffset)
* and the final tick rendering and placement (#5086).
*/
getSlotWidth: function() {
var chart = this.chart,
horiz = this.horiz,
labelOptions = this.options.labels,
slotCount = Math.max(this.tickPositions.length - (this.categories ? 0 : 1), 1),
marginLeft = chart.margin[3];
return (horiz && (labelOptions.step || 0) < 2 && !labelOptions.rotation && // #4415
((this.staggerLines || 1) * chart.plotWidth) / slotCount) ||
(!horiz && ((marginLeft && (marginLeft - chart.spacing[3])) || chart.chartWidth * 0.33)); // #1580, #1931
},
/**
* Render the axis labels and determine whether ellipsis or rotation need to be applied
*/
renderUnsquish: function() {
var chart = this.chart,
renderer = chart.renderer,
tickPositions = this.tickPositions,
ticks = this.ticks,
labelOptions = this.options.labels,
horiz = this.horiz,
slotWidth = this.getSlotWidth(),
innerWidth = Math.max(1, Math.round(slotWidth - 2 * (labelOptions.padding || 5))),
attr = {},
labelMetrics = this.labelMetrics(),
textOverflowOption = labelOptions.style && labelOptions.style.textOverflow,
css,
maxLabelLength = 0,
label,
i,
pos;
// Set rotation option unless it is "auto", like in gauges
if (!isString(labelOptions.rotation)) {
attr.rotation = labelOptions.rotation || 0; // #4443
}
// Get the longest label length
each(tickPositions, function(tick) {
tick = ticks[tick];
if (tick && tick.labelLength > maxLabelLength) {
maxLabelLength = tick.labelLength;
}
});
this.maxLabelLength = maxLabelLength;
// Handle auto rotation on horizontal axis
if (this.autoRotation) {
// Apply rotation only if the label is too wide for the slot, and
// the label is wider than its height.
if (maxLabelLength > innerWidth && maxLabelLength > labelMetrics.h) {
attr.rotation = this.labelRotation;
} else {
this.labelRotation = 0;
}
// Handle word-wrap or ellipsis on vertical axis
} else if (slotWidth) {
// For word-wrap or ellipsis
css = {
width: innerWidth + 'px'
};
if (!textOverflowOption) {
css.textOverflow = 'clip';
// On vertical axis, only allow word wrap if there is room for more lines.
i = tickPositions.length;
while (!horiz && i--) {
pos = tickPositions[i];
label = ticks[pos].label;
if (label) {
// Reset ellipsis in order to get the correct bounding box (#4070)
if (label.styles && label.styles.textOverflow === 'ellipsis') {
label.css({
textOverflow: 'clip'
});
// Set the correct width in order to read the bounding box height (#4678, #5034)
} else if (ticks[pos].labelLength > slotWidth) {
label.css({
width: slotWidth + 'px'
});
}
if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) {
label.specCss = {
textOverflow: 'ellipsis'
};
}
}
}
}
}
// Add ellipsis if the label length is significantly longer than ideal
if (attr.rotation) {
css = {
width: (maxLabelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + 'px'
};
if (!textOverflowOption) {
css.textOverflow = 'ellipsis';
}
}
// Set the explicit or automatic label alignment
this.labelAlign = labelOptions.align || this.autoLabelAlign(this.labelRotation);
if (this.labelAlign) {
attr.align = this.labelAlign;
}
// Apply general and specific CSS
each(tickPositions, function(pos) {
var tick = ticks[pos],
label = tick && tick.label;
if (label) {
label.attr(attr); // This needs to go before the CSS in old IE (#4502)
if (css) {
label.css(merge(css, label.specCss));
}
delete label.specCss;
tick.rotation = attr.rotation;
}
});
// Note: Why is this not part of getLabelPosition?
this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side !== 0);
},
/**
* Return true if the axis has associated data
*/
hasData: function() {
return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions);
},
/**
* Render the tick labels to a preliminary position to get their sizes
*/
getOffset: function() {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
tickPositions = axis.tickPositions,
ticks = axis.ticks,
horiz = axis.horiz,
side = axis.side,
invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
hasData,
showAxis,
titleOffset = 0,
titleOffsetOption,
titleMargin = 0,
axisTitleOptions = options.title,
labelOptions = options.labels,
labelOffset = 0, // reset
labelOffsetPadded,
opposite = axis.opposite,
axisOffset = chart.axisOffset,
clipOffset = chart.clipOffset,
clip,
directionFactor = [-1, 1, 1, -1][side],
n,
className = options.className,
textAlign,
axisParent = axis.axisParent, // Used in color axis
lineHeightCorrection,
tickSize = this.tickSize('tick');
// For reuse in Axis.render
hasData = axis.hasData();
axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
// Set/reset staggerLines
axis.staggerLines = axis.horiz && labelOptions.staggerLines;
// Create the axisGroup and gridGroup elements on first iteration
if (!axis.axisGroup) {
axis.gridGroup = renderer.g('grid')
.attr({
zIndex: options.gridZIndex || 1
})
.addClass('highcharts-' + this.coll.toLowerCase() + '-grid ' + (className || ''))
.add(axisParent);
axis.axisGroup = renderer.g('axis')
.attr({
zIndex: options.zIndex || 2
})
.addClass('highcharts-' + this.coll.toLowerCase() + ' ' + (className || ''))
.add(axisParent);
axis.labelGroup = renderer.g('axis-labels')
.attr({
zIndex: labelOptions.zIndex || 7
})
.addClass('highcharts-' + axis.coll.toLowerCase() + '-labels ' + (className || ''))
.add(axisParent);
}
if (hasData || axis.isLinked) {
// Generate ticks
each(tickPositions, function(pos) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
} else {
ticks[pos].addLabel(); // update labels depending on tick interval
}
});
axis.renderUnsquish();
// Left side must be align: right and right side must have align: left for labels
if (labelOptions.reserveSpace !== false && (side === 0 || side === 2 || {
1: 'left',
3: 'right'
}[side] === axis.labelAlign || axis.labelAlign === 'center')) {
each(tickPositions, function(pos) {
// get the highest offset
labelOffset = Math.max(
ticks[pos].getLabelSize(),
labelOffset
);
});
}
if (axis.staggerLines) {
labelOffset *= axis.staggerLines;
axis.labelOffset = labelOffset * (axis.opposite ? -1 : 1);
}
} else { // doesn't have data
for (n in ticks) {
ticks[n].destroy();
delete ticks[n];
}
}
if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
if (!axis.axisTitle) {
textAlign = axisTitleOptions.textAlign;
if (!textAlign) {
textAlign = (horiz ? {
low: 'left',
middle: 'center',
high: 'right'
} : {
low: opposite ? 'right' : 'left',
middle: 'center',
high: opposite ? 'left' : 'right'
})[axisTitleOptions.align];
}
axis.axisTitle = renderer.text(
axisTitleOptions.text,
0,
0,
axisTitleOptions.useHTML
)
.attr({
zIndex: 7,
rotation: axisTitleOptions.rotation || 0,
align: textAlign
})
.addClass('highcharts-axis-title')
.add(axis.axisGroup);
axis.axisTitle.isNew = true;
}
if (showAxis) {
titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
titleOffsetOption = axisTitleOptions.offset;
titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10);
}
// hide or show the title depending on whether showEmpty is set
axis.axisTitle[showAxis ? 'show' : 'hide'](true);
}
// Render the axis line
axis.renderLine();
// handle automatic or user set offset
axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
axis.tickRotCorr = axis.tickRotCorr || {
x: 0,
y: 0
}; // polar
if (side === 0) {
lineHeightCorrection = -axis.labelMetrics().h;
} else if (side === 2) {
lineHeightCorrection = axis.tickRotCorr.y;
} else {
lineHeightCorrection = 0;
}
// Find the padded label offset
labelOffsetPadded = Math.abs(labelOffset) + titleMargin;
if (labelOffset) {
labelOffsetPadded -= lineHeightCorrection;
labelOffsetPadded += directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + directionFactor * 8) : labelOptions.x);
}
axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded);
axisOffset[side] = Math.max(
axisOffset[side],
axis.axisTitleMargin + titleOffset + directionFactor * axis.offset,
labelOffsetPadded, // #3027
hasData && tickPositions.length && tickSize ? tickSize[0] : 0 // #4866
);
// Decide the clipping needed to keep the graph inside the plot area and axis lines
clip = options.offset ? 0 : Math.floor(axis.axisLine.strokeWidth() / 2) * 2; // #4308, #4371
clipOffset[invertedSide] = Math.max(clipOffset[invertedSide], clip);
},
/**
* Get the path for the axis line
*/
getLinePath: function(lineWidth) {
var chart = this.chart,
opposite = this.opposite,
offset = this.offset,
horiz = this.horiz,
lineLeft = this.left + (opposite ? this.width : 0) + offset,
lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
if (opposite) {
lineWidth *= -1; // crispify the other way - #1480, #1687
}
return chart.renderer
.crispLine([
'M',
horiz ?
this.left :
lineLeft,
horiz ?
lineTop :
this.top,
'L',
horiz ?
chart.chartWidth - this.right :
lineLeft,
horiz ?
lineTop :
chart.chartHeight - this.bottom
], lineWidth);
},
/**
* Render the axis line
* @returns {[type]} [description]
*/
renderLine: function() {
if (!this.axisLine) {
this.axisLine = this.chart.renderer.path()
.addClass('highcharts-axis-line')
.add(this.axisGroup);
}
},
/**
* Position the title
*/
getTitlePosition: function() {
// compute anchor points for each of the title align options
var horiz = this.horiz,
axisLeft = this.left,
axisTop = this.top,
axisLength = this.len,
axisTitleOptions = this.options.title,
margin = horiz ? axisLeft : axisTop,
opposite = this.opposite,
offset = this.offset,
xOption = axisTitleOptions.x || 0,
yOption = axisTitleOptions.y || 0,
fontSize = this.chart.renderer.fontMetrics(axisTitleOptions.style && axisTitleOptions.style.fontSize, this.axisTitle).f,
// the position in the length direction of the axis
alongAxis = {
low: margin + (horiz ? 0 : axisLength),
middle: margin + axisLength / 2,
high: margin + (horiz ? axisLength : 0)
}[axisTitleOptions.align],
// the position in the perpendicular direction of the axis
offAxis = (horiz ? axisTop + this.height : axisLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
this.axisTitleMargin +
(this.side === 2 ? fontSize : 0);
return {
x: horiz ?
alongAxis + xOption : offAxis + (opposite ? this.width : 0) + offset + xOption,
y: horiz ?
offAxis + yOption - (opposite ? this.height : 0) + offset : alongAxis + yOption
};
},
/**
* Render the axis
*/
render: function() {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
isLog = axis.isLog,
lin2log = axis.lin2log,
isLinked = axis.isLinked,
tickPositions = axis.tickPositions,
axisTitle = axis.axisTitle,
ticks = axis.ticks,
minorTicks = axis.minorTicks,
alternateBands = axis.alternateBands,
stackLabelOptions = options.stackLabels,
alternateGridColor = options.alternateGridColor,
tickmarkOffset = axis.tickmarkOffset,
axisLine = axis.axisLine,
hasRendered = chart.hasRendered,
slideInTicks = hasRendered && isNumber(axis.oldMin),
showAxis = axis.showAxis,
animation = animObject(renderer.globalAnimation),
from,
to;
// Reset
axis.labelEdge.length = 0;
//axis.justifyToPlot = overflow === 'justify';
axis.overlap = false;
// Mark all elements inActive before we go over and mark the active ones
each([ticks, minorTicks, alternateBands], function(coll) {
var pos;
for (pos in coll) {
coll[pos].isActive = false;
}
});
// If the series has data draw the ticks. Else only the line and title
if (axis.hasData() || isLinked) {
// minor ticks
if (axis.minorTickInterval && !axis.categories) {
each(axis.getMinorTickPositions(), function(pos) {
if (!minorTicks[pos]) {
minorTicks[pos] = new Tick(axis, pos, 'minor');
}
// render new ticks in old position
if (slideInTicks && minorTicks[pos].isNew) {
minorTicks[pos].render(null, true);
}
minorTicks[pos].render(null, false, 1);
});
}
// Major ticks. Pull out the first item and render it last so that
// we can get the position of the neighbour label. #808.
if (tickPositions.length) { // #1300
each(tickPositions, function(pos, i) {
// linked axes need an extra check to find out if
if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
}
// render new ticks in old position
if (slideInTicks && ticks[pos].isNew) {
ticks[pos].render(i, true, 0.1);
}
ticks[pos].render(i);
}
});
// In a categorized axis, the tick marks are displayed between labels. So
// we need to add a tick mark and grid line at the left edge of the X axis.
if (tickmarkOffset && (axis.min === 0 || axis.single)) {
if (!ticks[-1]) {
ticks[-1] = new Tick(axis, -1, null, true);
}
ticks[-1].render(-1);
}
}
// alternate grid color
if (alternateGridColor) {
each(tickPositions, function(pos, i) {
to = tickPositions[i + 1] !== undefined ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset;
if (i % 2 === 0 && pos < axis.max && to <= axis.max + (chart.polar ? -tickmarkOffset : tickmarkOffset)) { // #2248, #4660
if (!alternateBands[pos]) {
alternateBands[pos] = new PlotLineOrBand(axis);
}
from = pos + tickmarkOffset; // #949
alternateBands[pos].options = {
from: isLog ? lin2log(from) : from,
to: isLog ? lin2log(to) : to,
color: alternateGridColor
};
alternateBands[pos].render();
alternateBands[pos].isActive = true;
}
});
}
// custom plot lines and bands
if (!axis._addedPlotLB) { // only first time
each((options.plotLines || []).concat(options.plotBands || []), function(plotLineOptions) {
axis.addPlotBandOrLine(plotLineOptions);
});
axis._addedPlotLB = true;
}
} // end if hasData
// Remove inactive ticks
each([ticks, minorTicks, alternateBands], function(coll) {
var pos,
i,
forDestruction = [],
delay = animation.duration,
destroyInactiveItems = function() {
i = forDestruction.length;
while (i--) {
// When resizing rapidly, the same items may be destroyed in different timeouts,
// or the may be reactivated
if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
coll[forDestruction[i]].destroy();
delete coll[forDestruction[i]];
}
}
};
for (pos in coll) {
if (!coll[pos].isActive) {
// Render to zero opacity
coll[pos].render(pos, false, 0);
coll[pos].isActive = false;
forDestruction.push(pos);
}
}
// When the objects are finished fading out, destroy them
syncTimeout(
destroyInactiveItems,
coll === alternateBands || !chart.hasRendered || !delay ? 0 : delay
);
});
// Set the axis line path
if (axisLine) {
axisLine[axisLine.isPlaced ? 'animate' : 'attr']({
d: this.getLinePath(axisLine.strokeWidth())
});
axisLine.isPlaced = true;
// Show or hide the line depending on options.showEmpty
axisLine[showAxis ? 'show' : 'hide'](true);
}
if (axisTitle && showAxis) {
axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
axis.getTitlePosition()
);
axisTitle.isNew = false;
}
// Stacked totals:
if (stackLabelOptions && stackLabelOptions.enabled) {
axis.renderStackTotals();
}
// End stacked totals
axis.isDirty = false;
},
/**
* Redraw the axis to reflect changes in the data or axis extremes
*/
redraw: function() {
if (this.visible) {
// render the axis
this.render();
// move plot lines and bands
each(this.plotLinesAndBands, function(plotLine) {
plotLine.render();
});
}
// mark associated series as dirty and ready for redraw
each(this.series, function(series) {
series.isDirty = true;
});
},
/**
* Destroys an Axis instance.
*/
destroy: function(keepEvents) {
var axis = this,
stacks = axis.stacks,
stackKey,
plotLinesAndBands = axis.plotLinesAndBands,
i,
n,
keepProps;
// Remove the events
if (!keepEvents) {
removeEvent(axis);
}
// Destroy each stack total
for (stackKey in stacks) {
destroyObjectProperties(stacks[stackKey]);
stacks[stackKey] = null;
}
// Destroy collections
each([axis.ticks, axis.minorTicks, axis.alternateBands], function(coll) {
destroyObjectProperties(coll);
});
if (plotLinesAndBands) {
i = plotLinesAndBands.length;
while (i--) { // #1975
plotLinesAndBands[i].destroy();
}
}
// Destroy local variables
each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'gridGroup', 'labelGroup', 'cross'], function(prop) {
if (axis[prop]) {
axis[prop] = axis[prop].destroy();
}
});
// Delete all properties and fall back to the prototype.
// Preserve some properties, needed for Axis.update (#4317, #5773).
keepProps = ['extKey', 'hcEvents', 'names', 'series', 'userMax', 'userMin'];
for (n in axis) {
if (axis.hasOwnProperty(n) && inArray(n, keepProps) === -1) {
delete axis[n];
}
}
},
/**
* Draw the crosshair
*
* @param {Object} e The event arguments from the modified pointer event
* @param {Object} point The Point object
*/
drawCrosshair: function(e, point) {
var path,
options = this.crosshair,
snap = pick(options.snap, true),
pos,
categorized,
graphic = this.cross;
// Use last available event when updating non-snapped crosshairs without
// mouse interaction (#5287)
if (!e) {
e = this.cross && this.cross.e;
}
if (
// Disabled in options
!this.crosshair ||
// Snap
((defined(point) || !snap) === false)
) {
this.hideCrosshair();
} else {
// Get the path
if (!snap) {
pos = e && (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
} else if (defined(point)) {
pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834
}
if (defined(pos)) {
path = this.getPlotLinePath(
// First argument, value, only used on radial
point && (this.isXAxis ? point.x : pick(point.stackY, point.y)),
null,
null,
null,
pos // Translated position
) || null; // #3189
}
if (!defined(path)) {
this.hideCrosshair();
return;
}
categorized = this.categories && !this.isRadial;
// Draw the cross
if (!graphic) {
this.cross = graphic = this.chart.renderer
.path()
.addClass('highcharts-crosshair highcharts-crosshair-' +
(categorized ? 'category ' : 'thin ') + options.className)
.attr({
zIndex: pick(options.zIndex, 2)
})
.add();
}
graphic.show().attr({
d: path
});
if (categorized && !options.width) {
graphic.attr({
'stroke-width': this.transA
});
}
this.cross.e = e;
}
},
/**
* Hide the crosshair.
*/
hideCrosshair: function() {
if (this.cross) {
this.cross.hide();
}
}
}; // end Axis
extend(H.Axis.prototype, AxisPlotLineOrBandExtension);
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Axis = H.Axis,
getMagnitude = H.getMagnitude,
map = H.map,
normalizeTickInterval = H.normalizeTickInterval,
pick = H.pick;
/**
* Methods defined on the Axis prototype
*/
/**
* Set the tick positions of a logarithmic axis
*/
Axis.prototype.getLogTickPositions = function(interval, min, max, minor) {
var axis = this,
options = axis.options,
axisLength = axis.len,
lin2log = axis.lin2log,
log2lin = axis.log2lin,
// Since we use this method for both major and minor ticks,
// use a local variable and return the result
positions = [];
// Reset
if (!minor) {
axis._minorAutoInterval = null;
}
// First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
if (interval >= 0.5) {
interval = Math.round(interval);
positions = axis.getLinearTickPositions(interval, min, max);
// Second case: We need intermediary ticks. For example
// 1, 2, 4, 6, 8, 10, 20, 40 etc.
} else if (interval >= 0.08) {
var roundedMin = Math.floor(min),
intermediate,
i,
j,
len,
pos,
lastPos,
break2;
if (interval > 0.3) {
intermediate = [1, 2, 4];
} else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 4, 6, 8];
} else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
for (i = roundedMin; i < max + 1 && !break2; i++) {
len = intermediate.length;
for (j = 0; j < len && !break2; j++) {
pos = log2lin(lin2log(i) * intermediate[j]);
if (pos > min && (!minor || lastPos <= max) && lastPos !== undefined) { // #1670, lastPos is #3113
positions.push(lastPos);
}
if (lastPos > max) {
break2 = true;
}
lastPos = pos;
}
}
// Third case: We are so deep in between whole logarithmic values that
// we might as well handle the tick positions like a linear axis. For
// example 1.01, 1.02, 1.03, 1.04.
} else {
var realMin = lin2log(min),
realMax = lin2log(max),
tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
interval = pick(
filteredTickIntervalOption,
axis._minorAutoInterval,
(realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
);
interval = normalizeTickInterval(
interval,
null,
getMagnitude(interval)
);
positions = map(axis.getLinearTickPositions(
interval,
realMin,
realMax
), log2lin);
if (!minor) {
axis._minorAutoInterval = interval / 5;
}
}
// Set the axis-level tickInterval variable
if (!minor) {
axis.tickInterval = interval;
}
return positions;
};
Axis.prototype.log2lin = function(num) {
return Math.log(num) / Math.LN10;
};
Axis.prototype.lin2log = function(num) {
return Math.pow(10, num);
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var dateFormat = H.dateFormat,
each = H.each,
extend = H.extend,
format = H.format,
isNumber = H.isNumber,
map = H.map,
merge = H.merge,
pick = H.pick,
splat = H.splat,
stop = H.stop,
syncTimeout = H.syncTimeout,
timeUnits = H.timeUnits;
/**
* The tooltip object
* @param {Object} chart The chart instance
* @param {Object} options Tooltip options
*/
H.Tooltip = function() {
this.init.apply(this, arguments);
};
H.Tooltip.prototype = {
init: function(chart, options) {
// Save the chart and options
this.chart = chart;
this.options = options;
// Keep track of the current series
//this.currentSeries = undefined;
// List of crosshairs
this.crosshairs = [];
// Current values of x and y when animating
this.now = {
x: 0,
y: 0
};
// The tooltip is initially hidden
this.isHidden = true;
// Public property for getting the shared state.
this.split = options.split && !chart.inverted;
this.shared = options.shared || this.split;
},
/**
* Destroy the single tooltips in a split tooltip.
* If the tooltip is active then it is not destroyed, unless forced to.
* @param {boolean} force Force destroy all tooltips.
* @return {undefined}
*/
cleanSplit: function(force) {
each(this.chart.series, function(series) {
var tt = series && series.tt;
if (tt) {
if (!tt.isActive || force) {
series.tt = tt.destroy();
} else {
tt.isActive = false;
}
}
});
},
/**
* Create the Tooltip label element if it doesn't exist, then return the
* label.
*/
getLabel: function() {
var renderer = this.chart.renderer,
options = this.options;
if (!this.label) {
// Create the label
if (this.split) {
this.label = renderer.g('tooltip');
} else {
this.label = renderer.label(
'',
0,
0,
options.shape || 'callout',
null,
null,
options.useHTML,
null,
'tooltip'
)
.attr({
padding: options.padding,
r: options.borderRadius
});
}
this.label
.attr({
zIndex: 8
})
.add();
}
return this.label;
},
update: function(options) {
this.destroy();
this.init(this.chart, merge(true, this.options, options));
},
/**
* Destroy the tooltip and its elements.
*/
destroy: function() {
// Destroy and clear local variables
if (this.label) {
this.label = this.label.destroy();
}
if (this.split && this.tt) {
this.cleanSplit(this.chart, true);
this.tt = this.tt.destroy();
}
clearTimeout(this.hideTimer);
clearTimeout(this.tooltipTimeout);
},
/**
* Provide a soft movement for the tooltip
*
* @param {Number} x
* @param {Number} y
* @private
*/
move: function(x, y, anchorX, anchorY) {
var tooltip = this,
now = tooltip.now,
animate = tooltip.options.animation !== false && !tooltip.isHidden &&
// When we get close to the target position, abort animation and land on the right place (#3056)
(Math.abs(x - now.x) > 1 || Math.abs(y - now.y) > 1),
skipAnchor = tooltip.followPointer || tooltip.len > 1;
// Get intermediate values for animation
extend(now, {
x: animate ? (2 * now.x + x) / 3 : x,
y: animate ? (now.y + y) / 2 : y,
anchorX: skipAnchor ? undefined : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
anchorY: skipAnchor ? undefined : animate ? (now.anchorY + anchorY) / 2 : anchorY
});
// Move to the intermediate value
tooltip.getLabel().attr(now);
// Run on next tick of the mouse tracker
if (animate) {
// Never allow two timeouts
clearTimeout(this.tooltipTimeout);
// Set the fixed interval ticking for the smooth tooltip
this.tooltipTimeout = setTimeout(function() {
// The interval function may still be running during destroy,
// so check that the chart is really there before calling.
if (tooltip) {
tooltip.move(x, y, anchorX, anchorY);
}
}, 32);
}
},
/**
* Hide the tooltip
*/
hide: function(delay) {
var tooltip = this;
clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
delay = pick(delay, this.options.hideDelay, 500);
if (!this.isHidden) {
this.hideTimer = syncTimeout(function() {
tooltip.getLabel()[delay ? 'fadeOut' : 'hide']();
tooltip.isHidden = true;
}, delay);
}
},
/**
* Extendable method to get the anchor position of the tooltip
* from a point or set of points
*/
getAnchor: function(points, mouseEvent) {
var ret,
chart = this.chart,
inverted = chart.inverted,
plotTop = chart.plotTop,
plotLeft = chart.plotLeft,
plotX = 0,
plotY = 0,
yAxis,
xAxis;
points = splat(points);
// Pie uses a special tooltipPos
ret = points[0].tooltipPos;
// When tooltip follows mouse, relate the position to the mouse
if (this.followPointer && mouseEvent) {
if (mouseEvent.chartX === undefined) {
mouseEvent = chart.pointer.normalize(mouseEvent);
}
ret = [
mouseEvent.chartX - chart.plotLeft,
mouseEvent.chartY - plotTop
];
}
// When shared, use the average position
if (!ret) {
each(points, function(point) {
yAxis = point.series.yAxis;
xAxis = point.series.xAxis;
plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0);
plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
(!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
});
plotX /= points.length;
plotY /= points.length;
ret = [
inverted ? chart.plotWidth - plotY : plotX,
this.shared && !inverted && points.length > 1 && mouseEvent ?
mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
inverted ? chart.plotHeight - plotX : plotY
];
}
return map(ret, Math.round);
},
/**
* Place the tooltip in a chart without spilling over
* and not covering the point it self.
*/
getPosition: function(boxWidth, boxHeight, point) {
var chart = this.chart,
distance = this.distance,
ret = {},
h = point.h || 0, // #4117
swapped,
first = ['y', chart.chartHeight, boxHeight,
point.plotY + chart.plotTop, chart.plotTop,
chart.plotTop + chart.plotHeight
],
second = ['x', chart.chartWidth, boxWidth,
point.plotX + chart.plotLeft, chart.plotLeft,
chart.plotLeft + chart.plotWidth
],
// The far side is right or bottom
preferFarSide = !this.followPointer && pick(point.ttBelow, !chart.inverted === !!point.negative), // #4984
/**
* Handle the preferred dimension. When the preferred dimension is tooltip
* on top or bottom of the point, it will look for space there.
*/
firstDimension = function(dim, outerSize, innerSize, point, min, max) {
var roomLeft = innerSize < point - distance,
roomRight = point + distance + innerSize < outerSize,
alignedLeft = point - distance - innerSize,
alignedRight = point + distance;
if (preferFarSide && roomRight) {
ret[dim] = alignedRight;
} else if (!preferFarSide && roomLeft) {
ret[dim] = alignedLeft;
} else if (roomLeft) {
ret[dim] = Math.min(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h);
} else if (roomRight) {
ret[dim] = Math.max(
min,
alignedRight + h + innerSize > outerSize ?
alignedRight :
alignedRight + h
);
} else {
return false;
}
},
/**
* Handle the secondary dimension. If the preferred dimension is tooltip
* on top or bottom of the point, the second dimension is to align the tooltip
* above the point, trying to align center but allowing left or right
* align within the chart box.
*/
secondDimension = function(dim, outerSize, innerSize, point) {
var retVal;
// Too close to the edge, return false and swap dimensions
if (point < distance || point > outerSize - distance) {
retVal = false;
// Align left/top
} else if (point < innerSize / 2) {
ret[dim] = 1;
// Align right/bottom
} else if (point > outerSize - innerSize / 2) {
ret[dim] = outerSize - innerSize - 2;
// Align center
} else {
ret[dim] = point - innerSize / 2;
}
return retVal;
},
/**
* Swap the dimensions
*/
swap = function(count) {
var temp = first;
first = second;
second = temp;
swapped = count;
},
run = function() {
if (firstDimension.apply(0, first) !== false) {
if (secondDimension.apply(0, second) === false && !swapped) {
swap(true);
run();
}
} else if (!swapped) {
swap(true);
run();
} else {
ret.x = ret.y = 0;
}
};
// Under these conditions, prefer the tooltip on the side of the point
if (chart.inverted || this.len > 1) {
swap();
}
run();
return ret;
},
/**
* In case no user defined formatter is given, this will be used. Note that the context
* here is an object holding point, series, x, y etc.
*
* @returns {String|Array<String>}
*/
defaultFormatter: function(tooltip) {
var items = this.points || splat(this),
s;
// Build the header
s = [tooltip.tooltipFooterHeaderFormatter(items[0])];
// build the values
s = s.concat(tooltip.bodyFormatter(items));
// footer
s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true));
return s;
},
/**
* Refresh the tooltip's text and position.
* @param {Object} point
*/
refresh: function(point, mouseEvent) {
var tooltip = this,
chart = tooltip.chart,
label = tooltip.getLabel(),
options = tooltip.options,
x,
y,
anchor,
textConfig = {},
text,
pointConfig = [],
formatter = options.formatter || tooltip.defaultFormatter,
hoverPoints = chart.hoverPoints,
shared = tooltip.shared,
currentSeries;
clearTimeout(this.hideTimer);
// get the reference point coordinates (pie charts use tooltipPos)
tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
anchor = tooltip.getAnchor(point, mouseEvent);
x = anchor[0];
y = anchor[1];
// shared tooltip, array is sent over
if (shared && !(point.series && point.series.noSharedTooltip)) {
// hide previous hoverPoints and set new
chart.hoverPoints = point;
if (hoverPoints) {
each(hoverPoints, function(point) {
point.setState();
});
}
each(point, function(item) {
item.setState('hover');
pointConfig.push(item.getLabelConfig());
});
textConfig = {
x: point[0].category,
y: point[0].y
};
textConfig.points = pointConfig;
this.len = pointConfig.length;
point = point[0];
// single point tooltip
} else {
textConfig = point.getLabelConfig();
}
text = formatter.call(textConfig, tooltip);
// register the current series
currentSeries = point.series;
this.distance = pick(currentSeries.tooltipOptions.distance, 16);
// update the inner HTML
if (text === false) {
this.hide();
} else {
// show it
if (tooltip.isHidden) {
stop(label);
label.attr({
opacity: 1
}).show();
}
// update text
if (tooltip.split) {
this.renderSplit(text, chart.hoverPoints);
} else {
label.attr({
text: text.join ? text.join('') : text
});
// Set the stroke color of the box to reflect the point
label.removeClass(/highcharts-color-[\d]+/g)
.addClass('highcharts-color-' + pick(point.colorIndex, currentSeries.colorIndex));
tooltip.updatePosition({
plotX: x,
plotY: y,
negative: point.negative,
ttBelow: point.ttBelow,
h: anchor[2] || 0
});
}
this.isHidden = false;
}
},
/**
* Render the split tooltip. Loops over each point's text and adds
* a label next to the point, then uses the distribute function to
* find best non-overlapping positions.
*/
renderSplit: function(labels, points) {
var tooltip = this,
boxes = [],
chart = this.chart,
ren = chart.renderer,
rightAligned = true,
options = this.options,
headerHeight,
tooltipLabel = this.getLabel();
// Create the individual labels
each(labels.slice(0, labels.length - 1), function(str, i) {
var point = points[i - 1] ||
// Item 0 is the header. Instead of this, we could also use the crosshair label
{
isHeader: true,
plotX: points[0].plotX
},
owner = point.series || tooltip,
tt = owner.tt,
series = point.series || {},
colorClass = 'highcharts-color-' + pick(point.colorIndex, series.colorIndex, 'none'),
target,
x,
bBox,
boxWidth;
// Store the tooltip referance on the series
if (!tt) {
owner.tt = tt = ren.label(null, null, null, point.isHeader && 'callout')
.addClass('highcharts-tooltip-box ' + colorClass)
.attr({
'padding': options.padding,
'r': options.borderRadius
})
.add(tooltipLabel);
// Add a connector back to the point
if (point.series) {
tt.connector = ren.path()
.addClass('highcharts-tooltip-connector ' + colorClass)
// Add it inside the label group so we will get hide and
// destroy for free
.add(tt);
}
}
tt.isActive = true;
tt.attr({
text: str
});
// Get X position now, so we can move all to the other side in case of overflow
bBox = tt.getBBox();
boxWidth = bBox.width + tt.strokeWidth();
if (point.isHeader) {
headerHeight = bBox.height;
x = Math.max(
0, // No left overflow
Math.min(
point.plotX + chart.plotLeft - boxWidth / 2,
chart.chartWidth - boxWidth // No right overflow (#5794)
)
);
} else {
x = point.plotX + chart.plotLeft - pick(options.distance, 16) -
boxWidth;
}
// If overflow left, we don't use this x in the next loop
if (x < 0) {
rightAligned = false;
}
// Prepare for distribution
target = (point.series && point.series.yAxis && point.series.yAxis.pos) + (point.plotY || 0);
target -= chart.plotTop;
boxes.push({
target: point.isHeader ? chart.plotHeight + headerHeight : target,
rank: point.isHeader ? 1 : 0,
size: owner.tt.getBBox().height + 1,
point: point,
x: x,
tt: tt
});
});
// Clean previous run (for missing points)
this.cleanSplit();
// Distribute and put in place
H.distribute(boxes, chart.plotHeight + headerHeight);
each(boxes, function(box) {
var point = box.point,
tt = box.tt,
attr;
// Put the label in place
attr = {
visibility: box.pos === undefined ? 'hidden' : 'inherit',
x: (rightAligned || point.isHeader ? box.x : point.plotX + chart.plotLeft + pick(options.distance, 16)),
y: box.pos + chart.plotTop
};
if (point.isHeader) {
attr.anchorX = point.plotX + chart.plotLeft;
attr.anchorY = attr.y - 100;
}
tt.attr(attr);
// Draw the connector to the point
if (!point.isHeader) {
tt.connector.attr({
d: [
'M',
point.plotX + chart.plotLeft - attr.x,
point.plotY + point.series.yAxis.pos - attr.y,
'L',
(rightAligned ? -1 : 1) * pick(options.distance, 16) +
point.plotX + chart.plotLeft - attr.x,
box.pos + chart.plotTop + tt.getBBox().height / 2 -
attr.y
]
});
}
});
},
/**
* Find the new position and perform the move
*/
updatePosition: function(point) {
var chart = this.chart,
label = this.getLabel(),
pos = (this.options.positioner || this.getPosition).call(
this,
label.width,
label.height,
point
);
// do the move
this.move(
Math.round(pos.x),
Math.round(pos.y || 0), // can be undefined (#3977)
point.plotX + chart.plotLeft,
point.plotY + chart.plotTop
);
},
/**
* Get the best X date format based on the closest point range on the axis.
*/
getXDateFormat: function(point, options, xAxis) {
var xDateFormat,
dateTimeLabelFormats = options.dateTimeLabelFormats,
closestPointRange = xAxis && xAxis.closestPointRange,
n,
blank = '01-01 00:00:00.000',
strpos = {
millisecond: 15,
second: 12,
minute: 9,
hour: 6,
day: 3
},
date,
lastN = 'millisecond'; // for sub-millisecond data, #4223
if (closestPointRange) {
date = dateFormat('%m-%d %H:%M:%S.%L', point.x);
for (n in timeUnits) {
// If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format
if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek &&
date.substr(6) === blank.substr(6)) {
n = 'week';
break;
}
// The first format that is too great for the range
if (timeUnits[n] > closestPointRange) {
n = lastN;
break;
}
// If the point is placed every day at 23:59, we need to show
// the minutes as well. #2637.
if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) {
break;
}
// Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition
if (n !== 'week') {
lastN = n;
}
}
if (n) {
xDateFormat = dateTimeLabelFormats[n];
}
} else {
xDateFormat = dateTimeLabelFormats.day;
}
return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581
},
/**
* Format the footer/header of the tooltip
* #3397: abstraction to enable formatting of footer and header
*/
tooltipFooterHeaderFormatter: function(labelConfig, isFooter) {
var footOrHead = isFooter ? 'footer' : 'header',
series = labelConfig.series,
tooltipOptions = series.tooltipOptions,
xDateFormat = tooltipOptions.xDateFormat,
xAxis = series.xAxis,
isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(labelConfig.key),
formatString = tooltipOptions[footOrHead + 'Format'];
// Guess the best date format based on the closest point distance (#568, #3418)
if (isDateTime && !xDateFormat) {
xDateFormat = this.getXDateFormat(labelConfig, tooltipOptions, xAxis);
}
// Insert the footer date format if any
if (isDateTime && xDateFormat) {
formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}');
}
return format(formatString, {
point: labelConfig,
series: series
});
},
/**
* Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item,
* abstracting this functionality allows to easily overwrite and extend it.
*/
bodyFormatter: function(items) {
return map(items, function(item) {
var tooltipOptions = item.series.tooltipOptions;
return (tooltipOptions.pointFormatter || item.point.tooltipFormatter)
.call(item.point, tooltipOptions.pointFormat);
});
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
attr = H.attr,
charts = H.charts,
color = H.color,
css = H.css,
defined = H.defined,
doc = H.doc,
each = H.each,
extend = H.extend,
fireEvent = H.fireEvent,
offset = H.offset,
pick = H.pick,
removeEvent = H.removeEvent,
splat = H.splat,
Tooltip = H.Tooltip,
win = H.win;
/**
* The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
* Subsequent methods should be named differently from what they are doing.
* @param {Object} chart The Chart instance
* @param {Object} options The root options object
*/
H.Pointer = function(chart, options) {
this.init(chart, options);
};
H.Pointer.prototype = {
/**
* Initialize Pointer
*/
init: function(chart, options) {
// Store references
this.options = options;
this.chart = chart;
// Do we need to handle click on a touch device?
this.runChartClick = options.chart.events && !!options.chart.events.click;
this.pinchDown = [];
this.lastValidTouch = {};
if (Tooltip && options.tooltip.enabled) {
chart.tooltip = new Tooltip(chart, options.tooltip);
this.followTouchMove = pick(options.tooltip.followTouchMove, true);
}
this.setDOMEvents();
},
/**
* Resolve the zoomType option
*/
zoomOption: function() {
var chart = this.chart,
zoomType = chart.options.chart.zoomType,
zoomX = /x/.test(zoomType),
zoomY = /y/.test(zoomType),
inverted = chart.inverted;
this.zoomX = zoomX;
this.zoomY = zoomY;
this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
this.hasZoom = zoomX || zoomY;
},
/**
* Add crossbrowser support for chartX and chartY
* @param {Object} e The event object in standard browsers
*/
normalize: function(e, chartPosition) {
var chartX,
chartY,
ePos;
// IE normalizing
e = e || win.event;
if (!e.target) {
e.target = e.srcElement;
}
// iOS (#2757)
ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e;
// Get mouse position
if (!chartPosition) {
this.chartPosition = chartPosition = offset(this.chart.container);
}
// chartX and chartY
if (ePos.pageX === undefined) { // IE < 9. #886.
chartX = Math.max(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
// for IE10 quirks mode within framesets
chartY = e.y;
} else {
chartX = ePos.pageX - chartPosition.left;
chartY = ePos.pageY - chartPosition.top;
}
return extend(e, {
chartX: Math.round(chartX),
chartY: Math.round(chartY)
});
},
/**
* Get the click position in terms of axis values.
*
* @param {Object} e A pointer event
*/
getCoordinates: function(e) {
var coordinates = {
xAxis: [],
yAxis: []
};
each(this.chart.axes, function(axis) {
coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
axis: axis,
value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
});
});
return coordinates;
},
/**
* With line type charts with a single tracker, get the point closest to the mouse.
* Run Point.onMouseOver and display tooltip for the point or points.
*/
runPointActions: function(e) {
var pointer = this,
chart = pointer.chart,
series = chart.series,
tooltip = chart.tooltip,
shared = tooltip ? tooltip.shared : false,
followPointer,
updatePosition = true,
hoverPoint = chart.hoverPoint,
hoverSeries = chart.hoverSeries,
i,
anchor,
noSharedTooltip,
stickToHoverSeries,
directTouch,
kdpoints = [],
kdpointT;
// For hovering over the empty parts of the plot area (hoverSeries is undefined).
// If there is one series with point tracking (combo chart), don't go to nearest neighbour.
if (!shared && !hoverSeries) {
for (i = 0; i < series.length; i++) {
if (series[i].directTouch || !series[i].options.stickyTracking) {
series = [];
}
}
}
// If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on
// a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise,
// search the k-d tree.
stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch);
if (stickToHoverSeries && hoverPoint) {
kdpoints = [hoverPoint];
// Handle shared tooltip or cases where a series is not yet hovered
} else {
// When we have non-shared tooltip and sticky tracking is disabled,
// search for the closest point only on hovered series: #5533, #5476
if (!shared && hoverSeries && !hoverSeries.options.stickyTracking) {
series = [hoverSeries];
}
// Find nearest points on all series
each(series, function(s) {
// Skip hidden series
noSharedTooltip = s.noSharedTooltip && shared;
directTouch = !shared && s.directTouch;
if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821
kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828
if (kdpointT && kdpointT.series) { // Point.series becomes null when reset and before redraw (#5197)
kdpoints.push(kdpointT);
}
}
});
// Sort kdpoints by distance to mouse pointer
kdpoints.sort(function(p1, p2) {
var isCloserX = p1.distX - p2.distX,
isCloser = p1.dist - p2.dist,
isAbove = p1.series.group.zIndex > p2.series.group.zIndex ? -1 : 1;
// We have two points which are not in the same place on xAxis and shared tooltip:
if (isCloserX !== 0 && shared) { // #5721
return isCloserX;
}
// Points are not exactly in the same place on x/yAxis:
if (isCloser !== 0) {
return isCloser;
}
// The same xAxis and yAxis position, sort by z-index:
return isAbove;
});
}
// Remove points with different x-positions, required for shared tooltip and crosshairs (#4645):
if (shared) {
i = kdpoints.length;
while (i--) {
if (kdpoints[i].x !== kdpoints[0].x || kdpoints[i].series.noSharedTooltip) {
kdpoints.splice(i, 1);
}
}
}
// Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200
if (kdpoints[0] && (kdpoints[0] !== this.prevKDPoint || (tooltip && tooltip.isHidden))) {
// Draw tooltip if necessary
if (shared && !kdpoints[0].series.noSharedTooltip) {
// Do mouseover on all points (#3919, #3985, #4410, #5622)
for (i = 0; i < kdpoints.length; i++) {
kdpoints[i].onMouseOver(e, kdpoints[i] !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoints[0]));
}
if (kdpoints.length && tooltip) {
// Keep the order of series in tooltip:
tooltip.refresh(kdpoints.sort(function(p1, p2) {
return p1.series.index - p2.series.index;
}), e);
}
} else {
if (tooltip) {
tooltip.refresh(kdpoints[0], e);
}
if (!hoverSeries || !hoverSeries.directTouch) { // #4448
kdpoints[0].onMouseOver(e);
}
}
this.prevKDPoint = kdpoints[0];
updatePosition = false;
}
// Update positions (regardless of kdpoint or hoverPoint)
if (updatePosition) {
followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer;
if (tooltip && followPointer && !tooltip.isHidden) {
anchor = tooltip.getAnchor([{}], e);
tooltip.updatePosition({
plotX: anchor[0],
plotY: anchor[1]
});
}
}
// Start the event listener to pick up the tooltip and crosshairs
if (!pointer._onDocumentMouseMove) {
pointer._onDocumentMouseMove = function(e) {
if (charts[H.hoverChartIndex]) {
charts[H.hoverChartIndex].pointer.onDocumentMouseMove(e);
}
};
addEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
}
// Crosshair. For each hover point, loop over axes and draw cross if that point
// belongs to the axis (#4927).
each(shared ? kdpoints : [pick(hoverPoint, kdpoints[0])], function drawPointCrosshair(point) { // #5269
each(chart.axes, function drawAxisCrosshair(axis) {
// In case of snap = false, point is undefined, and we draw the crosshair anyway (#5066)
if (!point || point.series && point.series[axis.coll] === axis) { // #5658
axis.drawCrosshair(e, point);
}
});
});
},
/**
* Reset the tracking by hiding the tooltip, the hover series state and the hover point
*
* @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
*/
reset: function(allowMove, delay) {
var pointer = this,
chart = pointer.chart,
hoverSeries = chart.hoverSeries,
hoverPoint = chart.hoverPoint,
hoverPoints = chart.hoverPoints,
tooltip = chart.tooltip,
tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint;
// Check if the points have moved outside the plot area (#1003, #4736, #5101)
if (allowMove && tooltipPoints) {
each(splat(tooltipPoints), function(point) {
if (point.series.isCartesian && point.plotX === undefined) {
allowMove = false;
}
});
}
// Just move the tooltip, #349
if (allowMove) {
if (tooltip && tooltipPoints) {
tooltip.refresh(tooltipPoints);
if (hoverPoint) { // #2500
hoverPoint.setState(hoverPoint.state, true);
each(chart.axes, function(axis) {
if (axis.crosshair) {
axis.drawCrosshair(null, hoverPoint);
}
});
}
}
// Full reset
} else {
if (hoverPoint) {
hoverPoint.onMouseOut();
}
if (hoverPoints) {
each(hoverPoints, function(point) {
point.setState();
});
}
if (hoverSeries) {
hoverSeries.onMouseOut();
}
if (tooltip) {
tooltip.hide(delay);
}
if (pointer._onDocumentMouseMove) {
removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
pointer._onDocumentMouseMove = null;
}
// Remove crosshairs
each(chart.axes, function(axis) {
axis.hideCrosshair();
});
pointer.hoverX = pointer.prevKDPoint = chart.hoverPoints = chart.hoverPoint = null;
}
},
/**
* Scale series groups to a certain scale and translation
*/
scaleGroups: function(attribs, clip) {
var chart = this.chart,
seriesAttribs;
// Scale each series
each(chart.series, function(series) {
seriesAttribs = attribs || series.getPlotBox(); // #1701
if (series.xAxis && series.xAxis.zoomEnabled && series.group) {
series.group.attr(seriesAttribs);
if (series.markerGroup) {
series.markerGroup.attr(seriesAttribs);
series.markerGroup.clip(clip ? chart.clipRect : null);
}
if (series.dataLabelsGroup) {
series.dataLabelsGroup.attr(seriesAttribs);
}
}
});
// Clip
chart.clipRect.attr(clip || chart.clipBox);
},
/**
* Start a drag operation
*/
dragStart: function(e) {
var chart = this.chart;
// Record the start position
chart.mouseIsDown = e.type;
chart.cancelClick = false;
chart.mouseDownX = this.mouseDownX = e.chartX;
chart.mouseDownY = this.mouseDownY = e.chartY;
},
/**
* Perform a drag operation in response to a mousemove event while the mouse is down
*/
drag: function(e) {
var chart = this.chart,
chartOptions = chart.options.chart,
chartX = e.chartX,
chartY = e.chartY,
zoomHor = this.zoomHor,
zoomVert = this.zoomVert,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
clickedInside,
size,
selectionMarker = this.selectionMarker,
mouseDownX = this.mouseDownX,
mouseDownY = this.mouseDownY,
panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key'];
// If the device supports both touch and mouse (like IE11), and we are touch-dragging
// inside the plot area, don't handle the mouse event. #4339.
if (selectionMarker && selectionMarker.touch) {
return;
}
// If the mouse is outside the plot area, adjust to cooordinates
// inside to prevent the selection marker from going outside
if (chartX < plotLeft) {
chartX = plotLeft;
} else if (chartX > plotLeft + plotWidth) {
chartX = plotLeft + plotWidth;
}
if (chartY < plotTop) {
chartY = plotTop;
} else if (chartY > plotTop + plotHeight) {
chartY = plotTop + plotHeight;
}
// determine if the mouse has moved more than 10px
this.hasDragged = Math.sqrt(
Math.pow(mouseDownX - chartX, 2) +
Math.pow(mouseDownY - chartY, 2)
);
if (this.hasDragged > 10) {
clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
// make a selection
if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) {
if (!selectionMarker) {
this.selectionMarker = selectionMarker = chart.renderer.rect(
plotLeft,
plotTop,
zoomHor ? 1 : plotWidth,
zoomVert ? 1 : plotHeight,
0
)
.attr({
'class': 'highcharts-selection-marker',
'zIndex': 7
})
.add();
}
}
// adjust the width of the selection marker
if (selectionMarker && zoomHor) {
size = chartX - mouseDownX;
selectionMarker.attr({
width: Math.abs(size),
x: (size > 0 ? 0 : size) + mouseDownX
});
}
// adjust the height of the selection marker
if (selectionMarker && zoomVert) {
size = chartY - mouseDownY;
selectionMarker.attr({
height: Math.abs(size),
y: (size > 0 ? 0 : size) + mouseDownY
});
}
// panning
if (clickedInside && !selectionMarker && chartOptions.panning) {
chart.pan(e, chartOptions.panning);
}
}
},
/**
* On mouse up or touch end across the entire document, drop the selection.
*/
drop: function(e) {
var pointer = this,
chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
originalEvent: e, // #4890
xAxis: [],
yAxis: []
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function(axis) {
if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{
xAxis: 'zoomX',
yAxis: 'zoomY'
}[axis.coll]])) { // #859, #3569
var horiz = axis.horiz,
minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding : 0, // #1207, #3075
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
selectionData[axis.coll].push({
axis: axis,
min: Math.min(selectionMin, selectionMax), // for reversed axes
max: Math.max(selectionMin, selectionMax)
});
runZoom = true;
}
});
if (runZoom) {
fireEvent(chart, 'selection', selectionData, function(args) {
chart.zoom(extend(args, hasPinched ? {
animation: false
} : null));
});
}
}
this.selectionMarker = this.selectionMarker.destroy();
// Reset scaling preview
if (hasPinched) {
this.scaleGroups();
}
}
// Reset all
if (chart) { // it may be destroyed on mouse up - #877
css(chart.container, {
cursor: chart._cursor
});
chart.cancelClick = this.hasDragged > 10; // #370
chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
this.pinchDown = [];
}
},
onContainerMouseDown: function(e) {
e = this.normalize(e);
this.zoomOption();
// issue #295, dragging not always working in Firefox
if (e.preventDefault) {
e.preventDefault();
}
this.dragStart(e);
},
onDocumentMouseUp: function(e) {
if (charts[H.hoverChartIndex]) {
charts[H.hoverChartIndex].pointer.drop(e);
}
},
/**
* Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
* Issue #149 workaround. The mouseleave event does not always fire.
*/
onDocumentMouseMove: function(e) {
var chart = this.chart,
chartPosition = this.chartPosition;
e = this.normalize(e, chartPosition);
// If we're outside, hide the tooltip
if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') &&
!chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
this.reset();
}
},
/**
* When mouse leaves the container, hide the tooltip.
*/
onContainerMouseLeave: function(e) {
var chart = charts[H.hoverChartIndex];
if (chart && (e.relatedTarget || e.toElement)) { // #4886, MS Touch end fires mouseleave but with no related target
chart.pointer.reset();
chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
}
},
// The mousemove, touchmove and touchstart event handler
onContainerMouseMove: function(e) {
var chart = this.chart;
if (!defined(H.hoverChartIndex) || !charts[H.hoverChartIndex] || !charts[H.hoverChartIndex].mouseIsDown) {
H.hoverChartIndex = chart.index;
}
e = this.normalize(e);
e.returnValue = false; // #2251, #3224
if (chart.mouseIsDown === 'mousedown') {
this.drag(e);
}
// Show the tooltip and run mouse over events (#977)
if ((this.inClass(e.target, 'highcharts-tracker') ||
chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
this.runPointActions(e);
}
},
/**
* Utility to detect whether an element has, or has a parent with, a specific
* class name. Used on detection of tracker objects and on deciding whether
* hovering the tooltip should cause the active series to mouse out.
*/
inClass: function(element, className) {
var elemClassName;
while (element) {
elemClassName = attr(element, 'class');
if (elemClassName) {
if (elemClassName.indexOf(className) !== -1) {
return true;
}
if (elemClassName.indexOf('highcharts-container') !== -1) {
return false;
}
}
element = element.parentNode;
}
},
onTrackerMouseOut: function(e) {
var series = this.chart.hoverSeries,
relatedTarget = e.relatedTarget || e.toElement;
if (series && relatedTarget && !series.options.stickyTracking &&
!this.inClass(relatedTarget, 'highcharts-tooltip') &&
(!this.inClass(relatedTarget, 'highcharts-series-' + series.index) || // #2499, #4465
!this.inClass(relatedTarget, 'highcharts-tracker') // #5553
)
) {
series.onMouseOut();
}
},
onContainerClick: function(e) {
var chart = this.chart,
hoverPoint = chart.hoverPoint,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop;
e = this.normalize(e);
if (!chart.cancelClick) {
// On tracker click, fire the series and point events. #783, #1583
if (hoverPoint && this.inClass(e.target, 'highcharts-tracker')) {
// the series click event
fireEvent(hoverPoint.series, 'click', extend(e, {
point: hoverPoint
}));
// the point click event
if (chart.hoverPoint) { // it may be destroyed (#1844)
hoverPoint.firePointEvent('click', e);
}
// When clicking outside a tracker, fire a chart event
} else {
extend(e, this.getCoordinates(e));
// fire a click event in the chart
if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
fireEvent(chart, 'click', e);
}
}
}
},
/**
* Set the JS DOM events on the container and document. This method should contain
* a one-to-one assignment between methods and their handlers. Any advanced logic should
* be moved to the handler reflecting the event's name.
*/
setDOMEvents: function() {
var pointer = this,
container = pointer.chart.container;
container.onmousedown = function(e) {
pointer.onContainerMouseDown(e);
};
container.onmousemove = function(e) {
pointer.onContainerMouseMove(e);
};
container.onclick = function(e) {
pointer.onContainerClick(e);
};
addEvent(container, 'mouseleave', pointer.onContainerMouseLeave);
if (H.chartCount === 1) {
addEvent(doc, 'mouseup', pointer.onDocumentMouseUp);
}
if (H.hasTouch) {
container.ontouchstart = function(e) {
pointer.onContainerTouchStart(e);
};
container.ontouchmove = function(e) {
pointer.onContainerTouchMove(e);
};
if (H.chartCount === 1) {
addEvent(doc, 'touchend', pointer.onDocumentTouchEnd);
}
}
},
/**
* Destroys the Pointer object and disconnects DOM events.
*/
destroy: function() {
var prop;
removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave);
if (!H.chartCount) {
removeEvent(doc, 'mouseup', this.onDocumentMouseUp);
removeEvent(doc, 'touchend', this.onDocumentTouchEnd);
}
// memory and CPU leak
clearInterval(this.tooltipTimeout);
for (prop in this) {
this[prop] = null;
}
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var charts = H.charts,
each = H.each,
extend = H.extend,
map = H.map,
noop = H.noop,
pick = H.pick,
Pointer = H.Pointer;
/* Support for touch devices */
extend(Pointer.prototype, {
/**
* Run translation operations
*/
pinchTranslate: function(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (this.zoomHor || this.pinchHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (this.zoomVert || this.pinchVert) {
this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
},
/**
* Run translation operations for each direction (horizontal and vertical) independently
*/
pinchTranslateDirection: function(horiz, pinchDown, touches, transform,
selectionMarker, clip, lastValidTouch, forcedScale) {
var chart = this.chart,
xy = horiz ? 'x' : 'y',
XY = horiz ? 'X' : 'Y',
sChartXY = 'chart' + XY,
wh = horiz ? 'width' : 'height',
plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
selectionWH,
selectionXY,
clipXY,
scale = forcedScale || 1,
inverted = chart.inverted,
bounds = chart.bounds[horiz ? 'h' : 'v'],
singleTouch = pinchDown.length === 1,
touch0Start = pinchDown[0][sChartXY],
touch0Now = touches[0][sChartXY],
touch1Start = !singleTouch && pinchDown[1][sChartXY],
touch1Now = !singleTouch && touches[1][sChartXY],
outOfBounds,
transformScale,
scaleKey,
setScale = function() {
// Don't zoom if fingers are too close on this axis
if (!singleTouch && Math.abs(touch0Start - touch1Start) > 20) {
scale = forcedScale || Math.abs(touch0Now - touch1Now) / Math.abs(touch0Start - touch1Start);
}
clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
};
// Set the scale, first pass
setScale();
selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
// Out of bounds
if (selectionXY < bounds.min) {
selectionXY = bounds.min;
outOfBounds = true;
} else if (selectionXY + selectionWH > bounds.max) {
selectionXY = bounds.max - selectionWH;
outOfBounds = true;
}
// Is the chart dragged off its bounds, determined by dataMin and dataMax?
if (outOfBounds) {
// Modify the touchNow position in order to create an elastic drag movement. This indicates
// to the user that the chart is responsive but can't be dragged further.
touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
if (!singleTouch) {
touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
}
// Set the scale, second pass to adapt to the modified touchNow positions
setScale();
} else {
lastValidTouch[xy] = [touch0Now, touch1Now];
}
// Set geometry for clipping, selection and transformation
if (!inverted) {
clip[xy] = clipXY - plotLeftTop;
clip[wh] = selectionWH;
}
scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
transformScale = inverted ? 1 / scale : scale;
selectionMarker[wh] = selectionWH;
selectionMarker[xy] = selectionXY;
transform[scaleKey] = scale;
transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
},
/**
* Handle touch events with two touches
*/
pinch: function(e) {
var self = this,
chart = self.chart,
pinchDown = self.pinchDown,
touches = e.touches,
touchesLength = touches.length,
lastValidTouch = self.lastValidTouch,
hasZoom = self.hasZoom,
selectionMarker = self.selectionMarker,
transform = {},
fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, 'highcharts-tracker') &&
chart.runTrackerClick) || self.runChartClick),
clip = {};
// Don't initiate panning until the user has pinched. This prevents us from
// blocking page scrolling as users scroll down a long page (#4210).
if (touchesLength > 1) {
self.initiated = true;
}
// On touch devices, only proceed to trigger click if a handler is defined
if (hasZoom && self.initiated && !fireClickEvent) {
e.preventDefault();
}
// Normalize each touch
map(touches, function(e) {
return self.normalize(e);
});
// Register the touch start position
if (e.type === 'touchstart') {
each(touches, function(e, i) {
pinchDown[i] = {
chartX: e.chartX,
chartY: e.chartY
};
});
lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
// Identify the data bounds in pixels
each(chart.axes, function(axis) {
if (axis.zoomEnabled) {
var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
minPixelPadding = axis.minPixelPadding,
min = axis.toPixels(pick(axis.options.min, axis.dataMin)),
max = axis.toPixels(pick(axis.options.max, axis.dataMax)),
absMin = Math.min(min, max),
absMax = Math.max(min, max);
// Store the bounds for use in the touchmove handler
bounds.min = Math.min(axis.pos, absMin - minPixelPadding);
bounds.max = Math.max(axis.pos + axis.len, absMax + minPixelPadding);
}
});
self.res = true; // reset on next move
// Event type is touchmove, handle panning and pinching
} else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
// Set the marker
if (!selectionMarker) {
self.selectionMarker = selectionMarker = extend({
destroy: noop,
touch: true
}, chart.plotBox);
}
self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
self.hasPinched = hasZoom;
// Scale and translate the groups to provide visual feedback during pinching
self.scaleGroups(transform, clip);
// Optionally move the tooltip on touchmove
if (!hasZoom && self.followTouchMove && touchesLength === 1) {
this.runPointActions(self.normalize(e));
} else if (self.res) {
self.res = false;
this.reset(false, 0);
}
}
},
/**
* General touch handler shared by touchstart and touchmove.
*/
touch: function(e, start) {
var chart = this.chart,
hasMoved,
pinchDown;
H.hoverChartIndex = chart.index;
if (e.touches.length === 1) {
e = this.normalize(e);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) {
// Run mouse events and display tooltip etc
if (start) {
this.runPointActions(e);
}
// Android fires touchmove events after the touchstart even if the
// finger hasn't moved, or moved only a pixel or two. In iOS however,
// the touchmove doesn't fire unless the finger moves more than ~4px.
// So we emulate this behaviour in Android by checking how much it
// moved, and cancelling on small distances. #3450.
if (e.type === 'touchmove') {
pinchDown = this.pinchDown;
hasMoved = pinchDown[0] ? Math.sqrt( // #5266
Math.pow(pinchDown[0].chartX - e.chartX, 2) +
Math.pow(pinchDown[0].chartY - e.chartY, 2)
) >= 4 : false;
}
if (pick(hasMoved, true)) {
this.pinch(e);
}
} else if (start) {
// Hide the tooltip on touching outside the plot area (#1203)
this.reset();
}
} else if (e.touches.length === 2) {
this.pinch(e);
}
},
onContainerTouchStart: function(e) {
this.zoomOption();
this.touch(e, true);
},
onContainerTouchMove: function(e) {
this.touch(e);
},
onDocumentTouchEnd: function(e) {
if (charts[H.hoverChartIndex]) {
charts[H.hoverChartIndex].pointer.drop(e);
}
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
charts = H.charts,
css = H.css,
doc = H.doc,
extend = H.extend,
noop = H.noop,
Pointer = H.Pointer,
removeEvent = H.removeEvent,
win = H.win,
wrap = H.wrap;
if (win.PointerEvent || win.MSPointerEvent) {
// The touches object keeps track of the points being touched at all times
var touches = {},
hasPointerEvent = !!win.PointerEvent,
getWebkitTouches = function() {
var key,
fake = [];
fake.item = function(i) {
return this[i];
};
for (key in touches) {
if (touches.hasOwnProperty(key)) {
fake.push({
pageX: touches[key].pageX,
pageY: touches[key].pageY,
target: touches[key].target
});
}
}
return fake;
},
translateMSPointer = function(e, method, wktype, func) {
var p;
if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[H.hoverChartIndex]) {
func(e);
p = charts[H.hoverChartIndex].pointer;
p[method]({
type: wktype,
target: e.currentTarget,
preventDefault: noop,
touches: getWebkitTouches()
});
}
};
/**
* Extend the Pointer prototype with methods for each event handler and more
*/
extend(Pointer.prototype, {
onContainerPointerDown: function(e) {
translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function(e) {
touches[e.pointerId] = {
pageX: e.pageX,
pageY: e.pageY,
target: e.currentTarget
};
});
},
onContainerPointerMove: function(e) {
translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function(e) {
touches[e.pointerId] = {
pageX: e.pageX,
pageY: e.pageY
};
if (!touches[e.pointerId].target) {
touches[e.pointerId].target = e.currentTarget;
}
});
},
onDocumentPointerUp: function(e) {
translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function(e) {
delete touches[e.pointerId];
});
},
/**
* Add or remove the MS Pointer specific events
*/
batchMSEvents: function(fn) {
fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
}
});
// Disable default IE actions for pinch and such on chart element
wrap(Pointer.prototype, 'init', function(proceed, chart, options) {
proceed.call(this, chart, options);
if (this.hasZoom) { // #4014
css(chart.container, {
'-ms-touch-action': 'none',
'touch-action': 'none'
});
}
});
// Add IE specific touch events to chart
wrap(Pointer.prototype, 'setDOMEvents', function(proceed) {
proceed.apply(this);
if (this.hasZoom || this.followTouchMove) {
this.batchMSEvents(addEvent);
}
});
// Destroy MS events also
wrap(Pointer.prototype, 'destroy', function(proceed) {
this.batchMSEvents(removeEvent);
proceed.call(this);
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Legend,
addEvent = H.addEvent,
css = H.css,
discardElement = H.discardElement,
defined = H.defined,
each = H.each,
extend = H.extend,
isFirefox = H.isFirefox,
marginNames = H.marginNames,
merge = H.merge,
pick = H.pick,
setAnimation = H.setAnimation,
stableSort = H.stableSort,
win = H.win,
wrap = H.wrap;
/**
* The overview of the chart's series
*/
Legend = H.Legend = function(chart, options) {
this.init(chart, options);
};
Legend.prototype = {
/**
* Initialize the legend
*/
init: function(chart, options) {
this.chart = chart;
this.setOptions(options);
if (options.enabled) {
// Render it
this.render();
// move checkboxes
addEvent(this.chart, 'endResize', function() {
this.legend.positionCheckboxes();
});
}
},
setOptions: function(options) {
var padding = pick(options.padding, 8);
this.options = options;
this.itemMarginTop = options.itemMarginTop || 0;
this.padding = padding;
this.initialItemX = padding;
this.initialItemY = padding - 5; // 5 is the number of pixels above the text
this.maxItemWidth = 0;
this.itemHeight = 0;
this.symbolWidth = pick(options.symbolWidth, 16);
this.pages = [];
},
/**
* Update the legend with new options. Equivalent to running chart.update with a legend
* configuration option.
* @param {Object} options Legend options
* @param {Boolean} redraw Whether to redraw the chart, defaults to true.
*/
update: function(options, redraw) {
var chart = this.chart;
this.setOptions(merge(true, this.options, options));
this.destroy();
chart.isDirtyLegend = chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Set the colors for the legend item
* @param {Object} item A Series or Point instance
* @param {Object} visible Dimmed or colored
*/
colorizeItem: function(item, visible) {
item.legendGroup[visible ? 'removeClass' : 'addClass']('highcharts-legend-item-hidden');
},
/**
* Position the legend item
* @param {Object} item A Series or Point instance
*/
positionItem: function(item) {
var legend = this,
options = legend.options,
symbolPadding = options.symbolPadding,
ltr = !options.rtl,
legendItemPos = item._legendItemPos,
itemX = legendItemPos[0],
itemY = legendItemPos[1],
checkbox = item.checkbox,
legendGroup = item.legendGroup;
if (legendGroup && legendGroup.element) {
legendGroup.translate(
ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
itemY
);
}
if (checkbox) {
checkbox.x = itemX;
checkbox.y = itemY;
}
},
/**
* Destroy a single legend item
* @param {Object} item The series or point
*/
destroyItem: function(item) {
var checkbox = item.checkbox;
// destroy SVG elements
each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function(key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
if (checkbox) {
discardElement(item.checkbox);
}
},
/**
* Destroys the legend.
*/
destroy: function() {
var legend = this,
legendGroup = legend.group,
box = legend.box;
if (box) {
legend.box = box.destroy();
}
// Destroy items
each(this.getAllItems(), function(item) {
each(['legendItem', 'legendGroup'], function(key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
});
if (legendGroup) {
legend.group = legendGroup.destroy();
}
},
/**
* Position the checkboxes after the width is determined
*/
positionCheckboxes: function(scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight,
titleHeight = this.titleHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function(item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = translateY + titleHeight + checkbox.y + (scrollOffset || 0) + 3;
css(checkbox, {
left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + 'px',
top: top + 'px',
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : 'none'
});
}
});
}
},
/**
* Render the legend title on top of the legend
*/
renderTitle: function() {
var options = this.options,
padding = this.padding,
titleOptions = options.title,
titleHeight = 0,
bBox;
if (titleOptions.text) {
if (!this.title) {
this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
.attr({
zIndex: 1
})
.add(this.group);
}
bBox = this.title.getBBox();
titleHeight = bBox.height;
this.offsetWidth = bBox.width; // #1717
this.contentGroup.attr({
translateY: titleHeight
});
}
this.titleHeight = titleHeight;
},
/**
* Set the legend item text
*/
setText: function(item) {
var options = this.options;
item.legendItem.attr({
text: options.labelFormat ? H.format(options.labelFormat, item) : options.labelFormatter.call(item)
});
},
/**
* Render a single specific legend item
* @param {Object} item A series or point
*/
renderItem: function(item) {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
options = legend.options,
horizontal = options.layout === 'horizontal',
symbolWidth = legend.symbolWidth,
symbolPadding = options.symbolPadding,
padding = legend.padding,
itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
ltr = !options.rtl,
itemHeight,
widthOption = options.width,
itemMarginBottom = options.itemMarginBottom || 0,
itemMarginTop = legend.itemMarginTop,
initialItemX = legend.initialItemX,
bBox,
itemWidth,
li = item.legendItem,
isSeries = !item.series,
series = !isSeries && item.series.drawLegendSymbol ? item.series : item,
seriesOptions = series.options,
showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
useHTML = options.useHTML,
fontSize = 12;
if (!li) { // generate it once, later move it
// Generate the group box
// A group to hold the symbol and text. Text is to be appended in Legend class.
item.legendGroup = renderer.g('legend-item')
.addClass('highcharts-' + series.type + '-series highcharts-color-' + item.colorIndex + ' ' +
(item.options.className || '') +
(isSeries ? 'highcharts-series-' + item.index : '')
)
.attr({
zIndex: 1
})
.add(legend.scrollGroup);
// Generate the list item text and add it to the group
item.legendItem = li = renderer.text(
'',
ltr ? symbolWidth + symbolPadding : -symbolPadding,
legend.baseline || 0,
useHTML
)
.attr({
align: ltr ? 'left' : 'right',
zIndex: 2
})
.add(item.legendGroup);
// Get the baseline for the first item - the font size is equal for all
if (!legend.baseline) {
legend.fontMetrics = renderer.fontMetrics(
fontSize,
li
);
legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop;
li.attr('y', legend.baseline);
}
// Draw the legend symbol inside the group box
series.drawLegendSymbol(legend, item);
if (legend.setItemEvents) {
legend.setItemEvents(item, li, useHTML);
}
// add the HTML checkbox on top
if (showCheckbox) {
legend.createCheckboxForItem(item);
}
}
// Colorize the items
legend.colorizeItem(item, item.visible);
// Always update the text
legend.setText(item);
// calculate the positions for the next line
bBox = li.getBBox();
itemWidth = item.checkboxOffset =
options.itemWidth ||
item.legendItemWidth ||
symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
legend.itemHeight = itemHeight = Math.round(item.legendItemHeight || bBox.height);
// if the item exceeds the width, start a new line
if (horizontal && legend.itemX - initialItemX + itemWidth >
(widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
legend.itemX = initialItemX;
legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
legend.lastLineHeight = 0; // reset for next line (#915, #3976)
}
// If the item exceeds the height, start a new column
/*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
legend.itemY = legend.initialItemY;
legend.itemX += legend.maxItemWidth;
legend.maxItemWidth = 0;
}*/
// Set the edge positions
legend.maxItemWidth = Math.max(legend.maxItemWidth, itemWidth);
legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
legend.lastLineHeight = Math.max(itemHeight, legend.lastLineHeight); // #915
// cache the position of the newly generated or reordered items
item._legendItemPos = [legend.itemX, legend.itemY];
// advance
if (horizontal) {
legend.itemX += itemWidth;
} else {
legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
legend.lastLineHeight = itemHeight;
}
// the width of the widest item
legend.offsetWidth = widthOption || Math.max(
(horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
legend.offsetWidth
);
},
/**
* Get all items, which is one item per series for normal series and one item per point
* for pie series.
*/
getAllItems: function() {
var allItems = [];
each(this.chart.series, function(series) {
var seriesOptions = series && series.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (series && pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? undefined : false, true)) {
// Use points or series for the legend item depending on legendType
allItems = allItems.concat(
series.legendItems ||
(seriesOptions.legendType === 'point' ?
series.data :
series)
);
}
});
return allItems;
},
/**
* Adjust the chart margins by reserving space for the legend on only one side
* of the chart. If the position is set to a corner, top or bottom is reserved
* for horizontal legends and left or right for vertical ones.
*/
adjustMargins: function(margin, spacing) {
var chart = this.chart,
options = this.options,
// Use the first letter of each alignment option in order to detect the side
alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7
if (!options.floating) {
each([
/(lth|ct|rth)/,
/(rtv|rm|rbv)/,
/(rbh|cb|lbh)/,
/(lbv|lm|ltv)/
], function(alignments, side) {
if (alignments.test(alignment) && !defined(margin[side])) {
// Now we have detected on which side of the chart we should reserve space for the legend
chart[marginNames[side]] = Math.max(
chart[marginNames[side]],
chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
pick(options.margin, 12) +
spacing[side]
);
}
});
}
},
/**
* Render the legend. This method can be called both before and after
* chart.render. If called after, it will only rearrange items instead
* of creating new ones.
*/
render: function() {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
legendGroup = legend.group,
allItems,
display,
legendWidth,
legendHeight,
box = legend.box,
options = legend.options,
padding = legend.padding;
legend.itemX = legend.initialItemX;
legend.itemY = legend.initialItemY;
legend.offsetWidth = 0;
legend.lastItemY = 0;
if (!legendGroup) {
legend.group = legendGroup = renderer.g('legend')
.attr({
zIndex: 7
})
.add();
legend.contentGroup = renderer.g()
.attr({
zIndex: 1
}) // above background
.add(legendGroup);
legend.scrollGroup = renderer.g()
.add(legend.contentGroup);
}
legend.renderTitle();
// add each series or point
allItems = legend.getAllItems();
// sort by legendIndex
stableSort(allItems, function(a, b) {
return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
});
// reversed legend
if (options.reversed) {
allItems.reverse();
}
legend.allItems = allItems;
legend.display = display = !!allItems.length;
// render the items
legend.lastLineHeight = 0;
each(allItems, function(item) {
legend.renderItem(item);
});
// Get the box
legendWidth = (options.width || legend.offsetWidth) + padding;
legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
legendHeight = legend.handleOverflow(legendHeight);
legendHeight += padding;
// Draw the border and/or background
if (!box) {
legend.box = box = renderer.rect()
.addClass('highcharts-legend-box')
.attr({
r: options.borderRadius
})
.add(legendGroup);
box.isNew = true;
}
if (legendWidth > 0 && legendHeight > 0) {
box[box.isNew ? 'attr' : 'animate'](
box.crisp({
x: 0,
y: 0,
width: legendWidth,
height: legendHeight
}, box.strokeWidth())
);
box.isNew = false;
}
// hide the border if no items
box[display ? 'show' : 'hide']();
// Open for responsiveness
if (legendGroup.getStyle('display') === 'none') {
legendWidth = legendHeight = 0;
}
legend.legendWidth = legendWidth;
legend.legendHeight = legendHeight;
// Now that the legend width and height are established, put the items in the
// final position
each(allItems, function(item) {
legend.positionItem(item);
});
// 1.x compatibility: positioning based on style
/*var props = ['left', 'right', 'top', 'bottom'],
prop,
i = 4;
while (i--) {
prop = props[i];
if (options.style[prop] && options.style[prop] !== 'auto') {
options[i < 2 ? 'align' : 'verticalAlign'] = prop;
options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
}
}*/
if (display) {
legendGroup.align(extend({
width: legendWidth,
height: legendHeight
}, options), true, 'spacingBox');
}
if (!chart.isResizing) {
this.positionCheckboxes();
}
},
/**
* Set up the overflow handling by adding navigation with up and down arrows below the
* legend.
*/
handleOverflow: function(legendHeight) {
var legend = this,
chart = this.chart,
renderer = chart.renderer,
options = this.options,
optionsY = options.y,
alignTop = options.verticalAlign === 'top',
spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
maxHeight = options.maxHeight,
clipHeight,
clipRect = this.clipRect,
navOptions = options.navigation,
animation = pick(navOptions.animation, true),
arrowSize = navOptions.arrowSize || 12,
nav = this.nav,
pages = this.pages,
padding = this.padding,
lastY,
allItems = this.allItems,
clipToHeight = function(height) {
clipRect.attr({
height: height
});
// useHTML
if (legend.contentGroup.div) {
legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)';
}
};
// Adjust the height
if (options.layout === 'horizontal') {
spaceHeight /= 2;
}
if (maxHeight) {
spaceHeight = Math.min(spaceHeight, maxHeight);
}
// Reset the legend height and adjust the clipping rectangle
pages.length = 0;
if (legendHeight > spaceHeight && navOptions.enabled !== false) {
this.clipHeight = clipHeight = Math.max(spaceHeight - 20 - this.titleHeight - padding, 0);
this.currentPage = pick(this.currentPage, 1);
this.fullHeight = legendHeight;
// Fill pages with Y positions so that the top of each a legend item defines
// the scroll top for each page (#2098)
each(allItems, function(item, i) {
var y = item._legendItemPos[1],
h = Math.round(item.legendItem.getBBox().height),
len = pages.length;
if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
pages.push(lastY || y);
len++;
}
if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
pages.push(y);
}
if (y !== lastY) {
lastY = y;
}
});
// Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
if (!clipRect) {
clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0);
legend.contentGroup.clip(clipRect);
}
clipToHeight(clipHeight);
// Add navigation elements
if (!nav) {
this.nav = nav = renderer.g().attr({
zIndex: 1
}).add(this.group);
this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
.on('click', function() {
legend.scroll(-1, animation);
})
.add(nav);
this.pager = renderer.text('', 15, 10)
.addClass('highcharts-legend-navigation')
.add(nav);
this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
.on('click', function() {
legend.scroll(1, animation);
})
.add(nav);
}
// Set initial position
legend.scroll(0);
legendHeight = spaceHeight;
} else if (nav) {
clipToHeight(chart.chartHeight);
nav.hide();
this.scrollGroup.attr({
translateY: 1
});
this.clipHeight = 0; // #1379
}
return legendHeight;
},
/**
* Scroll the legend by a number of pages
* @param {Object} scrollBy
* @param {Object} animation
*/
scroll: function(scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== undefined) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: 'visible'
});
this.up.attr({
'class': currentPage === 1 ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active'
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.down.attr({
'x': 18 + this.pager.getBBox().width, // adjust to text width
'class': currentPage === pageCount ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active'
});
scrollOffset = -pages[currentPage - 1] + this.initialItemY;
this.scrollGroup.animate({
translateY: scrollOffset
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
}
};
/*
* LegendSymbolMixin
*/
H.LegendSymbolMixin = {
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawRectangle: function(legend, item) {
var options = legend.options,
symbolHeight = options.symbolHeight || legend.fontMetrics.f,
square = options.squareSymbol,
symbolWidth = square ? symbolHeight : legend.symbolWidth;
item.legendSymbol = this.chart.renderer.rect(
square ? (legend.symbolWidth - symbolHeight) / 2 : 0,
legend.baseline - symbolHeight + 1, // #3988
symbolWidth,
symbolHeight,
pick(legend.options.symbolRadius, symbolHeight / 2)
)
.addClass('highcharts-point')
.attr({
zIndex: 3
}).add(item.legendGroup);
},
/**
* Get the series' symbol in the legend. This method should be overridable to create custom
* symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
*
* @param {Object} legend The legend object
*/
drawLineMarker: function(legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendSymbol,
symbolWidth = legend.symbolWidth,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline - Math.round(legend.fontMetrics.b * 0.3),
attr = {};
// Draw the line
this.legendLine = renderer.path([
'M',
0,
verticalCenter,
'L',
symbolWidth,
verticalCenter
])
.addClass('highcharts-graph')
.attr(attr)
.add(legendItemGroup);
// Draw the marker
if (markerOptions && markerOptions.enabled !== false) {
radius = this.symbol.indexOf('url') === 0 ? 0 : markerOptions.radius;
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius,
markerOptions
)
.addClass('highcharts-point')
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
}
};
// Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
// and for #2580, a similar drawing flaw in Firefox 26.
// Explore if there's a general cause for this. The problem may be related
// to nested group elements, as the legend item texts are within 4 group elements.
if (/Trident\/7\.0/.test(win.navigator.userAgent) || isFirefox) {
wrap(Legend.prototype, 'positionItem', function(proceed, item) {
var legend = this,
runPositionItem = function() { // If chart destroyed in sync, this is undefined (#2030)
if (item._legendItemPos) {
proceed.call(legend, item);
}
};
// Do it now, for export and to get checkbox placement
runPositionItem();
// Do it after to work around the core issue
setTimeout(runPositionItem);
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animate = H.animate,
animObject = H.animObject,
attr = H.attr,
doc = H.doc,
Axis = H.Axis, // @todo add as requirement
createElement = H.createElement,
defaultOptions = H.defaultOptions,
discardElement = H.discardElement,
charts = H.charts,
css = H.css,
defined = H.defined,
each = H.each,
error = H.error,
extend = H.extend,
fireEvent = H.fireEvent,
getStyle = H.getStyle,
grep = H.grep,
isNumber = H.isNumber,
isObject = H.isObject,
isString = H.isString,
Legend = H.Legend, // @todo add as requirement
marginNames = H.marginNames,
merge = H.merge,
Pointer = H.Pointer, // @todo add as requirement
pick = H.pick,
pInt = H.pInt,
removeEvent = H.removeEvent,
seriesTypes = H.seriesTypes,
splat = H.splat,
svg = H.svg,
syncTimeout = H.syncTimeout,
win = H.win,
Renderer = H.Renderer;
/**
* The Chart class
* @param {String|Object} renderTo The DOM element to render to, or its id
* @param {Object} options
* @param {Function} callback Function to run when the chart has loaded
*/
var Chart = H.Chart = function() {
this.getArgs.apply(this, arguments);
};
H.chart = function(a, b, c) {
return new Chart(a, b, c);
};
Chart.prototype = {
/**
* Hook for modules
*/
callbacks: [],
/**
* Handle the arguments passed to the constructor
* @returns {Array} Arguments without renderTo
*/
getArgs: function() {
var args = [].slice.call(arguments);
// Remove the optional first argument, renderTo, and
// set it on this.
if (isString(args[0]) || args[0].nodeName) {
this.renderTo = args.shift();
}
this.init(args[0], args[1]);
},
/**
* Initialize the chart
*/
init: function(userOptions, callback) {
// Handle regular options
var options,
seriesOptions = userOptions.series; // skip merging data points to increase performance
userOptions.series = null;
options = merge(defaultOptions, userOptions); // do the merge
options.series = userOptions.series = seriesOptions; // set back the series data
this.userOptions = userOptions;
this.respRules = [];
var optionsChart = options.chart;
var chartEvents = optionsChart.events;
this.margin = [];
this.spacing = [];
//this.runChartClick = chartEvents && !!chartEvents.click;
this.bounds = {
h: {},
v: {}
}; // Pixel data bounds for touch zoom
this.callback = callback;
this.isResizing = 0;
this.options = options;
//chartTitleOptions = undefined;
//chartSubtitleOptions = undefined;
this.axes = [];
this.series = [];
this.hasCartesianSeries = optionsChart.showAxes;
//this.axisOffset = undefined;
//this.inverted = undefined;
//this.loadingShown = undefined;
//this.container = undefined;
//this.chartWidth = undefined;
//this.chartHeight = undefined;
//this.marginRight = undefined;
//this.marginBottom = undefined;
//this.containerWidth = undefined;
//this.containerHeight = undefined;
//this.oldChartWidth = undefined;
//this.oldChartHeight = undefined;
//this.renderTo = undefined;
//this.renderToClone = undefined;
//this.spacingBox = undefined
//this.legend = undefined;
// Elements
//this.chartBackground = undefined;
//this.plotBackground = undefined;
//this.plotBGImage = undefined;
//this.plotBorder = undefined;
//this.loadingDiv = undefined;
//this.loadingSpan = undefined;
var chart = this,
eventType;
// Add the chart to the global lookup
chart.index = charts.length;
charts.push(chart);
H.chartCount++;
// Chart event handlers
if (chartEvents) {
for (eventType in chartEvents) {
addEvent(chart, eventType, chartEvents[eventType]);
}
}
chart.xAxis = [];
chart.yAxis = [];
chart.pointCount = chart.colorCounter = chart.symbolCounter = 0;
chart.firstRender();
},
/**
* Initialize an individual series, called internally before render time
*/
initSeries: function(options) {
var chart = this,
optionsChart = chart.options.chart,
type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
series,
Constr = seriesTypes[type];
// No such series type
if (!Constr) {
error(17, true);
}
series = new Constr();
series.init(this, options);
return series;
},
/**
* Check whether a given point is within the plot area
*
* @param {Number} plotX Pixel x relative to the plot area
* @param {Number} plotY Pixel y relative to the plot area
* @param {Boolean} inverted Whether the chart is inverted
*/
isInsidePlot: function(plotX, plotY, inverted) {
var x = inverted ? plotY : plotX,
y = inverted ? plotX : plotY;
return x >= 0 &&
x <= this.plotWidth &&
y >= 0 &&
y <= this.plotHeight;
},
/**
* Redraw legend, axes or series based on updated data
*
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
redraw: function(animation) {
var chart = this,
axes = chart.axes,
series = chart.series,
pointer = chart.pointer,
legend = chart.legend,
redrawLegend = chart.isDirtyLegend,
hasStackedSeries,
hasDirtyStacks,
hasCartesianSeries = chart.hasCartesianSeries,
isDirtyBox = chart.isDirtyBox,
seriesLength = series.length,
i = seriesLength,
serie,
renderer = chart.renderer,
isHiddenChart = renderer.isHidden(),
afterRedraw = [];
H.setAnimation(animation, chart);
if (isHiddenChart) {
chart.cloneRenderTo();
}
// Adjust title layout (reflow multiline text)
chart.layOutTitles();
// link stacked series
while (i--) {
serie = series[i];
if (serie.options.stacking) {
hasStackedSeries = true;
if (serie.isDirty) {
hasDirtyStacks = true;
break;
}
}
}
if (hasDirtyStacks) { // mark others as dirty
i = seriesLength;
while (i--) {
serie = series[i];
if (serie.options.stacking) {
serie.isDirty = true;
}
}
}
// Handle updated data in the series
each(series, function(serie) {
if (serie.isDirty) {
if (serie.options.legendType === 'point') {
if (serie.updateTotals) {
serie.updateTotals();
}
redrawLegend = true;
}
}
if (serie.isDirtyData) {
fireEvent(serie, 'updatedData');
}
});
// handle added or removed series
if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
// draw legend graphics
legend.render();
chart.isDirtyLegend = false;
}
// reset stacks
if (hasStackedSeries) {
chart.getStacks();
}
if (hasCartesianSeries) {
// set axes scales
each(axes, function(axis) {
axis.updateNames();
axis.setScale();
});
}
chart.getMargins(); // #3098
if (hasCartesianSeries) {
// If one axis is dirty, all axes must be redrawn (#792, #2169)
each(axes, function(axis) {
if (axis.isDirty) {
isDirtyBox = true;
}
});
// redraw axes
each(axes, function(axis) {
// Fire 'afterSetExtremes' only if extremes are set
var key = axis.min + ',' + axis.max;
if (axis.extKey !== key) { // #821, #4452
axis.extKey = key;
afterRedraw.push(function() { // prevent a recursive call to chart.redraw() (#1119)
fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
delete axis.eventArgs;
});
}
if (isDirtyBox || hasStackedSeries) {
axis.redraw();
}
});
}
// the plot areas size has changed
if (isDirtyBox) {
chart.drawChartBox();
}
// redraw affected series
each(series, function(serie) {
if ((isDirtyBox || serie.isDirty) && serie.visible) {
serie.redraw();
}
});
// move tooltip or reset
if (pointer) {
pointer.reset(true);
}
// redraw if canvas
renderer.draw();
// fire the event
fireEvent(chart, 'redraw');
if (isHiddenChart) {
chart.cloneRenderTo(true);
}
// Fire callbacks that are put on hold until after the redraw
each(afterRedraw, function(callback) {
callback.call();
});
},
/**
* Get an axis, series or point object by id.
* @param id {String} The id as given in the configuration options
*/
get: function(id) {
var chart = this,
axes = chart.axes,
series = chart.series;
var i,
j,
points;
// search axes
for (i = 0; i < axes.length; i++) {
if (axes[i].options.id === id) {
return axes[i];
}
}
// search series
for (i = 0; i < series.length; i++) {
if (series[i].options.id === id) {
return series[i];
}
}
// search points
for (i = 0; i < series.length; i++) {
points = series[i].points || [];
for (j = 0; j < points.length; j++) {
if (points[j].id === id) {
return points[j];
}
}
}
return null;
},
/**
* Create the Axis instances based on the config options
*/
getAxes: function() {
var chart = this,
options = this.options,
xAxisOptions = options.xAxis = splat(options.xAxis || {}),
yAxisOptions = options.yAxis = splat(options.yAxis || {}),
optionsArray;
// make sure the options are arrays and add some members
each(xAxisOptions, function(axis, i) {
axis.index = i;
axis.isX = true;
});
each(yAxisOptions, function(axis, i) {
axis.index = i;
});
// concatenate all axis options into one array
optionsArray = xAxisOptions.concat(yAxisOptions);
each(optionsArray, function(axisOptions) {
new Axis(chart, axisOptions); // eslint-disable-line no-new
});
},
/**
* Get the currently selected points from all series
*/
getSelectedPoints: function() {
var points = [];
each(this.series, function(serie) {
points = points.concat(grep(serie.points || [], function(point) {
return point.selected;
}));
});
return points;
},
/**
* Get the currently selected series
*/
getSelectedSeries: function() {
return grep(this.series, function(serie) {
return serie.selected;
});
},
/**
* Show the title and subtitle of the chart
*
* @param titleOptions {Object} New title options
* @param subtitleOptions {Object} New subtitle options
*
*/
setTitle: function(titleOptions, subtitleOptions, redraw) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function(arr, i) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
chart[name] = chart.renderer.text(
chartTitleOptions.text,
0,
0,
chartTitleOptions.useHTML
)
.attr({
align: chartTitleOptions.align,
'class': 'highcharts-' + name,
zIndex: chartTitleOptions.zIndex || 4
})
.add();
// Update methods, shortcut to Chart.setTitle
chart[name].update = function(o) {
chart.setTitle(!i && o, i && o);
};
}
});
chart.layOutTitles(redraw);
},
/**
* Lay out the chart titles and cache the full offset height for use in getMargins
*/
layOutTitles: function(redraw) {
var titleOffset = 0,
requiresDirtyBox,
renderer = this.renderer,
spacingBox = this.spacingBox;
// Lay out the title and the subtitle respectively
each(['title', 'subtitle'], function(key) {
var title = this[key],
titleOptions = this.options[key],
titleSize;
if (title) {
titleSize = renderer.fontMetrics(titleSize, title).b;
title
.css({
width: (titleOptions.width || spacingBox.width + titleOptions.widthAdjust) + 'px'
})
.align(extend({
y: titleOffset + titleSize + (key === 'title' ? -3 : 2)
}, titleOptions), false, 'spacingBox');
if (!titleOptions.floating && !titleOptions.verticalAlign) {
titleOffset = Math.ceil(titleOffset + title.getBBox().height);
}
}
}, this);
requiresDirtyBox = this.titleOffset !== titleOffset;
this.titleOffset = titleOffset; // used in getMargins
if (!this.isDirtyBox && requiresDirtyBox) {
this.isDirtyBox = requiresDirtyBox;
// Redraw if necessary (#2719, #2744)
if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
this.redraw();
}
}
},
/**
* Get chart width and height according to options and container size
*/
getChartSize: function() {
var chart = this,
optionsChart = chart.options.chart,
widthOption = optionsChart.width,
heightOption = optionsChart.height,
renderTo = chart.renderToClone || chart.renderTo;
// Get inner width and height
if (!defined(widthOption)) {
chart.containerWidth = getStyle(renderTo, 'width');
}
if (!defined(heightOption)) {
chart.containerHeight = getStyle(renderTo, 'height');
}
chart.chartWidth = Math.max(0, widthOption || chart.containerWidth || 600); // #1393, 1460
chart.chartHeight = Math.max(0, pick(heightOption,
// the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
chart.containerHeight > 19 ? chart.containerHeight : 400));
},
/**
* Create a clone of the chart's renderTo div and place it outside the viewport to allow
* size computation on chart.render and chart.redraw
*/
cloneRenderTo: function(revert) {
var clone = this.renderToClone,
container = this.container;
// Destroy the clone and bring the container back to the real renderTo div
if (revert) {
if (clone) {
while (clone.childNodes.length) { // #5231
this.renderTo.appendChild(clone.firstChild);
}
discardElement(clone);
delete this.renderToClone;
}
// Set up the clone
} else {
if (container && container.parentNode === this.renderTo) {
this.renderTo.removeChild(container); // do not clone this
}
this.renderToClone = clone = this.renderTo.cloneNode(0);
css(clone, {
position: 'absolute',
top: '-9999px',
display: 'block' // #833
});
if (clone.style.setProperty) { // #2631
clone.style.setProperty('display', 'block', 'important');
}
doc.body.appendChild(clone);
if (container) {
clone.appendChild(container);
}
}
},
/**
* Setter for the chart class name
*/
setClassName: function(className) {
this.container.className = 'highcharts-container ' + (className || '');
},
/**
* Get the containing element, determine the size and create the inner container
* div to hold the chart
*/
getContainer: function() {
var chart = this,
container,
options = chart.options,
optionsChart = options.chart,
chartWidth,
chartHeight,
renderTo = chart.renderTo,
indexAttrName = 'data-highcharts-chart',
oldChartIndex,
Ren,
containerId = 'highcharts-' + H.idCounter++,
containerStyle,
key;
if (!renderTo) {
chart.renderTo = renderTo = optionsChart.renderTo;
}
if (isString(renderTo)) {
chart.renderTo = renderTo = doc.getElementById(renderTo);
}
// Display an error if the renderTo is wrong
if (!renderTo) {
error(13, true);
}
// If the container already holds a chart, destroy it. The check for hasRendered is there
// because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart
// attribute and the SVG contents, but not an interactive chart. So in this case,
// charts[oldChartIndex] will point to the wrong chart if any (#2609).
oldChartIndex = pInt(attr(renderTo, indexAttrName));
if (isNumber(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) {
charts[oldChartIndex].destroy();
}
// Make a reference to the chart from the div
attr(renderTo, indexAttrName, chart.index);
// remove previous chart
renderTo.innerHTML = '';
// If the container doesn't have an offsetWidth, it has or is a child of a node
// that has display:none. We need to temporarily move it out to a visible
// state to determine the size, else the legend and tooltips won't render
// properly. The allowClone option is used in sparklines as a micro optimization,
// saving about 1-2 ms each chart.
if (!optionsChart.skipClone && !renderTo.offsetWidth) {
chart.cloneRenderTo();
}
// get the width and height
chart.getChartSize();
chartWidth = chart.chartWidth;
chartHeight = chart.chartHeight;
// Create the inner container
chart.container = container = createElement(
'div', {
id: containerId
},
containerStyle,
chart.renderToClone || renderTo
);
// cache the cursor (#1650)
chart._cursor = container.style.cursor;
// Initialize the renderer
Ren = H[optionsChart.renderer] || Renderer;
chart.renderer = new Ren(
container,
chartWidth,
chartHeight,
null,
optionsChart.forExport,
options.exporting && options.exporting.allowHTML
);
chart.setClassName(optionsChart.className);
// Initialize definitions
for (key in options.defs) {
this.renderer.definition(options.defs[key]);
}
// Add a reference to the charts index
chart.renderer.chartIndex = chart.index;
},
/**
* Calculate margins by rendering axis labels in a preliminary position. Title,
* subtitle and legend have already been rendered at this stage, but will be
* moved into their final positions
*/
getMargins: function(skipAxes) {
var chart = this,
spacing = chart.spacing,
margin = chart.margin,
titleOffset = chart.titleOffset;
chart.resetMargins();
// Adjust for title and subtitle
if (titleOffset && !defined(margin[0])) {
chart.plotTop = Math.max(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
}
// Adjust for legend
if (chart.legend.display) {
chart.legend.adjustMargins(margin, spacing);
}
// adjust for scroller
if (chart.extraBottomMargin) {
chart.marginBottom += chart.extraBottomMargin;
}
if (chart.extraTopMargin) {
chart.plotTop += chart.extraTopMargin;
}
if (!skipAxes) {
this.getAxisMargins();
}
},
getAxisMargins: function() {
var chart = this,
axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left
margin = chart.margin;
// pre-render axes to get labels offset width
if (chart.hasCartesianSeries) {
each(chart.axes, function(axis) {
if (axis.visible) {
axis.getOffset();
}
});
}
// Add the axis offsets
each(marginNames, function(m, side) {
if (!defined(margin[side])) {
chart[m] += axisOffset[side];
}
});
chart.setChartSize();
},
/**
* Resize the chart to its container if size is not explicitly set
*/
reflow: function(e) {
var chart = this,
optionsChart = chart.options.chart,
renderTo = chart.renderTo,
hasUserWidth = defined(optionsChart.width),
width = optionsChart.width || getStyle(renderTo, 'width'),
height = optionsChart.height || getStyle(renderTo, 'height'),
target = e ? e.target : win;
// Width and height checks for display:none. Target is doc in IE8 and Opera,
// win in Firefox, Chrome and IE9.
if (!hasUserWidth && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093
if (width !== chart.containerWidth || height !== chart.containerHeight) {
clearTimeout(chart.reflowTimeout);
// When called from window.resize, e is set, else it's called directly (#2224)
chart.reflowTimeout = syncTimeout(function() {
if (chart.container) { // It may have been destroyed in the meantime (#1257)
chart.setSize(undefined, undefined, false);
}
}, e ? 100 : 0);
}
chart.containerWidth = width;
chart.containerHeight = height;
}
},
/**
* Add the event handlers necessary for auto resizing
*/
initReflow: function() {
var chart = this,
reflow = function(e) {
chart.reflow(e);
};
addEvent(win, 'resize', reflow);
addEvent(chart, 'destroy', function() {
removeEvent(win, 'resize', reflow);
});
// The following will add listeners to re-fit the chart before and after
// printing (#2284). However it only works in WebKit. Should have worked
// in Firefox, but not supported in IE.
/*
if (win.matchMedia) {
win.matchMedia('print').addListener(function reflow() {
chart.reflow();
});
}
*/
},
/**
* Resize the chart to a given width and height
* @param {Number} width
* @param {Number} height
* @param {Object|Boolean} animation
*/
setSize: function(width, height, animation) {
var chart = this,
renderer = chart.renderer,
globalAnimation;
// Handle the isResizing counter
chart.isResizing += 1;
// set the animation for the current process
H.setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (width !== undefined) {
chart.options.chart.width = width;
}
if (height !== undefined) {
chart.options.chart.height = height;
}
chart.getChartSize();
// Resize the container with the global animation applied if enabled (#2503)
chart.setChartSize(true);
renderer.setSize(chart.chartWidth, chart.chartHeight, animation);
// handle axes
each(chart.axes, function(axis) {
axis.isDirty = true;
axis.setScale();
});
chart.isDirtyLegend = true; // force legend redraw
chart.isDirtyBox = true; // force redraw of plot and chart border
chart.layOutTitles(); // #2857
chart.getMargins();
if (chart.setResponsive) {
chart.setResponsive(false);
}
chart.redraw(animation);
chart.oldChartHeight = null;
fireEvent(chart, 'resize');
// Fire endResize and set isResizing back. If animation is disabled, fire without delay
syncTimeout(function() {
if (chart) {
fireEvent(chart, 'endResize', null, function() {
chart.isResizing -= 1;
});
}
}, animObject(globalAnimation).duration);
},
/**
* Set the public chart properties. This is done before and after the pre-render
* to determine margin sizes
*/
setChartSize: function(skipAxes) {
var chart = this,
inverted = chart.inverted,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
optionsChart = chart.options.chart,
spacing = chart.spacing,
clipOffset = chart.clipOffset,
clipX,
clipY,
plotLeft,
plotTop,
plotWidth,
plotHeight,
plotBorderWidth;
chart.plotLeft = plotLeft = Math.round(chart.plotLeft);
chart.plotTop = plotTop = Math.round(chart.plotTop);
chart.plotWidth = plotWidth = Math.max(0, Math.round(chartWidth - plotLeft - chart.marginRight));
chart.plotHeight = plotHeight = Math.max(0, Math.round(chartHeight - plotTop - chart.marginBottom));
chart.plotSizeX = inverted ? plotHeight : plotWidth;
chart.plotSizeY = inverted ? plotWidth : plotHeight;
chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
// Set boxes used for alignment
chart.spacingBox = renderer.spacingBox = {
x: spacing[3],
y: spacing[0],
width: chartWidth - spacing[3] - spacing[1],
height: chartHeight - spacing[0] - spacing[2]
};
chart.plotBox = renderer.plotBox = {
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
};
plotBorderWidth = 2 * Math.floor(chart.plotBorderWidth / 2);
clipX = Math.ceil(Math.max(plotBorderWidth, clipOffset[3]) / 2);
clipY = Math.ceil(Math.max(plotBorderWidth, clipOffset[0]) / 2);
chart.clipBox = {
x: clipX,
y: clipY,
width: Math.floor(chart.plotSizeX - Math.max(plotBorderWidth, clipOffset[1]) / 2 - clipX),
height: Math.max(0, Math.floor(chart.plotSizeY - Math.max(plotBorderWidth, clipOffset[2]) / 2 - clipY))
};
if (!skipAxes) {
each(chart.axes, function(axis) {
axis.setAxisSize();
axis.setAxisTranslation();
});
}
},
/**
* Initial margins before auto size margins are applied
*/
resetMargins: function() {
var chart = this,
chartOptions = chart.options.chart;
// Create margin and spacing array
each(['margin', 'spacing'], function splashArrays(target) {
var value = chartOptions[target],
values = isObject(value) ? value : [value, value, value, value];
each(['Top', 'Right', 'Bottom', 'Left'], function(sideName, side) {
chart[target][side] = pick(chartOptions[target + sideName], values[side]);
});
});
// Set margin names like chart.plotTop, chart.plotLeft, chart.marginRight, chart.marginBottom.
each(marginNames, function(m, side) {
chart[m] = pick(chart.margin[side], chart.spacing[side]);
});
chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
chart.clipOffset = [0, 0, 0, 0];
},
/**
* Draw the borders and backgrounds for chart and plot area
*/
drawChartBox: function() {
var chart = this,
optionsChart = chart.options.chart,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
chartBackground = chart.chartBackground,
plotBackground = chart.plotBackground,
plotBorder = chart.plotBorder,
chartBorderWidth,
mgn,
bgAttr,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
plotBox = chart.plotBox,
clipRect = chart.clipRect,
clipBox = chart.clipBox,
verb = 'animate';
// Chart area
if (!chartBackground) {
chart.chartBackground = chartBackground = renderer.rect()
.addClass('highcharts-background')
.add();
verb = 'attr';
}
chartBorderWidth = mgn = chartBackground.strokeWidth();
chartBackground[verb]({
x: mgn / 2,
y: mgn / 2,
width: chartWidth - mgn - chartBorderWidth % 2,
height: chartHeight - mgn - chartBorderWidth % 2,
r: optionsChart.borderRadius
});
// Plot background
verb = 'animate';
if (!plotBackground) {
verb = 'attr';
chart.plotBackground = plotBackground = renderer.rect()
.addClass('highcharts-plot-background')
.add();
}
plotBackground[verb](plotBox);
// Plot clip
if (!clipRect) {
chart.clipRect = renderer.clipRect(clipBox);
} else {
clipRect.animate({
width: clipBox.width,
height: clipBox.height
});
}
// Plot area border
verb = 'animate';
if (!plotBorder) {
verb = 'attr';
chart.plotBorder = plotBorder = renderer.rect()
.addClass('highcharts-plot-border')
.attr({
zIndex: 1 // Above the grid
})
.add();
}
plotBorder[verb](plotBorder.crisp({
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
}, -plotBorder.strokeWidth())); //#3282 plotBorder should be negative;
// reset
chart.isDirtyBox = false;
},
/**
* Detect whether a certain chart property is needed based on inspecting its options
* and series. This mainly applies to the chart.inverted property, and in extensions to
* the chart.angular and chart.polar properties.
*/
propFromSeries: function() {
var chart = this,
optionsChart = chart.options.chart,
klass,
seriesOptions = chart.options.series,
i,
value;
each(['inverted', 'angular', 'polar'], function(key) {
// The default series type's class
klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
// Get the value from available chart-wide properties
value =
optionsChart[key] || // It is set in the options
(klass && klass.prototype[key]); // The default series class requires it
// 4. Check if any the chart's series require it
i = seriesOptions && seriesOptions.length;
while (!value && i--) {
klass = seriesTypes[seriesOptions[i].type];
if (klass && klass.prototype[key]) {
value = true;
}
}
// Set the chart property
chart[key] = value;
});
},
/**
* Link two or more series together. This is done initially from Chart.render,
* and after Chart.addSeries and Series.remove.
*/
linkSeries: function() {
var chart = this,
chartSeries = chart.series;
// Reset links
each(chartSeries, function(series) {
series.linkedSeries.length = 0;
});
// Apply new links
each(chartSeries, function(series) {
var linkedTo = series.options.linkedTo;
if (isString(linkedTo)) {
if (linkedTo === ':previous') {
linkedTo = chart.series[series.index - 1];
} else {
linkedTo = chart.get(linkedTo);
}
if (linkedTo && linkedTo.linkedParent !== series) { // #3341 avoid mutual linking
linkedTo.linkedSeries.push(series);
series.linkedParent = linkedTo;
series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879
}
}
});
},
/**
* Render series for the chart
*/
renderSeries: function() {
each(this.series, function(serie) {
serie.translate();
serie.render();
});
},
/**
* Render labels for the chart
*/
renderLabels: function() {
var chart = this,
labels = chart.options.labels;
if (labels.items) {
each(labels.items, function(label) {
var style = extend(labels.style, label.style),
x = pInt(style.left) + chart.plotLeft,
y = pInt(style.top) + chart.plotTop + 12;
// delete to prevent rewriting in IE
delete style.left;
delete style.top;
chart.renderer.text(
label.html,
x,
y
)
.attr({
zIndex: 2
})
.css(style)
.add();
});
}
},
/**
* Render all graphics for the chart
*/
render: function() {
var chart = this,
axes = chart.axes,
renderer = chart.renderer,
options = chart.options,
tempWidth,
tempHeight,
redoHorizontal,
redoVertical;
// Title
chart.setTitle();
// Legend
chart.legend = new Legend(chart, options.legend);
// Get stacks
if (chart.getStacks) {
chart.getStacks();
}
// Get chart margins
chart.getMargins(true);
chart.setChartSize();
// Record preliminary dimensions for later comparison
tempWidth = chart.plotWidth;
tempHeight = chart.plotHeight = chart.plotHeight - 21; // 21 is the most common correction for X axis labels
// Get margins by pre-rendering axes
each(axes, function(axis) {
axis.setScale();
});
chart.getAxisMargins();
// If the plot area size has changed significantly, calculate tick positions again
redoHorizontal = tempWidth / chart.plotWidth > 1.1;
redoVertical = tempHeight / chart.plotHeight > 1.05; // Height is more sensitive
if (redoHorizontal || redoVertical) {
each(axes, function(axis) {
if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) {
axis.setTickInterval(true); // update to reflect the new margins
}
});
chart.getMargins(); // second pass to check for new labels
}
// Draw the borders and backgrounds
chart.drawChartBox();
// Axes
if (chart.hasCartesianSeries) {
each(axes, function(axis) {
if (axis.visible) {
axis.render();
}
});
}
// The series
if (!chart.seriesGroup) {
chart.seriesGroup = renderer.g('series-group')
.attr({
zIndex: 3
})
.add();
}
chart.renderSeries();
// Labels
chart.renderLabels();
// Credits
chart.addCredits();
// Handle responsiveness
if (chart.setResponsive) {
chart.setResponsive();
}
// Set flag
chart.hasRendered = true;
},
/**
* Show chart credits based on config options
*/
addCredits: function(credits) {
var chart = this;
credits = merge(true, this.options.credits, credits);
if (credits.enabled && !this.credits) {
this.credits = this.renderer.text(
credits.text + (this.mapCredits || ''),
0,
0
)
.addClass('highcharts-credits')
.on('click', function() {
if (credits.href) {
win.location.href = credits.href;
}
})
.attr({
align: credits.position.align,
zIndex: 8
})
.add()
.align(credits.position);
// Dynamically update
this.credits.update = function(options) {
chart.credits = chart.credits.destroy();
chart.addCredits(options);
};
}
},
/**
* Clean up memory usage
*/
destroy: function() {
var chart = this,
axes = chart.axes,
series = chart.series,
container = chart.container,
i,
parentNode = container && container.parentNode;
// fire the chart.destoy event
fireEvent(chart, 'destroy');
// Delete the chart from charts lookup array
charts[chart.index] = undefined;
H.chartCount--;
chart.renderTo.removeAttribute('data-highcharts-chart');
// remove events
removeEvent(chart);
// ==== Destroy collections:
// Destroy axes
i = axes.length;
while (i--) {
axes[i] = axes[i].destroy();
}
// Destroy scroller & scroller series before destroying base series
if (this.scroller && this.scroller.destroy) {
this.scroller.destroy();
}
// Destroy each series
i = series.length;
while (i--) {
series[i] = series[i].destroy();
}
// ==== Destroy chart properties:
each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer',
'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'
], function(name) {
var prop = chart[name];
if (prop && prop.destroy) {
chart[name] = prop.destroy();
}
});
// remove container and all SVG
if (container) { // can break in IE when destroyed before finished loading
container.innerHTML = '';
removeEvent(container);
if (parentNode) {
discardElement(container);
}
}
// clean it all up
for (i in chart) {
delete chart[i];
}
},
/**
* VML namespaces can't be added until after complete. Listening
* for Perini's doScroll hack is not enough.
*/
isReadyToRender: function() {
var chart = this;
// Note: win == win.top is required
if ((!svg && (win == win.top && doc.readyState !== 'complete'))) { // eslint-disable-line eqeqeq
doc.attachEvent('onreadystatechange', function() {
doc.detachEvent('onreadystatechange', chart.firstRender);
if (doc.readyState === 'complete') {
chart.firstRender();
}
});
return false;
}
return true;
},
/**
* Prepare for first rendering after all data are loaded
*/
firstRender: function() {
var chart = this,
options = chart.options;
// Check whether the chart is ready to render
if (!chart.isReadyToRender()) {
return;
}
// Create the container
chart.getContainer();
// Run an early event after the container and renderer are established
fireEvent(chart, 'init');
chart.resetMargins();
chart.setChartSize();
// Set the common chart properties (mainly invert) from the given series
chart.propFromSeries();
// get axes
chart.getAxes();
// Initialize the series
each(options.series || [], function(serieOptions) {
chart.initSeries(serieOptions);
});
chart.linkSeries();
// Run an event after axes and series are initialized, but before render. At this stage,
// the series data is indexed and cached in the xData and yData arrays, so we can access
// those before rendering. Used in Highstock.
fireEvent(chart, 'beforeRender');
// depends on inverted and on margins being set
if (Pointer) {
chart.pointer = new Pointer(chart, options);
}
chart.render();
// add canvas
chart.renderer.draw();
// Fire the load event if there are no external images
if (!chart.renderer.imgCount && chart.onload) {
chart.onload();
}
// If the chart was rendered outside the top container, put it back in (#3679)
chart.cloneRenderTo(true);
},
/**
* On chart load
*/
onload: function() {
// Run callbacks
each([this.callback].concat(this.callbacks), function(fn) {
if (fn && this.index !== undefined) { // Chart destroyed in its own callback (#3600)
fn.apply(this, [this]);
}
}, this);
fireEvent(this, 'load');
// Set up auto resize
if (this.options.chart.reflow !== false) {
this.initReflow();
}
// Don't run again
this.onload = null;
}
}; // end Chart
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Point,
each = H.each,
extend = H.extend,
erase = H.erase,
fireEvent = H.fireEvent,
format = H.format,
isArray = H.isArray,
isNumber = H.isNumber,
pick = H.pick,
removeEvent = H.removeEvent;
/**
* The Point object and prototype. Inheritable and used as base for PiePoint
*/
Point = H.Point = function() {};
Point.prototype = {
/**
* Initialize the point
* @param {Object} series The series object containing this point
* @param {Object} options The data in either number, array or object format
*/
init: function(series, options, x) {
var point = this,
colors,
colorCount = series.chart.options.chart.colorCount,
colorIndex;
point.series = series;
point.applyOptions(options, x);
if (series.options.colorByPoint) {
colorIndex = series.colorCounter;
series.colorCounter++;
// loop back to zero
if (series.colorCounter === colorCount) {
series.colorCounter = 0;
}
} else {
colorIndex = series.colorIndex;
}
point.colorIndex = pick(point.colorIndex, colorIndex);
series.chart.pointCount++;
return point;
},
/**
* Apply the options containing the x and y data and possible some extra properties.
* This is called on point init or from point.update.
*
* @param {Object} options
*/
applyOptions: function(options, x) {
var point = this,
series = point.series,
pointValKey = series.options.pointValKey || series.pointValKey;
options = Point.prototype.optionsToObject.call(this, options);
// copy options directly to point
extend(point, options);
point.options = point.options ? extend(point.options, options) : options;
// Since options are copied into the Point instance, some accidental options must be shielded (#5681)
if (options.group) {
delete point.group;
}
// For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
if (pointValKey) {
point.y = point[pointValKey];
}
point.isNull = pick(
point.isValid && !point.isValid(),
point.x === null || !isNumber(point.y, true)
); // #3571, check for NaN
// The point is initially selected by options (#5777)
if (point.selected) {
point.state = 'select';
}
// If no x is set by now, get auto incremented value. All points must have an
// x value, however the y value can be null to create a gap in the series
if ('name' in point && x === undefined && series.xAxis && series.xAxis.hasNames) {
point.x = series.xAxis.nameToX(point);
}
if (point.x === undefined && series) {
if (x === undefined) {
point.x = series.autoIncrement(point);
} else {
point.x = x;
}
}
return point;
},
/**
* Transform number or array configs into objects
*/
optionsToObject: function(options) {
var ret = {},
series = this.series,
keys = series.options.keys,
pointArrayMap = keys || series.pointArrayMap || ['y'],
valueCount = pointArrayMap.length,
firstItemType,
i = 0,
j = 0;
if (isNumber(options) || options === null) {
ret[pointArrayMap[0]] = options;
} else if (isArray(options)) {
// with leading x value
if (!keys && options.length > valueCount) {
firstItemType = typeof options[0];
if (firstItemType === 'string') {
ret.name = options[0];
} else if (firstItemType === 'number') {
ret.x = options[0];
}
i++;
}
while (j < valueCount) {
if (!keys || options[i] !== undefined) { // Skip undefined positions for keys
ret[pointArrayMap[j]] = options[i];
}
i++;
j++;
}
} else if (typeof options === 'object') {
ret = options;
// This is the fastest way to detect if there are individual point dataLabels that need
// to be considered in drawDataLabels. These can only occur in object configs.
if (options.dataLabels) {
series._hasPointLabels = true;
}
// Same approach as above for markers
if (options.marker) {
series._hasPointMarkers = true;
}
}
return ret;
},
/**
* Get the CSS class names for individual points
* @returns {String} The class name
*/
getClassName: function() {
return 'highcharts-point' +
(this.selected ? ' highcharts-point-select' : '') +
(this.negative ? ' highcharts-negative' : '') +
(this.isNull ? ' highcharts-null-point' : '') +
(this.colorIndex !== undefined ? ' highcharts-color-' + this.colorIndex : '') +
(this.options.className ? ' ' + this.options.className : '');
},
/**
* Return the zone that the point belongs to
*/
getZone: function() {
var series = this.series,
zones = series.zones,
zoneAxis = series.zoneAxis || 'y',
i = 0,
zone;
zone = zones[i];
while (this[zoneAxis] >= zone.value) {
zone = zones[++i];
}
if (zone && zone.color && !this.options.color) {
this.color = zone.color;
}
return zone;
},
/**
* Destroy a point to clear memory. Its reference still stays in series.data.
*/
destroy: function() {
var point = this,
series = point.series,
chart = series.chart,
hoverPoints = chart.hoverPoints,
prop;
chart.pointCount--;
if (hoverPoints) {
point.setState();
erase(hoverPoints, point);
if (!hoverPoints.length) {
chart.hoverPoints = null;
}
}
if (point === chart.hoverPoint) {
point.onMouseOut();
}
// remove all events
if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
removeEvent(point);
point.destroyElements();
}
if (point.legendItem) { // pies have legend items
chart.legend.destroyItem(point);
}
for (prop in point) {
point[prop] = null;
}
},
/**
* Destroy SVG elements associated with the point
*/
destroyElements: function() {
var point = this,
props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'],
prop,
i = 6;
while (i--) {
prop = props[i];
if (point[prop]) {
point[prop] = point[prop].destroy();
}
}
},
/**
* Return the configuration hash needed for the data label and tooltip formatters
*/
getLabelConfig: function() {
return {
x: this.category,
y: this.y,
color: this.color,
key: this.name || this.category,
series: this.series,
point: this,
percentage: this.percentage,
total: this.total || this.stackTotal
};
},
/**
* Extendable method for formatting each point's tooltip line
*
* @return {String} A string to be concatenated in to the common tooltip text
*/
tooltipFormatter: function(pointFormat) {
// Insert options for valueDecimals, valuePrefix, and valueSuffix
var series = this.series,
seriesTooltipOptions = series.tooltipOptions,
valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
valuePrefix = seriesTooltipOptions.valuePrefix || '',
valueSuffix = seriesTooltipOptions.valueSuffix || '';
// Loop over the point array map and replace unformatted values with sprintf formatting markup
each(series.pointArrayMap || ['y'], function(key) {
key = '{point.' + key; // without the closing bracket
if (valuePrefix || valueSuffix) {
pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
}
pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
});
return format(pointFormat, {
point: this,
series: this.series
});
},
/**
* Fire an event on the Point object.
* @param {String} eventType
* @param {Object} eventArgs Additional event arguments
* @param {Function} defaultFunction Default event handler
*/
firePointEvent: function(eventType, eventArgs, defaultFunction) {
var point = this,
series = this.series,
seriesOptions = series.options;
// load event handlers on demand to save time on mouseover/out
if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
this.importEvents();
}
// add default handler if in selection mode
if (eventType === 'click' && seriesOptions.allowPointSelect) {
defaultFunction = function(event) {
// Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
if (point.select) { // Could be destroyed by prior event handlers (#2911)
point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
}
};
}
fireEvent(this, eventType, eventArgs, defaultFunction);
},
visible: true
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animObject = H.animObject,
arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
correctFloat = H.correctFloat,
Date = H.Date,
defaultOptions = H.defaultOptions,
defaultPlotOptions = H.defaultPlotOptions,
defined = H.defined,
each = H.each,
erase = H.erase,
error = H.error,
extend = H.extend,
fireEvent = H.fireEvent,
grep = H.grep,
isArray = H.isArray,
isNumber = H.isNumber,
isString = H.isString,
LegendSymbolMixin = H.LegendSymbolMixin, // @todo add as a requirement
merge = H.merge,
pick = H.pick,
Point = H.Point, // @todo add as a requirement
removeEvent = H.removeEvent,
splat = H.splat,
stableSort = H.stableSort,
SVGElement = H.SVGElement,
syncTimeout = H.syncTimeout,
win = H.win;
/**
* @classDescription The base function which all other series types inherit from. The data in the series is stored
* in various arrays.
*
* - First, series.options.data contains all the original config options for
* each point whether added by options or methods like series.addPoint.
* - Next, series.data contains those values converted to points, but in case the series data length
* exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
* only contains the points that have been created on demand.
* - Then there's series.points that contains all currently visible point objects. In case of cropping,
* the cropped-away points are not part of this array. The series.points array starts at series.cropStart
* compared to series.data and series.options.data. If however the series data is grouped, these can't
* be correlated one to one.
* - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
* - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
*
* @param {Object} chart
* @param {Object} options
*/
H.Series = H.seriesType('line', null, { // base series options
allowPointSelect: false,
showCheckbox: false,
animation: {
duration: 1000
},
//clip: true,
//connectNulls: false,
//enableMouseTracking: true,
events: {},
//legendIndex: 0,
// stacking: null,
marker: {
//enabled: true,
//symbol: null,
radius: 4,
states: { // states for a single point
hover: {
animation: {
duration: 50
},
enabled: true,
radiusPlus: 2
}
}
},
point: {
events: {}
},
dataLabels: {
align: 'center',
// defer: true,
// enabled: false,
formatter: function() {
return this.y === null ? '' : H.numberFormat(this.y, -1);
},
/*style: {
color: 'contrast',
textShadow: '0 0 6px contrast, 0 0 3px contrast'
},*/
verticalAlign: 'bottom', // above singular point
x: 0,
y: 0,
// borderRadius: undefined,
padding: 5
},
cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
pointRange: 0,
//pointStart: 0,
//pointInterval: 1,
//showInLegend: null, // auto: true for standalone series, false for linked series
softThreshold: true,
states: { // states for the entire series
hover: {
//enabled: false,
lineWidthPlus: 1,
marker: {
// lineWidth: base + 1,
// radius: base + 1
},
halo: {
size: 10
}
},
select: {
marker: {}
}
},
stickyTracking: true,
//tooltip: {
//pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>'
//valueDecimals: null,
//xDateFormat: '%A, %b %e, %Y',
//valuePrefix: '',
//ySuffix: ''
//}
turboThreshold: 1000
// zIndex: null
// Prototype properties
}, {
isCartesian: true,
pointClass: Point,
sorted: true, // requires the data to be sorted
requireSorting: true,
directTouch: false,
axisTypes: ['xAxis', 'yAxis'],
colorCounter: 0,
parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
coll: 'series',
init: function(chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series,
sortByIndex = function(a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, b._i);
};
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: '',
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// Set the data
each(series.parallelArrays, function(key) {
series[key + 'Data'] = [];
});
series.setData(options.data, false);
// Mark cartesian
if (series.isCartesian) {
chart.hasCartesianSeries = true;
}
// Register it in the chart
chartSeries.push(series);
series._i = chartSeries.length - 1;
// Sort series according to index option (#248, #1123, #2456)
stableSort(chartSeries, sortByIndex);
if (this.yAxis) {
stableSort(this.yAxis.series, sortByIndex);
}
each(chartSeries, function(series, i) {
series.index = i;
series.name = series.name || 'Series ' + (i + 1);
});
},
/**
* Set the xAxis and yAxis properties of cartesian series, and register the series
* in the axis.series array
*/
bindAxes: function() {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
each(series.axisTypes || [], function(AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function(axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== undefined && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === undefined && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
// set this series.xAxis or series.yAxis reference
series[AXIS] = axis;
// mark dirty for redraw
axis.isDirty = true;
}
});
// The series needs an X and an Y axis
if (!series[AXIS] && series.optionalAxis !== AXIS) {
error(18, true);
}
});
},
/**
* For simple series types like line and column, the data values are held in arrays like
* xData and yData for quick lookup to find extremes and more. For multidimensional series
* like bubble and map, this can be extended with arrays like zData and valueData by
* adding to the series.parallelArrays array.
*/
updateParallelArrays: function(point, i) {
var series = point.series,
args = arguments,
fn = isNumber(i) ?
// Insert the value in the given position
function(key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} :
// Apply the method specified in i with the following arguments as arguments
function(key) {
Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
};
each(series.parallelArrays, fn);
},
/**
* Return an auto incremented x value based on the pointStart and pointInterval options.
* This is only used if an x value is not given for the point that calls autoIncrement.
*/
autoIncrement: function() {
var options = this.options,
xIncrement = this.xIncrement,
date,
pointInterval,
pointIntervalUnit = options.pointIntervalUnit;
xIncrement = pick(xIncrement, options.pointStart, 0);
this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1);
// Added code for pointInterval strings
if (pointIntervalUnit) {
date = new Date(xIncrement);
if (pointIntervalUnit === 'day') {
date = +date[Date.hcSetDate](date[Date.hcGetDate]() + pointInterval);
} else if (pointIntervalUnit === 'month') {
date = +date[Date.hcSetMonth](date[Date.hcGetMonth]() + pointInterval);
} else if (pointIntervalUnit === 'year') {
date = +date[Date.hcSetFullYear](date[Date.hcGetFullYear]() + pointInterval);
}
pointInterval = date - xIncrement;
}
this.xIncrement = xIncrement + pointInterval;
return xIncrement;
},
/**
* Set the series options by merging from the options tree
* @param {Object} itemOptions
*/
setOptions: function(itemOptions) {
var chart = this.chart,
chartOptions = chart.options,
plotOptions = chartOptions.plotOptions,
userOptions = chart.userOptions || {},
userPlotOptions = userOptions.plotOptions || {},
typeOptions = plotOptions[this.type],
options,
zones;
this.userOptions = itemOptions;
// General series options take precedence over type options because otherwise, default
// type options like column.animation would be overwritten by the general option.
// But issues have been raised here (#3881), and the solution may be to distinguish
// between default option and userOptions like in the tooltip below.
options = merge(
typeOptions,
plotOptions.series,
itemOptions
);
// The tooltip options are merged between global and series specific options
this.tooltipOptions = merge(
defaultOptions.tooltip,
defaultOptions.plotOptions[this.type].tooltip,
userOptions.tooltip,
userPlotOptions.series && userPlotOptions.series.tooltip,
userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
itemOptions.tooltip
);
// Delete marker object if not allowed (#1125)
if (typeOptions.marker === null) {
delete options.marker;
}
// Handle color zones
this.zoneAxis = options.zoneAxis;
zones = this.zones = (options.zones || []).slice();
if ((options.negativeColor || options.negativeFillColor) && !options.zones) {
zones.push({
value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0,
className: 'highcharts-negative'
});
}
if (zones.length) { // Push one extra zone for the rest
if (defined(zones[zones.length - 1].value)) {
zones.push({
});
}
}
return options;
},
getCyclic: function(prop, value, defaults) {
var i,
userOptions = this.userOptions,
indexName = prop + 'Index',
counterName = prop + 'Counter',
len = defaults ? defaults.length : pick(this.chart.options.chart[prop + 'Count'], this.chart[prop + 'Count']),
setting;
if (!value) {
// Pick up either the colorIndex option, or the _colorIndex after Series.update()
setting = pick(userOptions[indexName], userOptions['_' + indexName]);
if (defined(setting)) { // after Series.update()
i = setting;
} else {
userOptions['_' + indexName] = i = this.chart[counterName] % len;
this.chart[counterName] += 1;
}
if (defaults) {
value = defaults[i];
}
}
// Set the colorIndex
if (i !== undefined) {
this[indexName] = i;
}
this[prop] = value;
},
/**
* Get the series' color
*/
getColor: function() {
this.getCyclic('color');
},
/**
* Get the series' symbol
*/
getSymbol: function() {
var seriesMarkerOption = this.options.marker;
this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols);
},
drawLegendSymbol: LegendSymbolMixin.drawLineMarker,
/**
* Replace the series data with a new set of data
* @param {Object} data
* @param {Object} redraw
*/
setData: function(data, redraw, animation, updatePoints) {
var series = this,
oldData = series.points,
oldDataLength = (oldData && oldData.length) || 0,
dataLength,
options = series.options,
chart = series.chart,
firstPoint = null,
xAxis = series.xAxis,
i,
turboThreshold = options.turboThreshold,
pt,
xData = this.xData,
yData = this.yData,
pointArrayMap = series.pointArrayMap,
valueCount = pointArrayMap && pointArrayMap.length;
data = data || [];
dataLength = data.length;
redraw = pick(redraw, true);
// If the point count is the same as is was, just run Point.update which is
// cheaper, allows animation, and keeps references to points.
if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) {
each(data, function(point, i) {
// .update doesn't exist on a linked, hidden series (#3709)
if (oldData[i].update && point !== options.data[i]) {
oldData[i].update(point, false, null, false);
}
});
} else {
// Reset properties
series.xIncrement = null;
series.colorCounter = 0; // for series with colorByPoint (#1547)
// Update parallel arrays
each(this.parallelArrays, function(key) {
series[key + 'Data'].length = 0;
});
// In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
// first value is tested, and we assume that all the rest are defined the same
// way. Although the 'for' loops are similar, they are repeated inside each
// if-else conditional for max performance.
if (turboThreshold && dataLength > turboThreshold) {
// find the first non-null point
i = 0;
while (firstPoint === null && i < dataLength) {
firstPoint = data[i];
i++;
}
if (isNumber(firstPoint)) { // assume all points are numbers
for (i = 0; i < dataLength; i++) {
xData[i] = this.autoIncrement();
yData[i] = data[i];
}
} else if (isArray(firstPoint)) { // assume all points are arrays
if (valueCount) { // [x, low, high] or [x, o, h, l, c]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt.slice(1, valueCount + 1);
}
} else { // [x, y]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt[1];
}
}
} else {
error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
}
} else {
for (i = 0; i < dataLength; i++) {
if (data[i] !== undefined) { // stray commas in oldIE
pt = {
series: series
};
series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
series.updateParallelArrays(pt, i);
}
}
}
// Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
if (isString(yData[0])) {
error(14, true);
}
series.data = [];
series.options.data = series.userOptions.data = data;
// destroy old points
i = oldDataLength;
while (i--) {
if (oldData[i] && oldData[i].destroy) {
oldData[i].destroy();
}
}
// reset minRange (#878)
if (xAxis) {
xAxis.minRange = xAxis.userMinRange;
}
// redraw
series.isDirty = chart.isDirtyBox = true;
series.isDirtyData = !!oldData;
animation = false;
}
// Typically for pie series, points need to be processed and generated
// prior to rendering the legend
if (options.legendType === 'point') {
this.processData();
this.generatePoints();
}
if (redraw) {
chart.redraw(animation);
}
},
/**
* Process the data by cropping away unused data points if the series is longer
* than the crop threshold. This saves computing time for lage series.
*/
processData: function(force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599
isCartesian = series.isCartesian,
xExtremes,
val2lin = xAxis && xAxis.val2lin,
isLog = xAxis && xAxis.isLog,
min,
max;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
if (xAxis) {
xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
min = xExtremes.min;
max = xExtremes.max;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
}
}
// Find the closest distance between processed points
i = processedXData.length || 1;
while (--i) {
distance = isLog ?
val2lin(processedXData[i]) - val2lin(processedXData[i - 1]) :
processedXData[i] - processedXData[i - 1];
if (distance > 0 && (closestPointRange === undefined || distance < closestPointRange)) {
closestPointRange = distance;
// Unsorted data is not supported by the line tooltip, as well as data grouping and
// navigation in Stock charts (#725) and width calculation of columns (#1900)
} else if (distance < 0 && series.requireSorting) {
error(15);
}
}
// Record the properties
series.cropped = cropped; // undefined or true
series.cropStart = cropStart;
series.processedXData = processedXData;
series.processedYData = processedYData;
series.closestPointRange = closestPointRange;
},
/**
* Iterate over xData and crop values between min and max. Returns object containing crop start/end
* cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
*/
cropData: function(xData, yData, min, max) {
var dataLength = xData.length,
cropStart = 0,
cropEnd = dataLength,
cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
i,
j;
// iterate up to find slice start
for (i = 0; i < dataLength; i++) {
if (xData[i] >= min) {
cropStart = Math.max(0, i - cropShoulder);
break;
}
}
// proceed to find slice end
for (j = i; j < dataLength; j++) {
if (xData[j] > max) {
cropEnd = j + cropShoulder;
break;
}
}
return {
xData: xData.slice(cropStart, cropEnd),
yData: yData.slice(cropStart, cropEnd),
start: cropStart,
end: cropEnd
};
},
/**
* Generate the data point after the data has been processed by cropping away
* unused points and optionally grouped in Highcharts Stock.
*/
generatePoints: function() {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
PointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
point = data[cursor];
} else if (dataOptions[cursor] !== undefined) { // #970
data[cursor] = point = (new PointClass()).init(series, dataOptions[cursor], processedXData[i]);
}
points[i] = point;
} else {
// splat the y data in case of ohlc data array
points[i] = (new PointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
points[i].dataGroup = series.groupMap[i];
}
points[i].index = cursor; // For faster access in Point.update
}
// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
// swithching view from non-grouped data to grouped data (#637)
if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
for (i = 0; i < dataLength; i++) {
if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
i += processedDataLength;
}
if (data[i]) {
data[i].destroyElements();
data[i].plotX = undefined; // #1003
}
}
}
series.data = data;
series.points = points;
},
/**
* Calculate Y extremes for visible data
*/
getExtremes: function(yData) {
var xAxis = this.xAxis,
yAxis = this.yAxis,
xData = this.processedXData,
yDataLength,
activeYData = [],
activeCounter = 0,
xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
xMin = xExtremes.min,
xMax = xExtremes.max,
validValue,
withinRange,
x,
y,
i,
j;
yData = yData || this.stackedYData || this.processedYData || [];
yDataLength = yData.length;
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
// For points within the visible range, including the first point outside the
// visible range, consider y extremes
validValue = (isNumber(y, true) || isArray(y)) && (!yAxis.isLog || (y.length || y > 0));
withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped ||
((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax);
if (validValue && withinRange) {
j = y.length;
if (j) { // array, like ohlc or range data
while (j--) {
if (y[j] !== null) {
activeYData[activeCounter++] = y[j];
}
}
} else {
activeYData[activeCounter++] = y;
}
}
}
this.dataMin = arrayMin(activeYData);
this.dataMax = arrayMax(activeYData);
},
/**
* Translate data points from raw data values to chart specific positioning data
* needed later in drawPoints, drawGraph and drawTracker.
*/
translate: function() {
if (!this.processedXData) { // hidden series
this.processData();
}
this.generatePoints();
var series = this,
options = series.options,
stacking = options.stacking,
xAxis = series.xAxis,
categories = xAxis.categories,
yAxis = series.yAxis,
points = series.points,
dataLength = points.length,
hasModifyValue = !!series.modifyValue,
i,
pointPlacement = options.pointPlacement,
dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
threshold = options.threshold,
stackThreshold = options.startFromThreshold ? threshold : 0,
plotX,
plotY,
lastPlotX,
stackIndicator,
closestPointRangePx = Number.MAX_VALUE;
// Translate each point
for (i = 0; i < dataLength; i++) {
var point = points[i],
xValue = point.x,
yValue = point.y,
yBottom = point.low,
stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey],
pointStack,
stackValues;
// Discard disallowed y values for log axes (#3434)
if (yAxis.isLog && yValue !== null && yValue <= 0) {
point.isNull = true;
}
// Get the plotX translation
point.plotX = plotX = correctFloat( // #5236
Math.min(Math.max(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5) // #3923
);
// Calculate the bottom y value for stacked series
if (stacking && series.visible && !point.isNull && stack && stack[xValue]) {
stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index);
pointStack = stack[xValue];
stackValues = pointStack.points[stackIndicator.key];
yBottom = stackValues[0];
yValue = stackValues[1];
if (yBottom === stackThreshold && stackIndicator.key === stack[xValue].base) {
yBottom = pick(threshold, yAxis.min);
}
if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
yBottom = null;
}
point.total = point.stackTotal = pointStack.total;
point.percentage = pointStack.total && (point.y / pointStack.total * 100);
point.stackY = yValue;
// Place the stack label
pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
}
// Set translated yBottom or remove it
point.yBottom = defined(yBottom) ?
yAxis.translate(yBottom, 0, 1, 0, 1) :
null;
// general hook, used for Highstock compare mode
if (hasModifyValue) {
yValue = series.modifyValue(yValue, point);
}
// Set the the plotY value, reset it for redraws
point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
Math.min(Math.max(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201
undefined;
point.isInside = plotY !== undefined && plotY >= 0 && plotY <= yAxis.len && // #3519
plotX >= 0 && plotX <= xAxis.len;
// Set client related positions for mouse tracking
point.clientX = dynamicallyPlaced ? correctFloat(xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement)) : plotX; // #1514, #5383, #5518
point.negative = point.y < (threshold || 0);
// some API data
point.category = categories && categories[point.x] !== undefined ?
categories[point.x] : point.x;
// Determine auto enabling of markers (#3635, #5099)
if (!point.isNull) {
if (lastPlotX !== undefined) {
closestPointRangePx = Math.min(closestPointRangePx, Math.abs(plotX - lastPlotX));
}
lastPlotX = plotX;
}
}
series.closestPointRangePx = closestPointRangePx;
},
/**
* Return the series points with null points filtered out
*/
getValidPoints: function(points, insideOnly) {
var chart = this.chart;
return grep(points || this.points || [], function isValidPoint(point) { // #3916, #5029
if (insideOnly && !chart.isInsidePlot(point.plotX, point.plotY, chart.inverted)) { // #5085
return false;
}
return !point.isNull;
});
},
/**
* Set the clipping for the series. For animated series it is called twice, first to initiate
* animating the clip then the second time without the animation to set the final clip.
*/
setClip: function(animation) {
var chart = this.chart,
options = this.options,
renderer = chart.renderer,
inverted = chart.inverted,
seriesClipBox = this.clipBox,
clipBox = seriesClipBox || chart.clipBox,
sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526
clipRect = chart[sharedClipKey],
markerClipRect = chart[sharedClipKey + 'm'];
// If a clipping rectangle with the same properties is currently present in the chart, use that.
if (!clipRect) {
// When animation is set, prepare the initial positions
if (animation) {
clipBox.width = 0;
chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(-99, // include the width of the first marker
inverted ? -chart.plotLeft : -chart.plotTop,
99,
inverted ? chart.chartWidth : chart.chartHeight
);
}
chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox);
// Create hashmap for series indexes
clipRect.count = {
length: 0
};
}
if (animation) {
if (!clipRect.count[this.index]) {
clipRect.count[this.index] = true;
clipRect.count.length += 1;
}
}
if (options.clip !== false) {
this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect);
this.markerGroup.clip(markerClipRect);
this.sharedClipKey = sharedClipKey;
}
// Remove the shared clipping rectangle when all series are shown
if (!animation) {
if (clipRect.count[this.index]) {
delete clipRect.count[this.index];
clipRect.count.length -= 1;
}
if (clipRect.count.length === 0 && sharedClipKey && chart[sharedClipKey]) {
if (!seriesClipBox) {
chart[sharedClipKey] = chart[sharedClipKey].destroy();
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
}
}
}
},
/**
* Animate in the series
*/
animate: function(init) {
var series = this,
chart = series.chart,
clipRect,
animation = animObject(series.options.animation),
sharedClipKey;
// Initialize the animation. Set up the clipping rectangle.
if (init) {
series.setClip(animation);
// Run the animation
} else {
sharedClipKey = this.sharedClipKey;
clipRect = chart[sharedClipKey];
if (clipRect) {
clipRect.animate({
width: chart.plotSizeX
}, animation);
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'].animate({
width: chart.plotSizeX + 99
}, animation);
}
// Delete this function to allow it only once
series.animate = null;
}
},
/**
* This runs after animation to land on the final plot clipping
*/
afterAnimate: function() {
this.setClip();
fireEvent(this, 'afterAnimate');
},
/**
* Draw the markers
*/
drawPoints: function() {
var series = this,
points = series.points,
chart = series.chart,
plotY,
i,
point,
symbol,
graphic,
options = series.options,
seriesMarkerOptions = options.marker,
pointMarkerOptions,
hasPointMarker,
enabled,
isInside,
markerGroup = series.markerGroup,
xAxis = series.xAxis,
markerAttribs,
globallyEnabled = pick(
seriesMarkerOptions.enabled,
xAxis.isRadial ? true : null,
series.closestPointRangePx > 2 * seriesMarkerOptions.radius
);
if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {
i = points.length;
while (i--) {
point = points[i];
plotY = point.plotY;
graphic = point.graphic;
pointMarkerOptions = point.marker || {};
hasPointMarker = !!point.marker;
enabled = (globallyEnabled && pointMarkerOptions.enabled === undefined) || pointMarkerOptions.enabled;
isInside = point.isInside;
// only draw the point if y is defined
if (enabled && isNumber(plotY) && point.y !== null) {
// Shortcuts
symbol = pick(pointMarkerOptions.symbol, series.symbol);
point.hasImage = symbol.indexOf('url') === 0;
markerAttribs = series.markerAttribs(
point,
point.selected && 'select'
);
if (graphic) { // update
graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
.animate(markerAttribs);
} else if (isInside && (markerAttribs.width > 0 || point.hasImage)) {
point.graphic = graphic = chart.renderer.symbol(
symbol,
markerAttribs.x,
markerAttribs.y,
markerAttribs.width,
markerAttribs.height,
hasPointMarker ? pointMarkerOptions : seriesMarkerOptions
)
.add(markerGroup);
}
if (graphic) {
graphic.addClass(point.getClassName(), true);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
}
}
},
/**
* Get non-presentational attributes for the point.
*/
markerAttribs: function(point, state) {
var seriesMarkerOptions = this.options.marker,
seriesStateOptions,
pointOptions = point && point.options,
pointMarkerOptions = (pointOptions && pointOptions.marker) || {},
pointStateOptions,
radius = pick(
pointMarkerOptions.radius,
seriesMarkerOptions.radius
),
attribs;
// Handle hover and select states
if (state) {
seriesStateOptions = seriesMarkerOptions.states[state];
pointStateOptions = pointMarkerOptions.states &&
pointMarkerOptions.states[state];
radius = pick(
pointStateOptions && pointStateOptions.radius,
seriesStateOptions && seriesStateOptions.radius,
radius + (seriesStateOptions && seriesStateOptions.radiusPlus || 0)
);
}
if (point.hasImage) {
radius = 0; // and subsequently width and height is not set
}
attribs = {
x: Math.floor(point.plotX) - radius, // Math.floor for #1843
y: point.plotY - radius
};
if (radius) {
attribs.width = attribs.height = 2 * radius;
}
return attribs;
},
/**
* Clear DOM objects and free up memory
*/
destroy: function() {
var series = this,
chart = series.chart,
issue134 = /AppleWebKit\/533/.test(win.navigator.userAgent),
destroy,
i,
data = series.data || [],
point,
prop,
axis;
// add event hook
fireEvent(series, 'destroy');
// remove all events
removeEvent(series);
// erase from axes
each(series.axisTypes || [], function(AXIS) {
axis = series[AXIS];
if (axis && axis.series) {
erase(axis.series, series);
axis.isDirty = axis.forceRedraw = true;
}
});
// remove legend items
if (series.legendItem) {
series.chart.legend.destroyItem(series);
}
// destroy all points with their elements
i = data.length;
while (i--) {
point = data[i];
if (point && point.destroy) {
point.destroy();
}
}
series.points = null;
// Clear the animation timeout if we are destroying the series during initial animation
clearTimeout(series.animationTimeout);
// Destroy all SVGElements associated to the series
for (prop in series) {
if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying
// issue 134 workaround
destroy = issue134 && prop === 'group' ?
'hide' :
'destroy';
series[prop][destroy]();
}
}
// remove from hoverSeries
if (chart.hoverSeries === series) {
chart.hoverSeries = null;
}
erase(chart.series, series);
// clear all members
for (prop in series) {
delete series[prop];
}
},
/**
* Get the graph path
*/
getGraphPath: function(points, nullsAsZeroes, connectCliffs) {
var series = this,
options = series.options,
step = options.step,
reversed,
graphPath = [],
xMap = [],
gap;
points = points || series.points;
// Bottom of a stack is reversed
reversed = points.reversed;
if (reversed) {
points.reverse();
}
// Reverse the steps (#5004)
step = {
right: 1,
center: 2
}[step] || (step && 3);
if (step && reversed) {
step = 4 - step;
}
// Remove invalid points, especially in spline (#5015)
if (options.connectNulls && !nullsAsZeroes && !connectCliffs) {
points = this.getValidPoints(points);
}
// Build the line
each(points, function(point, i) {
var plotX = point.plotX,
plotY = point.plotY,
lastPoint = points[i - 1],
pathToPoint; // the path to this point from the previous
if ((point.leftCliff || (lastPoint && lastPoint.rightCliff)) && !connectCliffs) {
gap = true; // ... and continue
}
// Line series, nullsAsZeroes is not handled
if (point.isNull && !defined(nullsAsZeroes) && i > 0) {
gap = !options.connectNulls;
// Area series, nullsAsZeroes is set
} else if (point.isNull && !nullsAsZeroes) {
gap = true;
} else {
if (i === 0 || gap) {
pathToPoint = ['M', point.plotX, point.plotY];
} else if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
pathToPoint = series.getPointSpline(points, point, i);
} else if (step) {
if (step === 1) { // right
pathToPoint = [
'L',
lastPoint.plotX,
plotY
];
} else if (step === 2) { // center
pathToPoint = [
'L',
(lastPoint.plotX + plotX) / 2,
lastPoint.plotY,
'L',
(lastPoint.plotX + plotX) / 2,
plotY
];
} else {
pathToPoint = [
'L',
plotX,
lastPoint.plotY
];
}
pathToPoint.push('L', plotX, plotY);
} else {
// normal line to next point
pathToPoint = [
'L',
plotX,
plotY
];
}
// Prepare for animation. When step is enabled, there are two path nodes for each x value.
xMap.push(point.x);
if (step) {
xMap.push(point.x);
}
graphPath.push.apply(graphPath, pathToPoint);
gap = false;
}
});
graphPath.xMap = xMap;
series.graphPath = graphPath;
return graphPath;
},
/**
* Draw the actual graph
*/
drawGraph: function() {
var series = this,
options = this.options,
graphPath = (this.gappedPath || this.getGraphPath).call(this),
props = [
[
'graph',
'highcharts-graph'
]
];
// Add the zone properties if any
each(this.zones, function(zone, i) {
props.push([
'zone-graph-' + i,
'highcharts-graph highcharts-zone-graph-' + i + ' ' + (zone.className || '')
]);
});
// Draw the graph
each(props, function(prop, i) {
var graphKey = prop[0],
graph = series[graphKey],
attribs;
if (graph) {
graph.endX = graphPath.xMap;
graph.animate({
d: graphPath
});
} else if (graphPath.length) { // #1487
series[graphKey] = series.chart.renderer.path(graphPath)
.addClass(prop[1])
.attr({
zIndex: 1
}) // #1069
.add(series.group);
}
// Helpers for animation
if (graph) {
graph.startX = graphPath.xMap;
//graph.shiftUnit = options.step ? 2 : 1;
graph.isArea = graphPath.isArea; // For arearange animation
}
});
},
/**
* Clip the graphs into the positive and negative coloured graphs
*/
applyZones: function() {
var series = this,
chart = this.chart,
renderer = chart.renderer,
zones = this.zones,
translatedFrom,
translatedTo,
clips = this.clips || [],
clipAttr,
graph = this.graph,
area = this.area,
chartSizeMax = Math.max(chart.chartWidth, chart.chartHeight),
axis = this[(this.zoneAxis || 'y') + 'Axis'],
extremes,
reversed,
inverted = chart.inverted,
horiz,
pxRange,
pxPosMin,
pxPosMax,
ignoreZones = false;
if (zones.length && (graph || area) && axis && axis.min !== undefined) {
reversed = axis.reversed;
horiz = axis.horiz;
// The use of the Color Threshold assumes there are no gaps
// so it is safe to hide the original graph and area
if (graph) {
graph.hide();
}
if (area) {
area.hide();
}
// Create the clips
extremes = axis.getExtremes();
each(zones, function(threshold, i) {
translatedFrom = reversed ?
(horiz ? chart.plotWidth : 0) :
(horiz ? 0 : axis.toPixels(extremes.min));
translatedFrom = Math.min(Math.max(pick(translatedTo, translatedFrom), 0), chartSizeMax);
translatedTo = Math.min(Math.max(Math.round(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax);
if (ignoreZones) {
translatedFrom = translatedTo = axis.toPixels(extremes.max);
}
pxRange = Math.abs(translatedFrom - translatedTo);
pxPosMin = Math.min(translatedFrom, translatedTo);
pxPosMax = Math.max(translatedFrom, translatedTo);
if (axis.isXAxis) {
clipAttr = {
x: inverted ? pxPosMax : pxPosMin,
y: 0,
width: pxRange,
height: chartSizeMax
};
if (!horiz) {
clipAttr.x = chart.plotHeight - clipAttr.x;
}
} else {
clipAttr = {
x: 0,
y: inverted ? pxPosMax : pxPosMin,
width: chartSizeMax,
height: pxRange
};
if (horiz) {
clipAttr.y = chart.plotWidth - clipAttr.y;
}
}
if (clips[i]) {
clips[i].animate(clipAttr);
} else {
clips[i] = renderer.clipRect(clipAttr);
if (graph) {
series['zone-graph-' + i].clip(clips[i]);
}
if (area) {
series['zone-area-' + i].clip(clips[i]);
}
}
// if this zone extends out of the axis, ignore the others
ignoreZones = threshold.value > extremes.max;
});
this.clips = clips;
}
},
/**
* Initialize and perform group inversion on series.group and series.markerGroup
*/
invertGroups: function(inverted) {
var series = this,
chart = series.chart;
// Pie, go away (#1736)
if (!series.xAxis) {
return;
}
// A fixed size is needed for inversion to work
function setInvert() {
var size = {
width: series.yAxis.len,
height: series.xAxis.len
};
each(['group', 'markerGroup'], function(groupName) {
if (series[groupName]) {
series[groupName].attr(size).invert(inverted);
}
});
}
addEvent(chart, 'resize', setInvert); // do it on resize
addEvent(series, 'destroy', function() {
removeEvent(chart, 'resize', setInvert);
});
// Do it now
setInvert(inverted); // do it now
// On subsequent render and redraw, just do setInvert without setting up events again
series.invertGroups = setInvert;
},
/**
* General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
* series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
*/
plotGroup: function(prop, name, visibility, zIndex, parent) {
var group = this[prop],
isNew = !group;
// Generate it on first call
if (isNew) {
this[prop] = group = this.chart.renderer.g(name)
.attr({
zIndex: zIndex || 0.1 // IE8 and pointer logic use this
})
.add(parent);
group.addClass('highcharts-series-' + this.index + ' highcharts-' + this.type + '-series highcharts-color-' + this.colorIndex +
' ' + (this.options.className || ''));
}
// Place it on first and subsequent (redraw) calls
group.attr({
visibility: visibility
})[isNew ? 'attr' : 'animate'](this.getPlotBox());
return group;
},
/**
* Get the translation and scale for the plot area of this series
*/
getPlotBox: function() {
var chart = this.chart,
xAxis = this.xAxis,
yAxis = this.yAxis;
// Swap axes for inverted (#2339)
if (chart.inverted) {
xAxis = yAxis;
yAxis = this.xAxis;
}
return {
translateX: xAxis ? xAxis.left : chart.plotLeft,
translateY: yAxis ? yAxis.top : chart.plotTop,
scaleX: 1, // #1623
scaleY: 1
};
},
/**
* Render the graph and markers
*/
render: function() {
var series = this,
chart = series.chart,
group,
options = series.options,
// Animation doesn't work in IE8 quirks when the group div is hidden,
// and looks bad in other oldIE
animDuration = !!series.animate && chart.renderer.isSVG && animObject(options.animation).duration,
visibility = series.visible ? 'inherit' : 'hidden', // #2597
zIndex = options.zIndex,
hasRendered = series.hasRendered,
chartSeriesGroup = chart.seriesGroup,
inverted = chart.inverted;
// the group
group = series.plotGroup(
'group',
'series',
visibility,
zIndex,
chartSeriesGroup
);
series.markerGroup = series.plotGroup(
'markerGroup',
'markers',
visibility,
zIndex,
chartSeriesGroup
);
// initiate the animation
if (animDuration) {
series.animate(true);
}
// SVGRenderer needs to know this before drawing elements (#1089, #1795)
group.inverted = series.isCartesian ? inverted : false;
// draw the graph if any
if (series.drawGraph) {
series.drawGraph();
series.applyZones();
}
/* each(series.points, function (point) {
if (point.redraw) {
point.redraw();
}
});*/
// draw the data labels (inn pies they go before the points)
if (series.drawDataLabels) {
series.drawDataLabels();
}
// draw the points
if (series.visible) {
series.drawPoints();
}
// draw the mouse tracking area
if (series.drawTracker && series.options.enableMouseTracking !== false) {
series.drawTracker();
}
// Handle inverted series and tracker groups
series.invertGroups(inverted);
// Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839).
if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
group.clip(chart.clipRect);
}
// Run the animation
if (animDuration) {
series.animate();
}
// Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
// which should be available to the user).
if (!hasRendered) {
series.animationTimeout = syncTimeout(function() {
series.afterAnimate();
}, animDuration);
}
series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
// (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
series.hasRendered = true;
},
/**
* Redraw the series after an update in the axes.
*/
redraw: function() {
var series = this,
chart = series.chart,
wasDirty = series.isDirty || series.isDirtyData, // cache it here as it is set to false in render, but used after
group = series.group,
xAxis = series.xAxis,
yAxis = series.yAxis;
// reposition on resize
if (group) {
if (chart.inverted) {
group.attr({
width: chart.plotWidth,
height: chart.plotHeight
});
}
group.animate({
translateX: pick(xAxis && xAxis.left, chart.plotLeft),
translateY: pick(yAxis && yAxis.top, chart.plotTop)
});
}
series.translate();
series.render();
if (wasDirty) { // #3868, #3945
delete this.kdTree;
}
},
/**
* KD Tree && PointSearching Implementation
*/
kdDimensions: 1,
kdAxisArray: ['clientX', 'plotY'],
searchPoint: function(e, compareX) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
inverted = series.chart.inverted;
return this.searchKDTree({
clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos,
plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos
}, compareX);
},
buildKDTree: function() {
var series = this,
dimensions = series.kdDimensions;
// Internal function
function _kdtree(points, depth, dimensions) {
var axis,
median,
length = points && points.length;
if (length) {
// alternate between the axis
axis = series.kdAxisArray[depth % dimensions];
// sort point array
points.sort(function(a, b) {
return a[axis] - b[axis];
});
median = Math.floor(length / 2);
// build and return nod
return {
point: points[median],
left: _kdtree(points.slice(0, median), depth + 1, dimensions),
right: _kdtree(points.slice(median + 1), depth + 1, dimensions)
};
}
}
// Start the recursive build process with a clone of the points array and null points filtered out (#3873)
function startRecursive() {
series.kdTree = _kdtree(
series.getValidPoints(
null, !series.directTouch // For line-type series restrict to plot area, but column-type series not (#3916, #4511)
),
dimensions,
dimensions
);
}
delete series.kdTree;
// For testing tooltips, don't build async
syncTimeout(startRecursive, series.options.kdNow ? 0 : 1);
},
searchKDTree: function(point, compareX) {
var series = this,
kdX = this.kdAxisArray[0],
kdY = this.kdAxisArray[1],
kdComparer = compareX ? 'distX' : 'dist';
// Set the one and two dimensional distance on the point object
function setDistance(p1, p2) {
var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null,
y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null,
r = (x || 0) + (y || 0);
p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE;
p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE;
}
function _search(search, tree, depth, dimensions) {
var point = tree.point,
axis = series.kdAxisArray[depth % dimensions],
tdist,
sideA,
sideB,
ret = point,
nPoint1,
nPoint2;
setDistance(search, point);
// Pick side based on distance to splitting point
tdist = search[axis] - point[axis];
sideA = tdist < 0 ? 'left' : 'right';
sideB = tdist < 0 ? 'right' : 'left';
// End of tree
if (tree[sideA]) {
nPoint1 = _search(search, tree[sideA], depth + 1, dimensions);
ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point);
}
if (tree[sideB]) {
// compare distance to current best to splitting point to decide wether to check side B or not
if (Math.sqrt(tdist * tdist) < ret[kdComparer]) {
nPoint2 = _search(search, tree[sideB], depth + 1, dimensions);
ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret);
}
}
return ret;
}
if (!this.kdTree) {
this.buildKDTree();
}
if (this.kdTree) {
return _search(point,
this.kdTree, this.kdDimensions, this.kdDimensions);
}
}
}); // end Series prototype
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animate = H.animate,
Axis = H.Axis,
Chart = H.Chart,
createElement = H.createElement,
css = H.css,
defined = H.defined,
each = H.each,
erase = H.erase,
extend = H.extend,
fireEvent = H.fireEvent,
inArray = H.inArray,
isNumber = H.isNumber,
isObject = H.isObject,
merge = H.merge,
pick = H.pick,
Point = H.Point,
Series = H.Series,
seriesTypes = H.seriesTypes,
setAnimation = H.setAnimation,
splat = H.splat;
// Extend the Chart prototype for dynamic methods
extend(Chart.prototype, {
/**
* Add a series dynamically after time
*
* @param {Object} options The config options
* @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
* @return {Object} series The newly created series object
*/
addSeries: function(options, redraw, animation) {
var series,
chart = this;
if (options) {
redraw = pick(redraw, true); // defaults to true
fireEvent(chart, 'addSeries', {
options: options
}, function() {
series = chart.initSeries(options);
chart.isDirtyLegend = true; // the series array is out of sync with the display
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
return series;
},
/**
* Add an axis to the chart
* @param {Object} options The axis option
* @param {Boolean} isX Whether it is an X axis or a value axis
*/
addAxis: function(options, isX, redraw, animation) {
var key = isX ? 'xAxis' : 'yAxis',
chartOptions = this.options,
userOptions = merge(options, {
index: this[key].length,
isX: isX
});
new Axis(this, userOptions); // eslint-disable-line no-new
// Push the new axis options to the chart options
chartOptions[key] = splat(chartOptions[key] || {});
chartOptions[key].push(userOptions);
if (pick(redraw, true)) {
this.redraw(animation);
}
},
/**
* Dim the chart and show a loading text or symbol
* @param {String} str An optional text to show in the loading label instead of the default one
*/
showLoading: function(str) {
var chart = this,
options = chart.options,
loadingDiv = chart.loadingDiv,
loadingOptions = options.loading,
setLoadingSize = function() {
if (loadingDiv) {
css(loadingDiv, {
left: chart.plotLeft + 'px',
top: chart.plotTop + 'px',
width: chart.plotWidth + 'px',
height: chart.plotHeight + 'px'
});
}
};
// create the layer at the first call
if (!loadingDiv) {
chart.loadingDiv = loadingDiv = createElement('div', {
className: 'highcharts-loading highcharts-loading-hidden'
}, null, chart.container);
chart.loadingSpan = createElement(
'span', {
className: 'highcharts-loading-inner'
},
null,
loadingDiv
);
addEvent(chart, 'redraw', setLoadingSize); // #1080
}
loadingDiv.className = 'highcharts-loading';
// Update text
chart.loadingSpan.innerHTML = str || options.lang.loading;
chart.loadingShown = true;
setLoadingSize();
},
/**
* Hide the loading layer
*/
hideLoading: function() {
var options = this.options,
loadingDiv = this.loadingDiv;
if (loadingDiv) {
loadingDiv.className = 'highcharts-loading highcharts-loading-hidden';
}
this.loadingShown = false;
},
/**
* These properties cause isDirtyBox to be set to true when updating. Can be extended from plugins.
*/
propsRequireDirtyBox: ['backgroundColor', 'borderColor', 'borderWidth', 'margin', 'marginTop', 'marginRight',
'marginBottom', 'marginLeft', 'spacing', 'spacingTop', 'spacingRight', 'spacingBottom', 'spacingLeft',
'borderRadius', 'plotBackgroundColor', 'plotBackgroundImage', 'plotBorderColor', 'plotBorderWidth',
'plotShadow', 'shadow'
],
/**
* These properties cause all series to be updated when updating. Can be extended from plugins.
*/
propsRequireUpdateSeries: ['chart.polar', 'chart.ignoreHiddenSeries', 'chart.type', 'colors', 'plotOptions'],
/**
* Chart.update function that takes the whole options stucture.
*/
update: function(options, redraw) {
var key,
adders = {
credits: 'addCredits',
title: 'setTitle',
subtitle: 'setSubtitle'
},
optionsChart = options.chart,
updateAllAxes,
updateAllSeries,
newWidth,
newHeight;
// If the top-level chart option is present, some special updates are required
if (optionsChart) {
merge(true, this.options.chart, optionsChart);
// Setter function
if ('className' in optionsChart) {
this.setClassName(optionsChart.className);
}
if ('inverted' in optionsChart || 'polar' in optionsChart) {
this.propFromSeries(); // Parses options.chart.inverted and options.chart.polar together with the available series
updateAllAxes = true;
}
for (key in optionsChart) {
if (optionsChart.hasOwnProperty(key)) {
if (inArray('chart.' + key, this.propsRequireUpdateSeries) !== -1) {
updateAllSeries = true;
}
// Only dirty box
if (inArray(key, this.propsRequireDirtyBox) !== -1) {
this.isDirtyBox = true;
}
}
}
}
// Some option stuctures correspond one-to-one to chart objects that have
// update methods, for example
// options.credits => chart.credits
// options.legend => chart.legend
// options.title => chart.title
// options.tooltip => chart.tooltip
// options.subtitle => chart.subtitle
// options.navigator => chart.navigator
// options.scrollbar => chart.scrollbar
for (key in options) {
if (this[key] && typeof this[key].update === 'function') {
this[key].update(options[key], false);
// If a one-to-one object does not exist, look for an adder function
} else if (typeof this[adders[key]] === 'function') {
this[adders[key]](options[key]);
}
if (key !== 'chart' && inArray(key, this.propsRequireUpdateSeries) !== -1) {
updateAllSeries = true;
}
}
if (options.plotOptions) {
merge(true, this.options.plotOptions, options.plotOptions);
}
// Setters for collections. For axes and series, each item is referred by an id. If the
// id is not found, it defaults to the first item in the collection, so setting series
// without an id, will update the first series in the chart.
each(['xAxis', 'yAxis', 'series'], function(coll) {
if (options[coll]) {
each(splat(options[coll]), function(newOptions) {
var item = (defined(newOptions.id) && this.get(newOptions.id)) || this[coll][0];
if (item && item.coll === coll) {
item.update(newOptions, false);
}
}, this);
}
}, this);
if (updateAllAxes) {
each(this.axes, function(axis) {
axis.update({}, false);
});
}
// Certain options require the whole series structure to be thrown away
// and rebuilt
if (updateAllSeries) {
each(this.series, function(series) {
series.update({}, false);
});
}
// For loading, just update the options, do not redraw
if (options.loading) {
merge(true, this.options.loading, options.loading);
}
// Update size. Redraw is forced.
newWidth = optionsChart && optionsChart.width;
newHeight = optionsChart && optionsChart.height;
if ((isNumber(newWidth) && newWidth !== this.chartWidth) ||
(isNumber(newHeight) && newHeight !== this.chartHeight)) {
this.setSize(newWidth, newHeight);
} else if (pick(redraw, true)) {
this.redraw();
}
},
/**
* Setter function to allow use from chart.update
*/
setSubtitle: function(options) {
this.setTitle(undefined, options);
}
});
// extend the Point prototype for dynamic methods
extend(Point.prototype, {
/**
* Point.update with new options (typically x/y data) and optionally redraw the series.
*
* @param {Object} options Point options as defined in the series.data array
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
update: function(options, redraw, animation, runEvent) {
var point = this,
series = point.series,
graphic = point.graphic,
i,
chart = series.chart,
seriesOptions = series.options;
redraw = pick(redraw, true);
function update() {
point.applyOptions(options);
// Update visuals
if (point.y === null && graphic) { // #4146
point.graphic = graphic.destroy();
}
if (isObject(options, true)) {
// Destroy so we can get new elements
if (graphic && graphic.element) {
if (options && options.marker && options.marker.symbol) {
point.graphic = graphic.destroy();
}
}
if (options && options.dataLabels && point.dataLabel) { // #2468
point.dataLabel = point.dataLabel.destroy();
}
}
// record changes in the parallel arrays
i = point.index;
series.updateParallelArrays(point, i);
// Record the options to options.data. If there is an object from before,
// use point options, otherwise use raw options. (#4701)
seriesOptions.data[i] = isObject(seriesOptions.data[i], true) ? point.options : options;
// redraw
series.isDirty = series.isDirtyData = true;
if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
chart.isDirtyBox = true;
}
if (seriesOptions.legendType === 'point') { // #1831, #1885
chart.isDirtyLegend = true;
}
if (redraw) {
chart.redraw(animation);
}
}
// Fire the event with a default handler of doing the update
if (runEvent === false) { // When called from setData
update();
} else {
point.firePointEvent('update', {
options: options
}, update);
}
},
/**
* Remove a point and optionally redraw the series and if necessary the axes
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function(redraw, animation) {
this.series.removePoint(inArray(this, this.series.data), redraw, animation);
}
});
// Extend the series prototype for dynamic methods
extend(Series.prototype, {
/**
* Add a point dynamically after chart load time
* @param {Object} options Point options as given in series.data
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean} shift If shift is true, a point is shifted off the start
* of the series as one is appended to the end.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
addPoint: function(options, redraw, shift, animation) {
var series = this,
seriesOptions = series.options,
data = series.data,
chart = series.chart,
names = series.xAxis && series.xAxis.names,
dataOptions = seriesOptions.data,
point,
isInTheMiddle,
xData = series.xData,
i,
x;
// Optional redraw, defaults to true
redraw = pick(redraw, true);
// Get options and push the point to xData, yData and series.options. In series.generatePoints
// the Point instance will be created on demand and pushed to the series.data array.
point = {
series: series
};
series.pointClass.prototype.applyOptions.apply(point, [options]);
x = point.x;
// Get the insertion point
i = xData.length;
if (series.requireSorting && x < xData[i - 1]) {
isInTheMiddle = true;
while (i && xData[i - 1] > x) {
i--;
}
}
series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item
series.updateParallelArrays(point, i); // update it
if (names && point.name) {
names[x] = point.name;
}
dataOptions.splice(i, 0, options);
if (isInTheMiddle) {
series.data.splice(i, 0, null);
series.processData();
}
// Generate points to be added to the legend (#1329)
if (seriesOptions.legendType === 'point') {
series.generatePoints();
}
// Shift the first point off the parallel arrays
if (shift) {
if (data[0] && data[0].remove) {
data[0].remove(false);
} else {
data.shift();
series.updateParallelArrays(point, 'shift');
dataOptions.shift();
}
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw(animation); // Animation is set anyway on redraw, #5665
}
},
/**
* Remove a point (rendered or not), by index
*/
removePoint: function(i, redraw, animation) {
var series = this,
data = series.data,
point = data[i],
points = series.points,
chart = series.chart,
remove = function() {
if (points && points.length === data.length) { // #4935
points.splice(i, 1);
}
data.splice(i, 1);
series.options.data.splice(i, 1);
series.updateParallelArrays(point || {
series: series
}, 'splice', i, 1);
if (point) {
point.destroy();
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw();
}
};
setAnimation(animation, chart);
redraw = pick(redraw, true);
// Fire the event with a default handler of removing the point
if (point) {
point.firePointEvent('remove', null, remove);
} else {
remove();
}
},
/**
* Remove a series and optionally redraw the chart
*
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function(redraw, animation, withEvent) {
var series = this,
chart = series.chart;
function remove() {
// Destroy elements
series.destroy();
// Redraw
chart.isDirtyLegend = chart.isDirtyBox = true;
chart.linkSeries();
if (pick(redraw, true)) {
chart.redraw(animation);
}
}
// Fire the event with a default handler of removing the point
if (withEvent !== false) {
fireEvent(series, 'remove', null, remove);
} else {
remove();
}
},
/**
* Series.update with a new set of options
*/
update: function(newOptions, redraw) {
var series = this,
chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
newType = newOptions.type || oldOptions.type || chart.options.chart.type,
proto = seriesTypes[oldType].prototype,
preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
n;
// If we're changing type or zIndex, create new groups (#3380, #3404)
if ((newType && newType !== oldType) || newOptions.zIndex !== undefined) {
preserve.length = 0;
}
// Make sure groups are not destroyed (#3094)
each(preserve, function(prop) {
preserve[prop] = series[prop];
delete series[prop];
});
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, {
data: this.options.data
}, newOptions);
// Destroy the series and delete all properties. Reinsert all methods
// and properties from the new type prototype (#2270, #3719)
this.remove(false, null, false);
for (n in proto) {
this[n] = undefined;
}
extend(this, seriesTypes[newType || oldType].prototype);
// Re-register groups (#3094)
each(preserve, function(prop) {
series[prop] = preserve[prop];
});
this.init(chart, newOptions);
chart.linkSeries(); // Links are lost in this.remove (#3028)
if (pick(redraw, true)) {
chart.redraw(false);
}
}
});
// Extend the Axis.prototype for dynamic methods
extend(Axis.prototype, {
/**
* Axis.update with a new options structure
*/
update: function(newOptions, redraw) {
var chart = this.chart;
newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions);
this.destroy(true);
this.init(chart, extend(newOptions, {
events: undefined
}));
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Remove the axis from the chart
*/
remove: function(redraw) {
var chart = this.chart,
key = this.coll, // xAxis or yAxis
axisSeries = this.series,
i = axisSeries.length;
// Remove associated series (#2687)
while (i--) {
if (axisSeries[i]) {
axisSeries[i].remove(false);
}
}
// Remove the axis
erase(chart.axes, this);
erase(chart[key], this);
chart.options[key].splice(this.options.index, 1);
each(chart[key], function(axis, i) { // Re-index, #1706
axis.options.index = i;
});
this.destroy();
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Update the axis title by options
*/
setTitle: function(newTitleOptions, redraw) {
this.update({
title: newTitleOptions
}, redraw);
},
/**
* Set new axis categories and optionally redraw
* @param {Array} categories
* @param {Boolean} redraw
*/
setCategories: function(categories, redraw) {
this.update({
categories: categories
}, redraw);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var animObject = H.animObject,
color = H.color,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
LegendSymbolMixin = H.LegendSymbolMixin,
merge = H.merge,
noop = H.noop,
pick = H.pick,
Series = H.Series,
seriesType = H.seriesType,
stop = H.stop,
svg = H.svg;
/**
* The column series type
*/
seriesType('column', 'line', {
borderRadius: 0,
//colorByPoint: undefined,
groupPadding: 0.2,
//grouping: true,
marker: null, // point options are specified in the base options
pointPadding: 0.1,
//pointWidth: null,
minPointLength: 0,
cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
states: {
hover: {
halo: false
}
},
dataLabels: {
align: null, // auto
verticalAlign: null, // auto
y: null
},
softThreshold: false,
startFromThreshold: true, // false doesn't work well: http://jsfiddle.net/highcharts/hz8fopan/14/
stickyTracking: false,
tooltip: {
distance: 6
},
threshold: 0,
// Prototype members
}, {
cropShoulder: 0,
directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
trackerGroups: ['group', 'dataLabelsGroup'],
negStacks: true, // use separate negative stacks, unlike area stacks where a negative
// point is substracted from previous (#1910)
/**
* Initialize the series
*/
init: function() {
Series.prototype.init.apply(this, arguments);
var series = this,
chart = series.chart;
// if the series is added dynamically, force redraw of other
// series affected by a new column
if (chart.hasRendered) {
each(chart.series, function(otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
},
/**
* Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
* pointWidth etc.
*/
getColumnMetrics: function() {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
reversedXAxis = xAxis.reversed,
stackKey,
stackGroups = {},
columnCount = 0;
// Get the total number of column type series.
// This is called on every series. Consider moving this logic to a
// chart.orderStacks() function and call it on init, addSeries and removeSeries
if (options.grouping === false) {
columnCount = 1;
} else {
each(series.chart.series, function(otherSeries) {
var otherOptions = otherSeries.options,
otherYAxis = otherSeries.yAxis,
columnIndex;
if (otherSeries.type === series.type && otherSeries.visible &&
yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
if (otherOptions.stacking) {
stackKey = otherSeries.stackKey;
if (stackGroups[stackKey] === undefined) {
stackGroups[stackKey] = columnCount++;
}
columnIndex = stackGroups[stackKey];
} else if (otherOptions.grouping !== false) { // #1162
columnIndex = columnCount++;
}
otherSeries.columnIndex = columnIndex;
}
});
}
var categoryWidth = Math.min(
Math.abs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
xAxis.len // #1535
),
groupPadding = categoryWidth * options.groupPadding,
groupWidth = categoryWidth - 2 * groupPadding,
pointOffsetWidth = groupWidth / columnCount,
pointWidth = Math.min(
options.maxPointWidth || xAxis.len,
pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding))
),
pointPadding = (pointOffsetWidth - pointWidth) / 2,
colIndex = (series.columnIndex || 0) + (reversedXAxis ? 1 : 0), // #1251, #3737
pointXOffset = pointPadding + (groupPadding + colIndex *
pointOffsetWidth - (categoryWidth / 2)) *
(reversedXAxis ? -1 : 1);
// Save it for reading in linked series (Error bars particularly)
series.columnMetrics = {
width: pointWidth,
offset: pointXOffset
};
return series.columnMetrics;
},
/**
* Make the columns crisp. The edges are rounded to the nearest full pixel.
*/
crispCol: function(x, y, w, h) {
var chart = this.chart,
borderWidth = this.borderWidth,
xCrisp = -(borderWidth % 2 ? 0.5 : 0),
yCrisp = borderWidth % 2 ? 0.5 : 1,
right,
bottom,
fromTop;
if (chart.inverted && chart.renderer.isVML) {
yCrisp += 1;
}
// Horizontal. We need to first compute the exact right edge, then round it
// and compute the width from there.
right = Math.round(x + w) + xCrisp;
x = Math.round(x) + xCrisp;
w = right - x;
// Vertical
bottom = Math.round(y + h) + yCrisp;
fromTop = Math.abs(y) <= 0.5 && bottom > 0.5; // #4504, #4656
y = Math.round(y) + yCrisp;
h = bottom - y;
// Top edges are exceptions
if (fromTop && h) { // #5146
y -= 1;
h += 1;
}
return {
x: x,
y: y,
width: w,
height: h
};
},
/**
* Translate each point to the plot area coordinate system and find shape positions
*/
translate: function() {
var series = this,
chart = series.chart,
options = series.options,
dense = series.dense = series.closestPointRange * series.xAxis.transA < 2,
borderWidth = series.borderWidth = pick(
options.borderWidth,
dense ? 0 : 1 // #3635
),
yAxis = series.yAxis,
threshold = options.threshold,
translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
minPointLength = pick(options.minPointLength, 5),
metrics = series.getColumnMetrics(),
pointWidth = metrics.width,
seriesBarW = series.barW = Math.max(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width
pointXOffset = series.pointXOffset = metrics.offset;
if (chart.inverted) {
translatedThreshold -= 0.5; // #3355
}
// When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual
// columns to have individual sizes. When pointPadding is greater, we strive for equal-width
// columns (#2694).
if (options.pointPadding) {
seriesBarW = Math.ceil(seriesBarW);
}
Series.prototype.translate.apply(series);
// Record the new values
each(series.points, function(point) {
var yBottom = pick(point.yBottom, translatedThreshold),
safeDistance = 999 + Math.abs(yBottom),
plotY = Math.min(Math.max(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264)
barX = point.plotX + pointXOffset,
barW = seriesBarW,
barY = Math.min(plotY, yBottom),
up,
barH = Math.max(plotY, yBottom) - barY;
// Handle options.minPointLength
if (Math.abs(barH) < minPointLength) {
if (minPointLength) {
barH = minPointLength;
up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative);
barY = Math.abs(barY - translatedThreshold) > minPointLength ? // stacked
yBottom - minPointLength : // keep position
translatedThreshold - (up ? minPointLength : 0); // #1485, #4051
}
}
// Cache for access in polar
point.barX = barX;
point.pointWidth = pointWidth;
// Fix the tooltip on center of grouped columns (#1216, #424, #3648)
point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH];
// Register shape type and arguments to be used in drawPoints
point.shapeType = 'rect';
point.shapeArgs = series.crispCol.apply(
series,
point.isNull ? [point.plotX, yAxis.len / 2, 0, 0] : // #3169, drilldown from null must have a position to work from
[barX, barY, barW, barH]
);
});
},
getSymbol: noop,
/**
* Use a solid rectangle like the area series types
*/
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* Columns have no graph
*/
drawGraph: function() {
this.group[this.dense ? 'addClass' : 'removeClass']('highcharts-dense-data');
},
/**
* Draw the columns. For bars, the series.group is rotated, so the same coordinates
* apply for columns and bars. This method is inherited by scatter series.
*
*/
drawPoints: function() {
var series = this,
chart = this.chart,
options = series.options,
renderer = chart.renderer,
animationLimit = options.animationLimit || 250,
shapeArgs;
// draw the columns
each(series.points, function(point) {
var plotY = point.plotY,
graphic = point.graphic;
if (isNumber(plotY) && point.y !== null) {
shapeArgs = point.shapeArgs;
if (graphic) { // update
stop(graphic);
graphic[chart.pointCount < animationLimit ? 'animate' : 'attr'](
merge(shapeArgs)
);
} else {
point.graphic = graphic = renderer[point.shapeType](shapeArgs)
.attr({
'class': point.getClassName()
})
.add(point.group || series.group);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
});
},
/**
* Animate the column heights one by one from zero
* @param {Boolean} init Whether to initialize the animation or run it
*/
animate: function(init) {
var series = this,
yAxis = this.yAxis,
options = series.options,
inverted = this.chart.inverted,
attr = {},
translatedThreshold;
if (svg) { // VML is too slow anyway
if (init) {
attr.scaleY = 0.001;
translatedThreshold = Math.min(yAxis.pos + yAxis.len, Math.max(yAxis.pos, yAxis.toPixels(options.threshold)));
if (inverted) {
attr.translateX = translatedThreshold - yAxis.len;
} else {
attr.translateY = translatedThreshold;
}
series.group.attr(attr);
} else { // run the animation
attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
series.group.animate(attr, extend(animObject(series.options.animation), {
// Do the scale synchronously to ensure smooth updating (#5030)
step: function(val, fx) {
series.group.attr({
scaleY: Math.max(0.001, fx.pos) // #5250
});
}
}));
// delete this function to allow it only once
series.animate = null;
}
}
},
/**
* Remove this series from the chart
*/
remove: function() {
var series = this,
chart = series.chart;
// column and bar series affects other series of the same type
// as they are either stacked or grouped
if (chart.hasRendered) {
each(chart.series, function(otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
Series.prototype.remove.apply(series, arguments);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Series = H.Series,
seriesType = H.seriesType;
/**
* The scatter series type
*/
seriesType('scatter', 'line', {
lineWidth: 0,
marker: {
enabled: true // Overrides auto-enabling in line series (#3647)
},
tooltip: {
headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 0.85em"> {series.name}</span><br/>',
pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
}
// Prototype members
}, {
sorted: false,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
takeOrdinalPosition: false, // #2342
kdDimensions: 2,
drawGraph: function() {
if (this.options.lineWidth) {
Series.prototype.drawGraph.call(this);
}
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
arrayMax = H.arrayMax,
defined = H.defined,
each = H.each,
extend = H.extend,
format = H.format,
map = H.map,
merge = H.merge,
noop = H.noop,
pick = H.pick,
relativeLength = H.relativeLength,
Series = H.Series,
seriesTypes = H.seriesTypes,
stableSort = H.stableSort,
stop = H.stop;
/**
* Generatl distribution algorithm for distributing labels of differing size along a
* confined length in two dimensions. The algorithm takes an array of objects containing
* a size, a target and a rank. It will place the labels as close as possible to their
* targets, skipping the lowest ranked labels if necessary.
*/
H.distribute = function(boxes, len) {
var i,
overlapping = true,
origBoxes = boxes, // Original array will be altered with added .pos
restBoxes = [], // The outranked overshoot
box,
target,
total = 0;
function sortByTarget(a, b) {
return a.target - b.target;
}
// If the total size exceeds the len, remove those boxes with the lowest rank
i = boxes.length;
while (i--) {
total += boxes[i].size;
}
// Sort by rank, then slice away overshoot
if (total > len) {
stableSort(boxes, function(a, b) {
return (b.rank || 0) - (a.rank || 0);
});
i = 0;
total = 0;
while (total <= len) {
total += boxes[i].size;
i++;
}
restBoxes = boxes.splice(i - 1, boxes.length);
}
// Order by target
stableSort(boxes, sortByTarget);
// So far we have been mutating the original array. Now
// create a copy with target arrays
boxes = map(boxes, function(box) {
return {
size: box.size,
targets: [box.target]
};
});
while (overlapping) {
// Initial positions: target centered in box
i = boxes.length;
while (i--) {
box = boxes[i];
// Composite box, average of targets
target = (Math.min.apply(0, box.targets) + Math.max.apply(0, box.targets)) / 2;
box.pos = Math.min(Math.max(0, target - box.size / 2), len - box.size);
}
// Detect overlap and join boxes
i = boxes.length;
overlapping = false;
while (i--) {
if (i > 0 && boxes[i - 1].pos + boxes[i - 1].size > boxes[i].pos) { // Overlap
boxes[i - 1].size += boxes[i].size; // Add this size to the previous box
boxes[i - 1].targets = boxes[i - 1].targets.concat(boxes[i].targets);
// Overlapping right, push left
if (boxes[i - 1].pos + boxes[i - 1].size > len) {
boxes[i - 1].pos = len - boxes[i - 1].size;
}
boxes.splice(i, 1); // Remove this item
overlapping = true;
}
}
}
// Now the composite boxes are placed, we need to put the original boxes within them
i = 0;
each(boxes, function(box) {
var posInCompositeBox = 0;
each(box.targets, function() {
origBoxes[i].pos = box.pos + posInCompositeBox;
posInCompositeBox += origBoxes[i].size;
i++;
});
});
// Add the rest (hidden) boxes and sort by target
origBoxes.push.apply(origBoxes, restBoxes);
stableSort(origBoxes, sortByTarget);
};
/**
* Draw the data labels
*/
Series.prototype.drawDataLabels = function() {
var series = this,
seriesOptions = series.options,
options = seriesOptions.dataLabels,
points = series.points,
pointOptions,
generalOptions,
hasRendered = series.hasRendered || 0,
str,
dataLabelsGroup,
defer = pick(options.defer, true),
renderer = series.chart.renderer;
if (options.enabled || series._hasPointLabels) {
// Process default alignment of data labels for columns
if (series.dlProcessOptions) {
series.dlProcessOptions(options);
}
// Create a separate group for the data labels to avoid rotation
dataLabelsGroup = series.plotGroup(
'dataLabelsGroup',
'data-labels',
defer && !hasRendered ? 'hidden' : 'visible', // #5133
options.zIndex || 6
);
if (defer) {
dataLabelsGroup.attr({
opacity: +hasRendered
}); // #3300
if (!hasRendered) {
addEvent(series, 'afterAnimate', function() {
if (series.visible) { // #2597, #3023, #3024
dataLabelsGroup.show(true);
}
dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({
opacity: 1
}, {
duration: 200
});
});
}
}
// Make the labels for each point
generalOptions = options;
each(points, function(point) {
var enabled,
dataLabel = point.dataLabel,
labelConfig,
attr,
name,
rotation,
connector = point.connector,
isNew = true,
style,
moreStyle = {};
// Determine if each data label is enabled
pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps
enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled) && point.y !== null; // #2282, #4641
// If the point is outside the plot area, destroy it. #678, #820
if (dataLabel && !enabled) {
point.dataLabel = dataLabel.destroy();
// Individual labels are disabled if the are explicitly disabled
// in the point options, or if they fall outside the plot area.
} else if (enabled) {
// Create individual options structure that can be extended without
// affecting others
options = merge(generalOptions, pointOptions);
style = options.style;
rotation = options.rotation;
// Get the string
labelConfig = point.getLabelConfig();
str = options.format ?
format(options.format, labelConfig) :
options.formatter.call(labelConfig, options);
// update existing label
if (dataLabel) {
if (defined(str)) {
dataLabel
.attr({
text: str
});
isNew = false;
} else { // #1437 - the label is shown conditionally
point.dataLabel = dataLabel = dataLabel.destroy();
if (connector) {
point.connector = connector.destroy();
}
}
// create new label
} else if (defined(str)) {
attr = {
//align: align,
r: options.borderRadius || 0,
rotation: rotation,
padding: options.padding,
zIndex: 1
};
// Remove unused attributes (#947)
for (name in attr) {
if (attr[name] === undefined) {
delete attr[name];
}
}
dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation
str,
0, -9999,
options.shape,
null,
null,
options.useHTML,
null,
'data-label'
)
.attr(attr);
dataLabel.addClass('highcharts-data-label-color-' + point.colorIndex + ' ' + (options.className || ''));
dataLabel.add(dataLabelsGroup);
}
if (dataLabel) {
// Now the data label is created and placed at 0,0, so we need to align it
series.alignDataLabel(point, dataLabel, options, null, isNew);
}
}
});
}
};
/**
* Align each individual data label
*/
Series.prototype.alignDataLabel = function(point, dataLabel, options, alignTo, isNew) {
var chart = this.chart,
inverted = chart.inverted,
plotX = pick(point.plotX, -9999),
plotY = pick(point.plotY, -9999),
bBox = dataLabel.getBBox(),
fontSize,
baseline,
rotation = options.rotation,
normRotation,
negRotation,
align = options.align,
rotCorr, // rotation correction
// Math.round for rounding errors (#2683), alignTo to allow column labels (#2700)
visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, Math.round(plotY), inverted) ||
(alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))),
alignAttr, // the final position;
justify = pick(options.overflow, 'justify') === 'justify';
if (visible) {
baseline = chart.renderer.fontMetrics(fontSize, dataLabel).b;
// The alignment box is a singular point
alignTo = extend({
x: inverted ? chart.plotWidth - plotY : plotX,
y: Math.round(inverted ? chart.plotHeight - plotX : plotY),
width: 0,
height: 0
}, alignTo);
// Add the text size for alignment calculation
extend(options, {
width: bBox.width,
height: bBox.height
});
// Allow a hook for changing alignment in the last moment, then do the alignment
if (rotation) {
justify = false; // Not supported for rotated text
rotCorr = chart.renderer.rotCorr(baseline, rotation); // #3723
alignAttr = {
x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x,
y: alignTo.y + options.y + {
top: 0,
middle: 0.5,
bottom: 1
}[options.verticalAlign] * alignTo.height
};
dataLabel[isNew ? 'attr' : 'animate'](alignAttr)
.attr({ // #3003
align: align
});
// Compensate for the rotated label sticking out on the sides
normRotation = (rotation + 720) % 360;
negRotation = normRotation > 180 && normRotation < 360;
if (align === 'left') {
alignAttr.y -= negRotation ? bBox.height : 0;
} else if (align === 'center') {
alignAttr.x -= bBox.width / 2;
alignAttr.y -= bBox.height / 2;
} else if (align === 'right') {
alignAttr.x -= bBox.width;
alignAttr.y -= negRotation ? 0 : bBox.height;
}
} else {
dataLabel.align(options, null, alignTo);
alignAttr = dataLabel.alignAttr;
}
// Handle justify or crop
if (justify) {
this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
// Now check that the data label is within the plot area
} else if (pick(options.crop, true)) {
visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
}
// When we're using a shape, make it possible with a connector or an arrow pointing to thie point
if (options.shape && !rotation) {
dataLabel.attr({
anchorX: point.plotX,
anchorY: point.plotY
});
}
}
// Show or hide based on the final aligned position
if (!visible) {
stop(dataLabel);
dataLabel.attr({
y: -9999
});
dataLabel.placed = false; // don't animate back in
}
};
/**
* If data labels fall partly outside the plot area, align them back in, in a way that
* doesn't hide the point.
*/
Series.prototype.justifyDataLabel = function(dataLabel, options, alignAttr, bBox, alignTo, isNew) {
var chart = this.chart,
align = options.align,
verticalAlign = options.verticalAlign,
off,
justified,
padding = dataLabel.box ? 0 : (dataLabel.padding || 0);
// Off left
off = alignAttr.x + padding;
if (off < 0) {
if (align === 'right') {
options.align = 'left';
} else {
options.x = -off;
}
justified = true;
}
// Off right
off = alignAttr.x + bBox.width - padding;
if (off > chart.plotWidth) {
if (align === 'left') {
options.align = 'right';
} else {
options.x = chart.plotWidth - off;
}
justified = true;
}
// Off top
off = alignAttr.y + padding;
if (off < 0) {
if (verticalAlign === 'bottom') {
options.verticalAlign = 'top';
} else {
options.y = -off;
}
justified = true;
}
// Off bottom
off = alignAttr.y + bBox.height - padding;
if (off > chart.plotHeight) {
if (verticalAlign === 'top') {
options.verticalAlign = 'bottom';
} else {
options.y = chart.plotHeight - off;
}
justified = true;
}
if (justified) {
dataLabel.placed = !isNew;
dataLabel.align(options, null, alignTo);
}
};
/**
* Override the base drawDataLabels method by pie specific functionality
*/
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawDataLabels = function() {
var series = this,
data = series.data,
point,
chart = series.chart,
options = series.options.dataLabels,
connectorPadding = pick(options.connectorPadding, 10),
connectorWidth = pick(options.connectorWidth, 1),
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
connector,
distanceOption = options.distance,
seriesCenter = series.center,
radius = seriesCenter[2] / 2,
centerY = seriesCenter[1],
outside = distanceOption > 0,
dataLabel,
dataLabelWidth,
labelPos,
labelHeight,
halves = [ // divide the points into right and left halves for anti collision
[], // right
[] // left
],
x,
y,
visibility,
j,
overflow = [0, 0, 0, 0]; // top, right, bottom, left
// get out if not enabled
if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
return;
}
// run parent method
Series.prototype.drawDataLabels.apply(series);
each(data, function(point) {
if (point.dataLabel && point.visible) { // #407, #2510
// Arrange points for detection collision
halves[point.half].push(point);
// Reset positions (#4905)
point.dataLabel._pos = null;
}
});
/* Loop over the points in each half, starting from the top and bottom
* of the pie to detect overlapping labels.
*/
each(halves, function(points, i) {
var top,
bottom,
length = points.length,
positions,
naturalY,
size;
if (!length) {
return;
}
// Sort by angle
series.sortByAngle(points, i - 0.5);
// Only do anti-collision when we are outside the pie and have connectors (#856)
if (distanceOption > 0) {
top = Math.max(0, centerY - radius - distanceOption);
bottom = Math.min(centerY + radius + distanceOption, chart.plotHeight);
positions = map(points, function(point) {
if (point.dataLabel) {
size = point.dataLabel.getBBox().height || 21;
return {
target: point.labelPos[1] - top + size / 2,
size: size,
rank: point.y
};
}
});
H.distribute(positions, bottom + size - top);
}
// now the used slots are sorted, fill them up sequentially
for (j = 0; j < length; j++) {
point = points[j];
labelPos = point.labelPos;
dataLabel = point.dataLabel;
visibility = point.visible === false ? 'hidden' : 'inherit';
naturalY = labelPos[1];
if (positions) {
if (positions[j].pos === undefined) {
visibility = 'hidden';
} else {
labelHeight = positions[j].size;
y = top + positions[j].pos;
}
} else {
y = naturalY;
}
// get the x - use the natural x position for labels near the top and bottom, to prevent the top
// and botton slice connectors from touching each other on either side
if (options.justify) {
x = seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption);
} else {
x = series.getX(y < top + 2 || y > bottom - 2 ? naturalY : y, i);
}
// Record the placement and visibility
dataLabel._attr = {
visibility: visibility,
align: labelPos[6]
};
dataLabel._pos = {
x: x + options.x +
({
left: connectorPadding,
right: -connectorPadding
}[labelPos[6]] || 0),
y: y + options.y - 10 // 10 is for the baseline (label vs text)
};
labelPos.x = x;
labelPos.y = y;
// Detect overflowing data labels
if (series.options.size === null) {
dataLabelWidth = dataLabel.width;
// Overflow left
if (x - dataLabelWidth < connectorPadding) {
overflow[3] = Math.max(Math.round(dataLabelWidth - x + connectorPadding), overflow[3]);
// Overflow right
} else if (x + dataLabelWidth > plotWidth - connectorPadding) {
overflow[1] = Math.max(Math.round(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
}
// Overflow top
if (y - labelHeight / 2 < 0) {
overflow[0] = Math.max(Math.round(-y + labelHeight / 2), overflow[0]);
// Overflow left
} else if (y + labelHeight / 2 > plotHeight) {
overflow[2] = Math.max(Math.round(y + labelHeight / 2 - plotHeight), overflow[2]);
}
}
} // for each point
}); // for each half
// Do not apply the final placement and draw the connectors until we have verified
// that labels are not spilling over.
if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
// Place the labels in the final position
this.placeDataLabels();
// Draw the connectors
if (outside && connectorWidth) {
each(this.points, function(point) {
var isNew;
connector = point.connector;
dataLabel = point.dataLabel;
if (dataLabel && dataLabel._pos && point.visible) {
visibility = dataLabel._attr.visibility;
isNew = !connector;
if (isNew) {
point.connector = connector = chart.renderer.path()
.addClass('highcharts-data-label-connector highcharts-color-' + point.colorIndex)
.add(series.dataLabelsGroup);
}
connector[isNew ? 'attr' : 'animate']({
d: series.connectorPath(point.labelPos)
});
connector.attr('visibility', visibility);
} else if (connector) {
point.connector = connector.destroy();
}
});
}
}
};
/**
* Extendable method for getting the path of the connector between the data label
* and the pie slice.
*/
seriesTypes.pie.prototype.connectorPath = function(labelPos) {
var x = labelPos.x,
y = labelPos.y;
return pick(this.options.softConnector, true) ? [
'M',
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'C',
x, y, // first break, next to the label
2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
labelPos[2], labelPos[3], // second break
'L',
labelPos[4], labelPos[5] // base
] : [
'M',
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'L',
labelPos[2], labelPos[3], // second break
'L',
labelPos[4], labelPos[5] // base
];
};
/**
* Perform the final placement of the data labels after we have verified that they
* fall within the plot area.
*/
seriesTypes.pie.prototype.placeDataLabels = function() {
each(this.points, function(point) {
var dataLabel = point.dataLabel,
_pos;
if (dataLabel && point.visible) {
_pos = dataLabel._pos;
if (_pos) {
dataLabel.attr(dataLabel._attr);
dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
dataLabel.moved = true;
} else if (dataLabel) {
dataLabel.attr({
y: -9999
});
}
}
});
};
seriesTypes.pie.prototype.alignDataLabel = noop;
/**
* Verify whether the data labels are allowed to draw, or we should run more translation and data
* label positioning to keep them inside the plot area. Returns true when data labels are ready
* to draw.
*/
seriesTypes.pie.prototype.verifyDataLabelOverflow = function(overflow) {
var center = this.center,
options = this.options,
centerOption = options.center,
minSize = options.minSize || 80,
newSize = minSize,
ret;
// Handle horizontal size and center
if (centerOption[0] !== null) { // Fixed center
newSize = Math.max(center[2] - Math.max(overflow[1], overflow[3]), minSize);
} else { // Auto center
newSize = Math.max(
center[2] - overflow[1] - overflow[3], // horizontal overflow
minSize
);
center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
}
// Handle vertical size and center
if (centerOption[1] !== null) { // Fixed center
newSize = Math.max(Math.min(newSize, center[2] - Math.max(overflow[0], overflow[2])), minSize);
} else { // Auto center
newSize = Math.max(
Math.min(
newSize,
center[2] - overflow[0] - overflow[2] // vertical overflow
),
minSize
);
center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
}
// If the size must be decreased, we need to run translate and drawDataLabels again
if (newSize < center[2]) {
center[2] = newSize;
center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632
this.translate(center);
if (this.drawDataLabels) {
this.drawDataLabels();
}
// Else, return true to indicate that the pie and its labels is within the plot area
} else {
ret = true;
}
return ret;
};
}
if (seriesTypes.column) {
/**
* Override the basic data label alignment by adjusting for the position of the column
*/
seriesTypes.column.prototype.alignDataLabel = function(point, dataLabel, options, alignTo, isNew) {
var inverted = this.chart.inverted,
series = point.series,
dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series
inside = pick(options.inside, !!this.options.stacking), // draw it inside the box?
overshoot;
// Align to the column itself, or the top of it
if (dlBox) { // Area range uses this method but not alignTo
alignTo = merge(dlBox);
if (alignTo.y < 0) {
alignTo.height += alignTo.y;
alignTo.y = 0;
}
overshoot = alignTo.y + alignTo.height - series.yAxis.len;
if (overshoot > 0) {
alignTo.height -= overshoot;
}
if (inverted) {
alignTo = {
x: series.yAxis.len - alignTo.y - alignTo.height,
y: series.xAxis.len - alignTo.x - alignTo.width,
width: alignTo.height,
height: alignTo.width
};
}
// Compute the alignment box
if (!inside) {
if (inverted) {
alignTo.x += below ? 0 : alignTo.width;
alignTo.width = 0;
} else {
alignTo.y += below ? alignTo.height : 0;
alignTo.height = 0;
}
}
}
// When alignment is undefined (typically columns and bars), display the individual
// point below or above the point depending on the threshold
options.align = pick(
options.align, !inverted || inside ? 'center' : below ? 'right' : 'left'
);
options.verticalAlign = pick(
options.verticalAlign,
inverted || inside ? 'middle' : below ? 'top' : 'bottom'
);
// Call the parent method
Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
};
}
}(Highcharts));
(function(H) {
/**
* (c) 2009-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
/**
* Highcharts module to hide overlapping data labels. This module is included in Highcharts.
*/
var Chart = H.Chart,
each = H.each,
pick = H.pick,
addEvent = H.addEvent;
// Collect potensial overlapping data labels. Stack labels probably don't need to be
// considered because they are usually accompanied by data labels that lie inside the columns.
Chart.prototype.callbacks.push(function(chart) {
function collectAndHide() {
var labels = [];
each(chart.series, function(series) {
var dlOptions = series.options.dataLabels,
collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections
if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866
each(collections, function(coll) {
each(series.points, function(point) {
if (point[coll]) {
point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118
labels.push(point[coll]);
}
});
});
}
});
chart.hideOverlappingLabels(labels);
}
// Do it now ...
collectAndHide();
// ... and after each chart redraw
addEvent(chart, 'redraw', collectAndHide);
});
/**
* Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
* visual imression.
*/
Chart.prototype.hideOverlappingLabels = function(labels) {
var len = labels.length,
label,
i,
j,
label1,
label2,
isIntersecting,
pos1,
pos2,
parent1,
parent2,
padding,
intersectRect = function(x1, y1, w1, h1, x2, y2, w2, h2) {
return !(
x2 > x1 + w1 ||
x2 + w2 < x1 ||
y2 > y1 + h1 ||
y2 + h2 < y1
);
};
// Mark with initial opacity
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
label.oldOpacity = label.opacity;
label.newOpacity = 1;
}
}
// Prevent a situation in a gradually rising slope, that each label
// will hide the previous one because the previous one always has
// lower rank.
labels.sort(function(a, b) {
return (b.labelrank || 0) - (a.labelrank || 0);
});
// Detect overlapping labels
for (i = 0; i < len; i++) {
label1 = labels[i];
for (j = i + 1; j < len; ++j) {
label2 = labels[j];
if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) {
pos1 = label1.alignAttr;
pos2 = label2.alignAttr;
parent1 = label1.parentGroup; // Different panes have different positions
parent2 = label2.parentGroup;
padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333)
isIntersecting = intersectRect(
pos1.x + parent1.translateX,
pos1.y + parent1.translateY,
label1.width - padding,
label1.height - padding,
pos2.x + parent2.translateX,
pos2.y + parent2.translateY,
label2.width - padding,
label2.height - padding
);
if (isIntersecting) {
(label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0;
}
}
}
}
// Hide or show
each(labels, function(label) {
var complete,
newOpacity;
if (label) {
newOpacity = label.newOpacity;
if (label.oldOpacity !== newOpacity && label.placed) {
// Make sure the label is completely hidden to avoid catching clicks (#4362)
if (newOpacity) {
label.show(true);
} else {
complete = function() {
label.hide();
};
}
// Animate or set the opacity
label.alignAttr.opacity = newOpacity;
label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete);
}
label.isOld = true;
}
});
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Axis = H.Axis,
each = H.each,
pick = H.pick,
wrap = H.wrap;
/**
* Override to use the extreme coordinates from the SVG shape, not the
* data values
*/
wrap(Axis.prototype, 'getSeriesExtremes', function(proceed) {
var isXAxis = this.isXAxis,
dataMin,
dataMax,
xData = [],
useMapGeometry;
// Remove the xData array and cache it locally so that the proceed method doesn't use it
if (isXAxis) {
each(this.series, function(series, i) {
if (series.useMapGeometry) {
xData[i] = series.xData;
series.xData = [];
}
});
}
// Call base to reach normal cartesian series (like mappoint)
proceed.call(this);
// Run extremes logic for map and mapline
if (isXAxis) {
dataMin = pick(this.dataMin, Number.MAX_VALUE);
dataMax = pick(this.dataMax, -Number.MAX_VALUE);
each(this.series, function(series, i) {
if (series.useMapGeometry) {
dataMin = Math.min(dataMin, pick(series.minX, dataMin));
dataMax = Math.max(dataMax, pick(series.maxX, dataMin));
series.xData = xData[i]; // Reset xData array
useMapGeometry = true;
}
});
if (useMapGeometry) {
this.dataMin = dataMin;
this.dataMax = dataMax;
}
}
});
/**
* Override axis translation to make sure the aspect ratio is always kept
*/
wrap(Axis.prototype, 'setAxisTranslation', function(proceed) {
var chart = this.chart,
mapRatio,
plotRatio = chart.plotWidth / chart.plotHeight,
adjustedAxisLength,
xAxis = chart.xAxis[0],
padAxis,
fixTo,
fixDiff,
preserveAspectRatio;
// Run the parent method
proceed.call(this);
// Check for map-like series
if (this.coll === 'yAxis' && xAxis.transA !== undefined) {
each(this.series, function(series) {
if (series.preserveAspectRatio) {
preserveAspectRatio = true;
}
});
}
// On Y axis, handle both
if (preserveAspectRatio) {
// Use the same translation for both axes
this.transA = xAxis.transA = Math.min(this.transA, xAxis.transA);
mapRatio = plotRatio / ((xAxis.max - xAxis.min) / (this.max - this.min));
// What axis to pad to put the map in the middle
padAxis = mapRatio < 1 ? this : xAxis;
// Pad it
adjustedAxisLength = (padAxis.max - padAxis.min) * padAxis.transA;
padAxis.pixelPadding = padAxis.len - adjustedAxisLength;
padAxis.minPixelPadding = padAxis.pixelPadding / 2;
fixTo = padAxis.fixTo;
if (fixTo) {
fixDiff = fixTo[1] - padAxis.toValue(fixTo[0], true);
fixDiff *= padAxis.transA;
if (Math.abs(fixDiff) > padAxis.minPixelPadding || (padAxis.min === padAxis.dataMin && padAxis.max === padAxis.dataMax)) { // zooming out again, keep within restricted area
fixDiff = 0;
}
padAxis.minPixelPadding -= fixDiff;
}
}
});
/**
* Override Axis.render in order to delete the fixTo prop
*/
wrap(Axis.prototype, 'render', function(proceed) {
proceed.call(this);
this.fixTo = null;
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Axis = H.Axis,
Chart = H.Chart,
color = H.color,
ColorAxis,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
Legend = H.Legend,
LegendSymbolMixin = H.LegendSymbolMixin,
noop = H.noop,
merge = H.merge,
pick = H.pick,
wrap = H.wrap;
/**
* The ColorAxis object for inclusion in gradient legends
*/
ColorAxis = H.ColorAxis = function() {
this.init.apply(this, arguments);
};
extend(ColorAxis.prototype, Axis.prototype);
extend(ColorAxis.prototype, {
defaultColorAxisOptions: {
lineWidth: 0,
minPadding: 0,
maxPadding: 0,
gridLineWidth: 1,
tickPixelInterval: 72,
startOnTick: true,
endOnTick: true,
offset: 0,
marker: {
animation: {
duration: 50
},
width: 0.01
},
labels: {
overflow: 'justify'
},
minColor: '#e6ebf5',
maxColor: '#003399',
tickLength: 5,
showInLegend: true
},
init: function(chart, userOptions) {
var horiz = chart.options.legend.layout !== 'vertical',
options;
this.coll = 'colorAxis';
// Build the options
options = merge(this.defaultColorAxisOptions, {
side: horiz ? 2 : 1,
reversed: !horiz
}, userOptions, {
opposite: !horiz,
showEmpty: false,
title: null
});
Axis.prototype.init.call(this, chart, options);
// Base init() pushes it to the xAxis array, now pop it again
//chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop();
// Prepare data classes
if (userOptions.dataClasses) {
this.initDataClasses(userOptions);
}
this.initStops(userOptions);
// Override original axis properties
this.horiz = horiz;
this.zoomEnabled = false;
// Add default values
this.defaultLegendLength = 200;
},
/*
* Return an intermediate color between two colors, according to pos where 0
* is the from color and 1 is the to color.
* NOTE: Changes here should be copied
* to the same function in drilldown.src.js and solid-gauge-src.js.
*/
tweenColors: function(from, to, pos) {
// Check for has alpha, because rgba colors perform worse due to lack of
// support in WebKit.
var hasAlpha,
ret;
// Unsupported color, return to-color (#3920)
if (!to.rgba.length || !from.rgba.length) {
ret = to.input || 'none';
// Interpolate
} else {
from = from.rgba;
to = to.rgba;
hasAlpha = (to[3] !== 1 || from[3] !== 1);
ret = (hasAlpha ? 'rgba(' : 'rgb(') +
Math.round(to[0] + (from[0] - to[0]) * (1 - pos)) + ',' +
Math.round(to[1] + (from[1] - to[1]) * (1 - pos)) + ',' +
Math.round(to[2] + (from[2] - to[2]) * (1 - pos)) +
(hasAlpha ? (',' + (to[3] + (from[3] - to[3]) * (1 - pos))) : '') + ')';
}
return ret;
},
initDataClasses: function(userOptions) {
var axis = this,
chart = this.chart,
dataClasses,
colorCounter = 0,
colorCount = chart.options.chart.colorCount,
options = this.options,
len = userOptions.dataClasses.length;
this.dataClasses = dataClasses = [];
this.legendItems = [];
each(userOptions.dataClasses, function(dataClass, i) {
var colors;
dataClass = merge(dataClass);
dataClasses.push(dataClass);
if (!dataClass.color) {
if (options.dataClassColor === 'category') {
dataClass.colorIndex = colorCounter;
// increase and loop back to zero
colorCounter++;
if (colorCounter === colorCount) {
colorCounter = 0;
}
} else {
dataClass.color = axis.tweenColors(
color(options.minColor),
color(options.maxColor),
len < 2 ? 0.5 : i / (len - 1) // #3219
);
}
}
});
},
initStops: function(userOptions) {
this.stops = userOptions.stops || [
[0, this.options.minColor],
[1, this.options.maxColor]
];
each(this.stops, function(stop) {
stop.color = color(stop[1]);
});
},
/**
* Extend the setOptions method to process extreme colors and color
* stops.
*/
setOptions: function(userOptions) {
Axis.prototype.setOptions.call(this, userOptions);
this.options.crosshair = this.options.marker;
},
setAxisSize: function() {
var symbol = this.legendSymbol,
chart = this.chart,
legendOptions = chart.options.legend || {},
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) || this.defaultLegendLength;
}
},
/**
* Translate from a value to a color
*/
toColor: function(value, point) {
var pos,
stops = this.stops,
from,
to,
color,
dataClasses = this.dataClasses,
dataClass,
i;
if (dataClasses) {
i = dataClasses.length;
while (i--) {
dataClass = dataClasses[i];
from = dataClass.from;
to = dataClass.to;
if ((from === undefined || value >= from) && (to === undefined || value <= to)) {
color = dataClass.color;
if (point) {
point.dataClass = i;
point.colorIndex = dataClass.colorIndex;
}
break;
}
}
} else {
if (this.isLog) {
value = this.val2lin(value);
}
pos = 1 - ((this.max - value) / ((this.max - this.min) || 1));
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 = this.tweenColors(
from.color,
to.color,
pos
);
}
return color;
},
/**
* Override the getOffset method to add the whole axis groups inside the legend.
*/
getOffset: function() {
var group = this.legendGroup,
sideOffset = this.chart.axisOffset[this.side];
if (group) {
// Hook for the getOffset method to add groups to this parent group
this.axisParent = group;
// Call the base
Axis.prototype.getOffset.call(this);
// First time only
if (!this.added) {
this.added = true;
this.labelLeft = 0;
this.labelRight = this.width;
}
// Reset it to avoid color axis reserving space
this.chart.axisOffset[this.side] = sideOffset;
}
},
/**
* Create the color gradient
*/
setLegendColor: function() {
var grad,
horiz = this.horiz,
options = this.options,
reversed = this.reversed,
one = reversed ? 1 : 0,
zero = reversed ? 0 : 1;
grad = horiz ? [one, 0, zero, 0] : [0, zero, 0, one]; // #3190
this.legendColor = {
linearGradient: {
x1: grad[0],
y1: grad[1],
x2: grad[2],
y2: grad[3]
},
stops: options.stops || [
[0, options.minColor],
[1, options.maxColor]
]
};
},
/**
* The color axis appears inside the legend and has its own legend symbol
*/
drawLegendSymbol: function(legend, item) {
var padding = legend.padding,
legendOptions = legend.options,
horiz = this.horiz,
width = pick(legendOptions.symbolWidth, horiz ? this.defaultLegendLength : 12),
height = pick(legendOptions.symbolHeight, horiz ? 12 : this.defaultLegendLength),
labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30),
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
this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding);
this.legendItemHeight = height + padding + (horiz ? labelPadding : 0);
},
/**
* Fool the legend
*/
setState: noop,
visible: true,
setVisible: noop,
getSeriesExtremes: function() {
var series;
if (this.series.length) {
series = this.series[0];
this.dataMin = series.valueMin;
this.dataMax = series.valueMax;
}
},
drawCrosshair: function(e, point) {
var plotX = point && point.plotX,
plotY = point && point.plotY,
crossPos,
axisPos = this.pos,
axisLen = this.len;
if (point) {
crossPos = this.toPixels(point[point.series.colorKey]);
if (crossPos < axisPos) {
crossPos = axisPos - 2;
} else if (crossPos > axisPos + axisLen) {
crossPos = axisPos + axisLen + 2;
}
point.plotX = crossPos;
point.plotY = this.len - crossPos;
Axis.prototype.drawCrosshair.call(this, e, point);
point.plotX = plotX;
point.plotY = plotY;
if (this.cross) {
this.cross
.addClass('highcharts-coloraxis-marker')
.add(this.legendGroup);
}
}
},
getPlotLinePath: function(a, b, c, d, pos) {
return isNumber(pos) ? // crosshairs only // #3969 pos can be 0 !!
(this.horiz ? ['M', pos - 4, this.top - 6, 'L', pos + 4, this.top - 6, pos, this.top, 'Z'] : ['M', this.left, pos, 'L', this.left - 6, pos + 6, this.left - 6, pos - 6, 'Z']) :
Axis.prototype.getPlotLinePath.call(this, a, b, c, d);
},
update: function(newOptions, redraw) {
var chart = this.chart,
legend = chart.legend;
each(this.series, function(series) {
series.isDirtyData = true; // Needed for Axis.update when choropleth colors change
});
// When updating data classes, destroy old items and make sure new ones are created (#3207)
if (newOptions.dataClasses && legend.allItems) {
each(legend.allItems, function(item) {
if (item.isDataClass) {
item.legendGroup.destroy();
}
});
chart.isDirtyLegend = true;
}
// Keep the options structure updated for export. Unlike xAxis and yAxis, the colorAxis is
// not an array. (#3207)
chart.options[this.coll] = merge(this.userOptions, newOptions);
Axis.prototype.update.call(this, newOptions, redraw);
if (this.legendItem) {
this.setLegendColor();
legend.colorizeItem(this, true);
}
},
/**
* Get the legend item symbols for data classes
*/
getDataClassLegendSymbols: function() {
var axis = this,
chart = this.chart,
legendItems = this.legendItems,
legendOptions = chart.options.legend,
valueDecimals = legendOptions.valueDecimals,
valueSuffix = legendOptions.valueSuffix || '',
name;
if (!legendItems.length) {
each(this.dataClasses, function(dataClass, i) {
var vis = true,
from = dataClass.from,
to = dataClass.to;
// Assemble the default name. This can be overridden by legend.options.labelFormatter
name = '';
if (from === undefined) {
name = '< ';
} else if (to === undefined) {
name = '> ';
}
if (from !== undefined) {
name += H.numberFormat(from, valueDecimals) + valueSuffix;
}
if (from !== undefined && to !== undefined) {
name += ' - ';
}
if (to !== undefined) {
name += H.numberFormat(to, valueDecimals) + valueSuffix;
}
// Add a mock object to the legend items
legendItems.push(extend({
chart: chart,
name: name,
options: {},
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
visible: true,
setState: noop,
isDataClass: true,
setVisible: function() {
vis = this.visible = !vis;
each(axis.series, function(series) {
each(series.points, function(point) {
if (point.dataClass === i) {
point.setVisible(vis);
}
});
});
chart.legend.colorizeItem(this, vis);
}
}, dataClass));
});
}
return legendItems;
},
name: '' // Prevents 'undefined' in legend in IE8
});
/**
* Handle animation of the color attributes directly
*/
each(['fill', 'stroke'], function(prop) {
H.Fx.prototype[prop + 'Setter'] = function() {
this.elem.attr(prop, ColorAxis.prototype.tweenColors(color(this.start), color(this.end), this.pos));
};
});
/**
* Extend the chart getAxes method to also get the color axis
*/
wrap(Chart.prototype, 'getAxes', function(proceed) {
var options = this.options,
colorAxisOptions = options.colorAxis;
proceed.call(this);
this.colorAxis = [];
if (colorAxisOptions) {
new ColorAxis(this, colorAxisOptions); // eslint-disable-line no-new
}
});
/**
* Wrap the legend getAllItems method to add the color axis. This also removes the
* axis' own series to prevent them from showing up individually.
*/
wrap(Legend.prototype, 'getAllItems', function(proceed) {
var allItems = [],
colorAxis = this.chart.colorAxis[0];
if (colorAxis && colorAxis.options) {
if (colorAxis.options.showInLegend) {
// Data classes
if (colorAxis.options.dataClasses) {
allItems = allItems.concat(colorAxis.getDataClassLegendSymbols());
// Gradient legend
} else {
// Add this axis on top
allItems.push(colorAxis);
}
}
// Don't add the color axis' series
each(colorAxis.series, function(series) {
series.options.showInLegend = false;
});
}
return allItems.concat(proceed.call(this));
});
wrap(Legend.prototype, 'colorizeItem', function(proceed, item, visible) {
proceed.call(this, item, visible);
if (visible && item.legendColor) {
item.legendSymbol.attr({
fill: item.legendColor
});
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var defined = H.defined,
each = H.each,
noop = H.noop,
seriesTypes = H.seriesTypes;
/**
* Mixin for maps and heatmaps
*/
H.colorPointMixin = {
/**
* Color points have a value option that determines whether or not it is a null point
*/
isValid: function() {
return this.value !== null;
},
/**
* Set the visibility of a single point
*/
setVisible: function(vis) {
var point = this,
method = vis ? 'show' : 'hide';
// Show and hide associated elements
each(['graphic', 'dataLabel'], function(key) {
if (point[key]) {
point[key][method]();
}
});
}
};
H.colorSeriesMixin = {
pointArrayMap: ['value'],
axisTypes: ['xAxis', 'yAxis', 'colorAxis'],
optionalAxis: 'colorAxis',
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
getSymbol: noop,
parallelArrays: ['x', 'y', 'value'],
colorKey: 'value',
/**
* In choropleth maps, the color is a result of the value, so this needs translation too
*/
translateColors: function() {
var series = this,
nullColor = this.options.nullColor,
colorAxis = this.colorAxis,
colorKey = this.colorKey;
each(this.data, function(point) {
var value = point[colorKey],
color;
color = point.options.color ||
(point.isNull ? nullColor : (colorAxis && value !== undefined) ? colorAxis.toColor(value, point) : point.color || series.color);
if (color) {
point.color = color;
}
});
},
/**
* Get the color attibutes to apply on the graphic
*/
colorAttribs: function(point) {
var ret = {};
if (defined(point.color)) {
ret[this.colorProp || 'fill'] = point.color;
}
return ret;
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var color = H.color,
ColorAxis = H.ColorAxis,
colorPointMixin = H.colorPointMixin,
colorSeriesMixin = H.colorSeriesMixin,
doc = H.doc,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
LegendSymbolMixin = H.LegendSymbolMixin,
map = H.map,
merge = H.merge,
noop = H.noop,
pick = H.pick,
isArray = H.isArray,
Point = H.Point,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes,
splat = H.splat;
// The vector-effect attribute is not supported in IE <= 11 (at least), so we need
// diffent logic (#3218)
var supportsVectorEffect = doc.documentElement.style.vectorEffect !== undefined;
/**
* The MapAreaPoint object
*/
/**
* Add the map series type
*/
seriesType('map', 'scatter', {
allAreas: true,
animation: false, // makes the complex shapes slow
nullColor: '#f7f7f7',
borderColor: '#cccccc',
borderWidth: 1,
marker: null,
stickyTracking: false,
joinBy: 'hc-key',
dataLabels: {
formatter: function() { // #2945
return this.point.value;
},
inside: true, // for the color
verticalAlign: 'middle',
crop: false,
overflow: false,
padding: 0
},
turboThreshold: 0,
tooltip: {
followPointer: true,
pointFormat: '{point.name}: {point.value}<br/>'
},
states: {
normal: {
animation: true
},
hover: {
brightness: 0.2,
halo: null
},
select: {
color: '#cccccc'
}
}
// Prototype members
}, merge(colorSeriesMixin, {
type: 'map',
supportsDrilldown: true,
getExtremesFromAll: true,
useMapGeometry: true, // get axis extremes from paths, not values
forceDL: true,
searchPoint: noop,
directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
preserveAspectRatio: true, // X axis and Y axis must have same translation slope
pointArrayMap: ['value'],
/**
* Get the bounding box of all paths in the map combined.
*/
getBox: function(paths) {
var MAX_VALUE = Number.MAX_VALUE,
maxX = -MAX_VALUE,
minX = MAX_VALUE,
maxY = -MAX_VALUE,
minY = MAX_VALUE,
minRange = MAX_VALUE,
xAxis = this.xAxis,
yAxis = this.yAxis,
hasBox;
// Find the bounding box
each(paths || [], function(point) {
if (point.path) {
if (typeof point.path === 'string') {
point.path = H.splitPath(point.path);
}
var path = point.path || [],
i = path.length,
even = false, // while loop reads from the end
pointMaxX = -MAX_VALUE,
pointMinX = MAX_VALUE,
pointMaxY = -MAX_VALUE,
pointMinY = MAX_VALUE,
properties = point.properties;
// The first time a map point is used, analyze its box
if (!point._foundBox) {
while (i--) {
if (isNumber(path[i])) {
if (even) { // even = x
pointMaxX = Math.max(pointMaxX, path[i]);
pointMinX = Math.min(pointMinX, path[i]);
} else { // odd = Y
pointMaxY = Math.max(pointMaxY, path[i]);
pointMinY = Math.min(pointMinY, path[i]);
}
even = !even;
}
}
// Cache point bounding box for use to position data labels, bubbles etc
point._midX = pointMinX + (pointMaxX - pointMinX) *
(point.middleX || (properties && properties['hc-middle-x']) || 0.5); // pick is slower and very marginally needed
point._midY = pointMinY + (pointMaxY - pointMinY) *
(point.middleY || (properties && properties['hc-middle-y']) || 0.5);
point._maxX = pointMaxX;
point._minX = pointMinX;
point._maxY = pointMaxY;
point._minY = pointMinY;
point.labelrank = pick(point.labelrank, (pointMaxX - pointMinX) * (pointMaxY - pointMinY));
point._foundBox = true;
}
maxX = Math.max(maxX, point._maxX);
minX = Math.min(minX, point._minX);
maxY = Math.max(maxY, point._maxY);
minY = Math.min(minY, point._minY);
minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange);
hasBox = true;
}
});
// Set the box for the whole series
if (hasBox) {
this.minY = Math.min(minY, pick(this.minY, MAX_VALUE));
this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE));
this.minX = Math.min(minX, pick(this.minX, MAX_VALUE));
this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE));
// If no minRange option is set, set the default minimum zooming range to 5 times the
// size of the smallest element
if (xAxis && xAxis.options.minRange === undefined) {
xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE);
}
if (yAxis && yAxis.options.minRange === undefined) {
yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE);
}
}
},
getExtremes: function() {
// Get the actual value extremes for colors
Series.prototype.getExtremes.call(this, this.valueData);
// Recalculate box on updated data
if (this.chart.hasRendered && this.isDirtyData) {
this.getBox(this.options.data);
}
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Extremes for the mock Y axis
this.dataMin = this.minY;
this.dataMax = this.maxY;
},
/**
* Translate the path so that it automatically fits into the plot area box
* @param {Object} path
*/
translatePath: function(path) {
var series = this,
even = false, // while loop reads from the end
xAxis = series.xAxis,
yAxis = series.yAxis,
xMin = xAxis.min,
xTransA = xAxis.transA,
xMinPixelPadding = xAxis.minPixelPadding,
yMin = yAxis.min,
yTransA = yAxis.transA,
yMinPixelPadding = yAxis.minPixelPadding,
i,
ret = []; // Preserve the original
// Do the translation
if (path) {
i = path.length;
while (i--) {
if (isNumber(path[i])) {
ret[i] = even ?
(path[i] - xMin) * xTransA + xMinPixelPadding :
(path[i] - yMin) * yTransA + yMinPixelPadding;
even = !even;
} else {
ret[i] = path[i];
}
}
}
return ret;
},
/**
* 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.
*/
setData: function(data, redraw, animation, updatePoints) {
var options = this.options,
chartOptions = this.chart.options.chart,
globalMapData = chartOptions && chartOptions.map,
mapData = options.mapData,
joinBy = options.joinBy,
joinByNull = joinBy === null,
pointArrayMap = options.keys || this.pointArrayMap,
dataUsed = [],
mapMap = {},
mapPoint,
transform,
mapTransforms = this.chart.mapTransforms,
props,
i;
// Collect mapData from chart options if not defined on series
if (!mapData && globalMapData) {
mapData = typeof globalMapData === 'string' ? H.maps[globalMapData] : globalMapData;
}
if (joinByNull) {
joinBy = '_i';
}
joinBy = this.joinBy = splat(joinBy);
if (!joinBy[1]) {
joinBy[1] = joinBy[0];
}
// Pick up numeric values, add index
// Convert Array point definitions to objects using pointArrayMap
if (data) {
each(data, 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]) {
data[i][pointArrayMap[j]] = val[ix];
}
}
}
if (joinByNull) {
data[i]._i = i;
}
});
}
this.getBox(data);
// Pick up transform definitions for chart
this.chart.mapTransforms = mapTransforms = chartOptions && chartOptions.mapTransforms || mapData && mapData['hc-transform'] || mapTransforms;
// Cache cos/sin of transform rotation angle
if (mapTransforms) {
for (transform in mapTransforms) {
if (mapTransforms.hasOwnProperty(transform) && 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]) {
each(data, function(point) {
if (mapMap[point[joinBy[1]]]) {
dataUsed.push(mapMap[point[joinBy[1]]]);
}
});
}
if (options.allAreas) {
this.getBox(mapData);
data = data || [];
// Registered the point codes that actually hold data
if (joinBy[1]) {
each(data, function(point) {
dataUsed.push(point[joinBy[1]]);
});
}
// Add those map points that don't correspond to data, which will be drawn as null points
dataUsed = '|' + map(dataUsed, function(point) {
return point && point[joinBy[0]];
}).join('|') + '|'; // String search is faster than array.indexOf
each(mapData, function(mapPoint) {
if (!joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) {
data.push(merge(mapPoint, {
value: null
}));
updatePoints = false; // #5050 - adding all areas causes the update optimization of setData to kick in, even though the point order has changed
}
});
} else {
this.getBox(dataUsed); // Issue #4784
}
}
Series.prototype.setData.call(this, data, redraw, animation, updatePoints);
},
/**
* No graph for the map series
*/
drawGraph: noop,
/**
* 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,
/**
* Allow a quick redraw by just translating the area group. Used for zooming and panning
* in capable browsers.
*/
doFullTranslate: function() {
return this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans;
},
/**
* Add the path option for data points. Find the max value for color calculation.
*/
translate: function() {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
doFullTranslate = series.doFullTranslate();
series.generatePoints();
each(series.data, function(point) {
// Record the middle point (loosely based on centroid), determined
// by the middleX and middleY options.
point.plotX = xAxis.toPixels(point._midX, true);
point.plotY = yAxis.toPixels(point._midY, true);
if (doFullTranslate) {
point.shapeType = 'path';
point.shapeArgs = {
d: series.translatePath(point.path)
};
}
});
series.translateColors();
},
/**
* Get presentational attributes
*/
pointAttribs: function(point, state) {
var attr = seriesTypes.column.prototype.pointAttribs.call(this, point, state);
// Prevent flickering whan called from setState
if (point.isFading) {
delete attr.fill;
}
// If vector-effect is not supported, we 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. TODO: Check unstyled
if (supportsVectorEffect) {
attr['vector-effect'] = 'non-scaling-stroke';
} else {
attr['stroke-width'] = 'inherit';
}
return attr;
},
/**
* Use the drawPoints method of column, that is able to handle simple shapeArgs.
* Extend it by assigning the tooltip position.
*/
drawPoints: function() {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
group = series.group,
chart = series.chart,
renderer = chart.renderer,
scaleX,
scaleY,
translateX,
translateY,
baseTrans = this.baseTrans;
// Set a group that handles transform during zooming and panning in order to preserve clipping
// on series.group
if (!series.transformGroup) {
series.transformGroup = renderer.g()
.attr({
scaleX: 1,
scaleY: 1
})
.add(group);
series.transformGroup.survive = true;
}
// Draw the shapes again
if (series.doFullTranslate()) {
// Individual point actions. TODO: Check unstyled.
// Draw them in transformGroup
series.group = series.transformGroup;
seriesTypes.column.prototype.drawPoints.apply(series);
series.group = group; // Reset
// Add class names
each(series.points, function(point) {
if (point.graphic) {
if (point.name) {
point.graphic.addClass('highcharts-name-' + point.name.replace(/ /g, '-').toLowerCase());
}
if (point.properties && point.properties['hc-key']) {
point.graphic.addClass('highcharts-key-' + point.properties['hc-key'].toLowerCase());
}
}
});
// Set the base for later scale-zooming. The originX and originY properties are the
// axis values in the plot area's upper left corner.
this.baseTrans = {
originX: xAxis.min - xAxis.minPixelPadding / xAxis.transA,
originY: yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA),
transAX: xAxis.transA,
transAY: yAxis.transA
};
// Reset transformation in case we're doing a full translate (#3789)
this.transformGroup.animate({
translateX: 0,
translateY: 0,
scaleX: 1,
scaleY: 1
});
// Just update the scale and transform for better performance
} else {
scaleX = xAxis.transA / baseTrans.transAX;
scaleY = yAxis.transA / baseTrans.transAY;
translateX = xAxis.toPixels(baseTrans.originX, true);
translateY = yAxis.toPixels(baseTrans.originY, true);
// Handle rounding errors in normal view (#3789)
if (scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01) {
scaleX = 1;
scaleY = 1;
translateX = Math.round(translateX);
translateY = Math.round(translateY);
}
this.transformGroup.animate({
translateX: translateX,
translateY: translateY,
scaleX: scaleX,
scaleY: scaleY
});
}
// 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.
if (!supportsVectorEffect) {
series.group.element.setAttribute(
'stroke-width',
series.options[
(series.pointAttrToOptions && series.pointAttrToOptions['stroke-width']) || 'borderWidth'
] / (scaleX || 1)
);
}
this.drawMapDataLabels();
},
/**
* Draw the data labels. Special for maps is the time that the data labels are drawn (after points),
* and the clipping of the dataLabelsGroup.
*/
drawMapDataLabels: function() {
Series.prototype.drawDataLabels.call(this);
if (this.dataLabelsGroup) {
this.dataLabelsGroup.clip(this.chart.clipRect);
}
},
/**
* Override render to throw in an async call in IE8. Otherwise it chokes on the US counties demo.
*/
render: function() {
var series = this,
render = Series.prototype.render;
// Give IE8 some time to breathe.
if (series.chart.renderer.isVML && series.data.length > 3000) {
setTimeout(function() {
render.call(series);
});
} else {
render.call(series);
}
},
/**
* The initial animation for the map series. By default, animation is disabled.
* Animation of map shapes is not at all supported in VML browsers.
*/
animate: function(init) {
var chart = this.chart,
animation = this.options.animation,
group = this.group,
xAxis = this.xAxis,
yAxis = this.yAxis,
left = xAxis.pos,
top = yAxis.pos;
if (chart.renderer.isSVG) {
if (animation === true) {
animation = {
duration: 1000
};
}
// Initialize the animation
if (init) {
// Scale down the group and place it in the center
group.attr({
translateX: left + xAxis.len / 2,
translateY: top + yAxis.len / 2,
scaleX: 0.001, // #1499
scaleY: 0.001
});
// Run the animation
} else {
group.animate({
translateX: left,
translateY: top,
scaleX: 1,
scaleY: 1
}, animation);
// Delete this function to allow it only once
this.animate = null;
}
}
},
/**
* Animate in the new series from the clicked point in the old series.
* Depends on the drilldown.js module
*/
animateDrilldown: function(init) {
var toBox = this.chart.plotBox,
level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1],
fromBox = level.bBox,
animationOptions = this.chart.options.drilldown.animation,
scale;
if (!init) {
scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height);
level.shapeArgs = {
scaleX: scale,
scaleY: scale,
translateX: fromBox.x,
translateY: fromBox.y
};
each(this.points, function(point) {
if (point.graphic) {
point.graphic
.attr(level.shapeArgs)
.animate({
scaleX: 1,
scaleY: 1,
translateX: 0,
translateY: 0
}, animationOptions);
}
});
this.animate = null;
}
},
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* When drilling up, pull out the individual point graphics from the lower series
* and animate them into the origin point in the upper series.
*/
animateDrillupFrom: function(level) {
seriesTypes.column.prototype.animateDrillupFrom.call(this, level);
},
/**
* When drilling up, keep the upper series invisible until the lower series has
* moved into place
*/
animateDrillupTo: function(init) {
seriesTypes.column.prototype.animateDrillupTo.call(this, init);
}
// Point class
}), extend({
/**
* Extend the Point object to split paths
*/
applyOptions: function(options, x) {
var point = Point.prototype.applyOptions.call(this, options, x),
series = this.series,
joinBy = series.joinBy,
mapPoint;
if (series.mapData) {
mapPoint = point[joinBy[1]] !== undefined && series.mapMap[point[joinBy[1]]];
if (mapPoint) {
// This applies only to bubbles
if (series.xyFromShape) {
point.x = mapPoint._midX;
point.y = mapPoint._midY;
}
extend(point, mapPoint); // copy over properties
} else {
point.value = point.value || null;
}
}
return point;
},
/**
* Stop the fade-out
*/
onMouseOver: function(e) {
clearTimeout(this.colorInterval);
if (this.value !== null) {
Point.prototype.onMouseOver.call(this, e);
} else { //#3401 Tooltip doesn't hide when hovering over null points
this.series.onMouseOut(e);
}
},
/**
* Zoom the chart to view a specific area point
*/
zoomTo: function() {
var point = this,
series = point.series;
series.xAxis.setExtremes(
point._minX,
point._maxX,
false
);
series.yAxis.setExtremes(
point._minY,
point._maxY,
false
);
series.chart.redraw();
}
}, colorPointMixin));
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
Chart = H.Chart,
doc = H.doc,
each = H.each,
extend = H.extend,
merge = H.merge,
pick = H.pick,
wrap = H.wrap;
function stopEvent(e) {
if (e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.cancelBubble = true;
}
}
// Add events to the Chart object itself
extend(Chart.prototype, {
renderMapNavigation: function() {
var chart = this,
options = this.options.mapNavigation,
buttons = options.buttons,
n,
button,
buttonOptions,
attr,
states,
hoverStates,
selectStates,
outerHandler = function(e) {
this.handler.call(chart, e);
stopEvent(e); // Stop default click event (#4444)
};
if (pick(options.enableButtons, options.enabled) && !chart.renderer.forExport) {
chart.mapNavButtons = [];
for (n in buttons) {
if (buttons.hasOwnProperty(n)) {
buttonOptions = merge(options.buttonOptions, buttons[n]);
button = chart.renderer.button(
buttonOptions.text,
0,
0,
outerHandler,
attr,
hoverStates,
selectStates,
0,
n === 'zoomIn' ? 'topbutton' : 'bottombutton'
)
.addClass('highcharts-map-navigation')
.attr({
width: buttonOptions.width,
height: buttonOptions.height,
title: chart.options.lang[n],
padding: buttonOptions.padding,
zIndex: 5
})
.add();
button.handler = buttonOptions.onclick;
button.align(extend(buttonOptions, {
width: button.width,
height: 2 * button.height
}), null, buttonOptions.alignTo);
addEvent(button.element, 'dblclick', stopEvent); // Stop double click event (#4444)
chart.mapNavButtons.push(button);
}
}
}
},
/**
* 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.
*/
fitToBox: function(inner, outer) {
each([
['x', 'width'],
['y', 'height']
], function(dim) {
var pos = dim[0],
size = dim[1];
if (inner[pos] + inner[size] > outer[pos] + outer[size]) { // right overflow
if (inner[size] > outer[size]) { // the general size is greater, fit fully to outer
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;
},
/**
* Zoom the map in or out by a certain amount. Less than 1 zooms in, greater than 1 zooms out.
*/
mapZoom: function(howMuch, centerXArg, centerYArg, mouseX, mouseY) {
/*if (this.isMapZooming) {
this.mapZoomQueue = arguments;
return;
}*/
var chart = this,
xAxis = chart.xAxis[0],
xRange = xAxis.max - xAxis.min,
centerX = pick(centerXArg, xAxis.min + xRange / 2),
newXRange = xRange * howMuch,
yAxis = chart.yAxis[0],
yRange = yAxis.max - yAxis.min,
centerY = pick(centerYArg, yAxis.min + yRange / 2),
newYRange = yRange * howMuch,
fixToX = mouseX ? ((mouseX - xAxis.pos) / xAxis.len) : 0.5,
fixToY = mouseY ? ((mouseY - yAxis.pos) / yAxis.len) : 0.5,
newXMin = centerX - newXRange * fixToX,
newYMin = centerY - newYRange * fixToY,
newExt = chart.fitToBox({
x: newXMin,
y: newYMin,
width: newXRange,
height: newYRange
}, {
x: xAxis.dataMin,
y: yAxis.dataMin,
width: xAxis.dataMax - xAxis.dataMin,
height: yAxis.dataMax - yAxis.dataMin
}),
zoomOut = newExt.x <= xAxis.dataMin &&
newExt.width >= xAxis.dataMax - xAxis.dataMin &&
newExt.y <= yAxis.dataMin &&
newExt.height >= yAxis.dataMax - yAxis.dataMin;
// When mousewheel zooming, fix the point under the mouse
if (mouseX) {
xAxis.fixTo = [mouseX - xAxis.pos, centerXArg];
}
if (mouseY) {
yAxis.fixTo = [mouseY - yAxis.pos, centerYArg];
}
// Zoom
if (howMuch !== undefined && !zoomOut) {
xAxis.setExtremes(newExt.x, newExt.x + newExt.width, false);
yAxis.setExtremes(newExt.y, newExt.y + newExt.height, false);
// Reset zoom
} else {
xAxis.setExtremes(undefined, undefined, false);
yAxis.setExtremes(undefined, undefined, false);
}
// Prevent zooming until this one is finished animating
/*chart.holdMapZoom = true;
setTimeout(function () {
chart.holdMapZoom = false;
}, 200);*/
/*delay = animation ? animation.duration || 500 : 0;
if (delay) {
chart.isMapZooming = true;
setTimeout(function () {
chart.isMapZooming = false;
if (chart.mapZoomQueue) {
chart.mapZoom.apply(chart, chart.mapZoomQueue);
}
chart.mapZoomQueue = null;
}, delay);
}*/
chart.redraw();
}
});
/**
* Extend the Chart.render method to add zooming and panning
*/
wrap(Chart.prototype, 'render', function(proceed) {
var chart = this,
mapNavigation = chart.options.mapNavigation;
// Render the plus and minus buttons. Doing this before the shapes makes getBBox much quicker, at least in Chrome.
chart.renderMapNavigation();
proceed.call(chart);
// Add the double click event
if (pick(mapNavigation.enableDoubleClickZoom, mapNavigation.enabled) || mapNavigation.enableDoubleClickZoomTo) {
addEvent(chart.container, 'dblclick', function(e) {
chart.pointer.onContainerDblClick(e);
});
}
// Add the mousewheel event
if (pick(mapNavigation.enableMouseWheelZoom, mapNavigation.enabled)) {
addEvent(chart.container, doc.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function(e) {
chart.pointer.onContainerMouseWheel(e);
stopEvent(e); // Issue #5011, returning false from non-jQuery event does not prevent default
return false;
});
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var extend = H.extend,
pick = H.pick,
Pointer = H.Pointer,
wrap = H.wrap;
// 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,
chart.xAxis[0].toValue(e.chartX),
chart.yAxis[0].toValue(e.chartY),
e.chartX,
e.chartY
);
}
},
/**
* The event handler for the mouse scroll event
*/
onContainerMouseWheel: function(e) {
var chart = this.chart,
delta;
e = this.normalize(e);
// Firefox uses e.detail, WebKit and IE uses wheelDelta
delta = e.detail || -(e.wheelDelta / 120);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
chart.mapZoom(
Math.pow(chart.options.mapNavigation.mouseWheelSensitivity, delta),
chart.xAxis[0].toValue(e.chartX),
chart.yAxis[0].toValue(e.chartY),
e.chartX,
e.chartY
);
}
}
});
// Implement the pinchType option
wrap(Pointer.prototype, 'zoomOption', function(proceed) {
var mapNavigation = this.chart.options.mapNavigation;
proceed.apply(this, [].slice.call(arguments, 1));
// Pinch status
if (pick(mapNavigation.enableTouchZoom, mapNavigation.enabled)) {
this.pinchX = this.pinchHor = this.pinchY = this.pinchVert = this.hasZoom = true;
}
});
// 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
);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
// The mapline series type
seriesType('mapline', 'map', {
}, {
type: 'mapline',
colorProp: 'stroke',
drawLegendSymbol: seriesTypes.line.prototype.drawLegendSymbol
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var merge = H.merge,
Point = H.Point,
seriesType = H.seriesType;
// The mappoint series type
seriesType('mappoint', 'scatter', {
dataLabels: {
enabled: true,
formatter: function() { // #2945
return this.point.name;
},
crop: false,
defer: false,
overflow: false,
style: {
color: '#000000'
}
}
// Prototype members
}, {
type: 'mappoint',
forceDL: true
// Point class
}, {
applyOptions: function(options, x) {
var mergedOptions = options.lat !== undefined && options.lon !== undefined ? merge(options, this.series.chart.fromLatLonToPoint(options)) : options;
return Point.prototype.applyOptions.call(this, mergedOptions, x);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
Axis = H.Axis,
color = H.color,
each = H.each,
isNumber = H.isNumber,
noop = H.noop,
pick = H.pick,
pInt = H.pInt,
Point = H.Point,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
/* ****************************************************************************
* Start Bubble series code *
*****************************************************************************/
seriesType('bubble', 'scatter', {
dataLabels: {
formatter: function() { // #2945
return this.point.z;
},
inside: true,
verticalAlign: 'middle'
},
// displayNegative: true,
marker: {
// Avoid offset in Point.setState
radius: null,
states: {
hover: {
radiusPlus: 0
}
}
},
minSize: 8,
maxSize: '20%',
// negativeColor: null,
// sizeBy: 'area'
softThreshold: false,
states: {
hover: {
halo: {
size: 5
}
}
},
tooltip: {
pointFormat: '({point.x}, {point.y}), Size: {point.z}'
},
turboThreshold: 0,
zThreshold: 0,
zoneAxis: 'z'
// Prototype members
}, {
pointArrayMap: ['y', 'z'],
parallelArrays: ['x', 'y', 'z'],
trackerGroups: ['group', 'dataLabelsGroup'],
bubblePadding: true,
zoneAxis: 'z',
/**
* 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.
*/
getRadii: function(zMin, zMax, minSize, maxSize) {
var len,
i,
pos,
zData = this.zData,
radii = [],
options = this.options,
sizeByArea = options.sizeBy !== 'width',
zThreshold = options.zThreshold,
zRange = zMax - zMin,
value,
radius;
// Set the shape type and arguments to be picked up in drawPoints
for (i = 0, len = zData.length; i < len; i++) {
value = zData[i];
// When sizing by threshold, the absolute value of z determines the size
// of the bubble.
if (options.sizeByAbsoluteValue && value !== null) {
value = Math.abs(value - zThreshold);
zMax = Math.max(zMax - zThreshold, Math.abs(zMin - zThreshold));
zMin = 0;
}
if (value === null) {
radius = null;
// Issue #4419 - if value is less than zMin, push a radius that's always smaller than the minimum size
} else if (value < zMin) {
radius = minSize / 2 - 1;
} else {
// Relative size, a number between 0 and 1
pos = zRange > 0 ? (value - zMin) / zRange : 0.5;
if (sizeByArea && pos >= 0) {
pos = Math.sqrt(pos);
}
radius = Math.ceil(minSize + pos * (maxSize - minSize)) / 2;
}
radii.push(radius);
}
this.radii = radii;
},
/**
* Perform animation on the bubbles
*/
animate: function(init) {
var animation = this.options.animation;
if (!init) { // run the animation
each(this.points, function(point) {
var graphic = point.graphic,
shapeArgs = point.shapeArgs;
if (graphic && shapeArgs) {
// start values
graphic.attr('r', 1);
// animate
graphic.animate({
r: shapeArgs.r
}, animation);
}
});
// delete this function to allow it only once
this.animate = null;
}
},
/**
* Extend the base translate method to handle bubble size
*/
translate: function() {
var i,
data = this.data,
point,
radius,
radii = this.radii;
// Run the parent method
seriesTypes.scatter.prototype.translate.call(this);
// Set the shape type and arguments to be picked up in drawPoints
i = data.length;
while (i--) {
point = data[i];
radius = radii ? radii[i] : 0; // #1737
if (isNumber(radius) && radius >= this.minPxSize / 2) {
// Shape arguments
point.shapeType = 'circle';
point.shapeArgs = {
x: point.plotX,
y: point.plotY,
r: 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
point.shapeArgs = point.plotY = point.dlBox = undefined; // #1691
}
}
},
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawLegendSymbol: function(legend, item) {
var renderer = this.chart.renderer,
radius = renderer.fontMetrics(legend.itemStyle.fontSize).f / 2;
item.legendSymbol = renderer.circle(
radius,
legend.baseline - radius,
radius
).attr({
zIndex: 3
}).add(item.legendGroup);
item.legendSymbol.isMarker = true;
},
drawPoints: seriesTypes.column.prototype.drawPoints,
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
buildKDTree: noop,
applyZones: noop
// Point class
}, {
haloPath: function() {
return Point.prototype.haloPath.call(this, this.shapeArgs.r + this.series.options.states.hover.halo.size);
},
ttBelow: false
});
/**
* 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,
extremes = {},
smallestSize = Math.min(chart.plotWidth, chart.plotHeight),
zMin = Number.MAX_VALUE,
zMax = -Number.MAX_VALUE,
range = this.max - min,
transA = axisLength / range,
activeSeries = [];
// Handle padding on the second pass, or on redraw
each(this.series, function(series) {
var seriesOptions = series.options,
zData;
if (series.bubblePadding && (series.visible || !chart.options.chart.ignoreHiddenSeries)) {
// Correction for #1673
axis.allowZoomOutside = true;
// Cache it
activeSeries.push(series);
if (isXAxis) { // because X axis is evaluated first
// For each series, translate the size extremes to pixel values
each(['minSize', 'maxSize'], function(prop) {
var length = seriesOptions[prop],
isPercent = /%$/.test(length);
length = pInt(length);
extremes[prop] = isPercent ?
smallestSize * length / 100 :
length;
});
series.minPxSize = extremes.minSize;
series.maxPxSize = extremes.maxSize;
// Find the min and max Z
zData = series.zData;
if (zData.length) { // #1735
zMin = pick(seriesOptions.zMin, Math.min(
zMin,
Math.max(
arrayMin(zData),
seriesOptions.displayNegative === false ? seriesOptions.zThreshold : -Number.MAX_VALUE
)
));
zMax = pick(seriesOptions.zMax, Math.max(zMax, arrayMax(zData)));
}
}
}
});
each(activeSeries, function(series) {
var data = series[dataKey],
i = data.length,
radius;
if (isXAxis) {
series.getRadii(zMin, zMax, series.minPxSize, series.maxPxSize);
}
if (range > 0) {
while (i--) {
if (isNumber(data[i]) && axis.dataMin <= data[i] && data[i] <= axis.dataMax) {
radius = series.radii[i];
pxMin = Math.min(((data[i] - min) * transA) - radius, pxMin);
pxMax = Math.max(((data[i] - min) * transA) + radius, pxMax);
}
}
}
});
if (activeSeries.length && range > 0 && !this.isLog) {
pxMax -= axisLength;
transA *= (axisLength + pxMin - pxMax) / axisLength;
each([
['min', 'userMin', pxMin],
['max', 'userMax', pxMax]
], function(keys) {
if (pick(axis.options[keys[0]], axis[keys[1]]) === undefined) {
axis[keys[0]] += keys[2] / transA;
}
});
}
};
/* ****************************************************************************
* End Bubble series code *
*****************************************************************************/
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var merge = H.merge,
Point = H.Point,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
// The mapbubble series type
if (seriesTypes.bubble) {
seriesType('mapbubble', 'bubble', {
animationLimit: 500,
tooltip: {
pointFormat: '{point.name}: {point.z}'
}
// Prototype members
}, {
xyFromShape: true,
type: 'mapbubble',
pointArrayMap: ['z'], // If one single value is passed, it is interpreted as z
/**
* Return the map area identified by the dataJoinBy option
*/
getMapData: seriesTypes.map.prototype.getMapData,
getBox: seriesTypes.map.prototype.getBox,
setData: seriesTypes.map.prototype.setData
// Point class
}, {
applyOptions: function(options, x) {
var point;
if (options && options.lat !== undefined && options.lon !== undefined) {
point = Point.prototype.applyOptions.call(
this,
merge(options, this.series.chart.fromLatLonToPoint(options)),
x
);
} else {
point = seriesTypes.map.prototype.pointClass.prototype.applyOptions.call(this, options, x);
}
return point;
},
ttBelow: false
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Chart = H.Chart,
each = H.each,
extend = H.extend,
error = H.error,
format = H.format,
merge = H.merge,
win = H.win,
wrap = H.wrap;
/**
* Test for point in polygon. Polygon defined as array of [x,y] points.
*/
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;
}
/**
* Get point from latLon using specified transform definition
*/
Chart.prototype.transformFromLatLon = function(latLon, transform) {
if (win.proj4 === undefined) {
error(21);
return {
x: 0,
y: null
};
}
var projected = win.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] - (transform.xoffset || 0)) * (transform.scale || 1) + (transform.xpan || 0)) * (transform.jsonres || 1) + (transform.jsonmarginX || 0),
y: (((transform.yoffset || 0) - rotated[1]) * (transform.scale || 1) + (transform.ypan || 0)) * (transform.jsonres || 1) - (transform.jsonmarginY || 0)
};
};
/**
* Get latLon from point using specified transform definition
*/
Chart.prototype.transformToLatLon = function(point, transform) {
if (win.proj4 === undefined) {
error(21);
return;
}
var normalized = {
x: ((point.x - (transform.jsonmarginX || 0)) / (transform.jsonres || 1) - (transform.xpan || 0)) / (transform.scale || 1) + (transform.xoffset || 0),
y: ((-point.y - (transform.jsonmarginY || 0)) / (transform.jsonres || 1) + (transform.ypan || 0)) / (transform.scale || 1) + (transform.yoffset || 0)
},
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
};
};
Chart.prototype.fromPointToLatLon = function(point) {
var transforms = this.mapTransforms,
transform;
if (!transforms) {
error(22);
return;
}
for (transform in transforms) {
if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone &&
pointInPolygon({
x: point.x,
y: -point.y
}, transforms[transform].hitZone.coordinates[0])) {
return this.transformToLatLon(point, transforms[transform]);
}
}
return this.transformToLatLon(point, transforms['default']); // eslint-disable-line dot-notation
};
Chart.prototype.fromLatLonToPoint = function(latLon) {
var transforms = this.mapTransforms,
transform,
coords;
if (!transforms) {
error(22);
return {
x: 0,
y: null
};
}
for (transform in transforms) {
if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone) {
coords = this.transformFromLatLon(latLon, transforms[transform]);
if (pointInPolygon({
x: coords.x,
y: -coords.y
}, transforms[transform].hitZone.coordinates[0])) {
return coords;
}
}
}
return this.transformFromLatLon(latLon, transforms['default']); // eslint-disable-line dot-notation
};
/**
* Convert a geojson object to map data of a given Highcharts type (map, mappoint or mapline).
*/
H.geojson = function(geojson, hType, series) {
var mapData = [],
path = [],
polygonToPath = function(polygon) {
var i,
len = polygon.length;
path.push('M');
for (i = 0; i < len; i++) {
if (i === 1) {
path.push('L');
}
path.push(polygon[i][0], -polygon[i][1]);
}
};
hType = hType || 'map';
each(geojson.features, function(feature) {
var geometry = feature.geometry,
type = geometry.type,
coordinates = geometry.coordinates,
properties = feature.properties,
point;
path = [];
if (hType === 'map' || hType === 'mapbubble') {
if (type === 'Polygon') {
each(coordinates, polygonToPath);
path.push('Z');
} else if (type === 'MultiPolygon') {
each(coordinates, function(items) {
each(items, polygonToPath);
});
path.push('Z');
}
if (path.length) {
point = {
path: path
};
}
} else if (hType === 'mapline') {
if (type === 'LineString') {
polygonToPath(coordinates);
} else if (type === 'MultiLineString') {
each(coordinates, polygonToPath);
}
if (path.length) {
point = {
path: path
};
}
} else if (hType === 'mappoint') {
if (type === 'Point') {
point = {
x: coordinates[0],
y: -coordinates[1]
};
}
}
if (point) {
mapData.push(extend(point, {
name: properties.name || properties.NAME,
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
});
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Chart = H.Chart,
defaultOptions = H.defaultOptions,
each = H.each,
extend = H.extend,
merge = H.merge,
pick = H.pick,
Renderer = H.Renderer,
SVGRenderer = H.SVGRenderer,
VMLRenderer = H.VMLRenderer;
// Add language
extend(defaultOptions.lang, {
zoomIn: 'Zoom in',
zoomOut: 'Zoom out'
});
// Set the default map navigation options
defaultOptions.mapNavigation = {
buttonOptions: {
alignTo: 'plotBox',
align: 'left',
verticalAlign: 'top',
x: 0,
width: 18,
height: 18,
padding: 5
},
buttons: {
zoomIn: {
onclick: function() {
this.mapZoom(0.5);
},
text: '+',
y: 0
},
zoomOut: {
onclick: function() {
this.mapZoom(2);
},
text: '-',
y: 28
}
},
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
};
/**
* Utility for reading SVG paths directly.
*/
H.splitPath = function(path) {
var i;
// Move letters apart
path = path.replace(/([A-Za-z])/g, ' $1 ');
// Trim
path = path.replace(/^\s*/, '').replace(/\s*$/, '');
// Split on spaces and commas
path = path.split(/[ ,]+/); // Extra comma to escape gulp.scripts task
// Parse numbers
for (i = 0; i < path.length; i++) {
if (!/[a-zA-Z]/.test(path[i])) {
path[i] = parseFloat(path[i]);
}
}
return path;
};
// A placeholder for map definitions
H.maps = {};
// Create symbols for the zoom buttons
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'
];
}
SVGRenderer.prototype.symbols.topbutton = function(x, y, w, h, attr) {
return selectiveRoundedRect(x - 1, y - 1, w, h, attr.r, attr.r, 0, 0);
};
SVGRenderer.prototype.symbols.bottombutton = function(x, y, w, h, attr) {
return selectiveRoundedRect(x - 1, y - 1, w, h, 0, 0, attr.r, attr.r);
};
// The symbol callbacks are generated on the SVGRenderer object in all browsers. Even
// VML browsers need this in order to generate shapes in export. Now share
// them with the VMLRenderer.
if (Renderer === VMLRenderer) {
each(['topbutton', 'bottombutton'], function(shape) {
VMLRenderer.prototype.symbols[shape] = SVGRenderer.prototype.symbols[shape];
});
}
/**
* A wrapper for Chart with all the default values for a Map
*/
H.Map = H.mapChart = function(a, b, c) {
var hasRenderToArg = typeof a === 'string' || a.nodeName,
options = arguments[hasRenderToArg ? 1 : 0],
hiddenAxis = {
endOnTick: false,
visible: false,
minPadding: 0,
maxPadding: 0,
startOnTick: false
},
seriesOptions,
defaultCreditsOptions = H.getOptions().credits;
/* For visual testing
hiddenAxis.gridLineWidth = 1;
hiddenAxis.gridZIndex = 10;
hiddenAxis.tickPositions = undefined;
// */
// Don't merge the data
seriesOptions = options.series;
options.series = null;
options = merge({
chart: {
panning: 'xy',
type: 'map'
},
credits: {
mapText: pick(defaultCreditsOptions.mapText, ' \u00a9 <a href="{geojson.copyrightUrl}">{geojson.copyrightShort}</a>'),
mapTextFull: pick(defaultCreditsOptions.mapTextFull, '{geojson.copyright}')
},
xAxis: hiddenAxis,
yAxis: merge(hiddenAxis, {
reversed: true
})
},
options, // user's options
{ // forced options
chart: {
inverted: false,
alignTicks: false
}
}
);
options.series = seriesOptions;
return hasRenderToArg ?
new Chart(a, options, c) :
new Chart(options, b);
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var colorPointMixin = H.colorPointMixin,
colorSeriesMixin = H.colorSeriesMixin,
each = H.each,
LegendSymbolMixin = H.LegendSymbolMixin,
merge = H.merge,
noop = H.noop,
pick = H.pick,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
// The Heatmap series type
seriesType('heatmap', 'scatter', {
animation: false,
borderWidth: 0,
dataLabels: {
formatter: function() { // #2945
return this.point.value;
},
inside: true,
verticalAlign: 'middle',
crop: false,
overflow: false,
padding: 0 // #3837
},
marker: null,
pointRange: null, // dynamically set to colsize by default
tooltip: {
pointFormat: '{point.x}, {point.y}: {point.value}<br/>'
},
states: {
normal: {
animation: true
},
hover: {
halo: false, // #3406, halo is not required on heatmaps
brightness: 0.2
}
}
}, merge(colorSeriesMixin, {
pointArrayMap: ['y', 'value'],
hasPointSpecificOptions: true,
supportsDrilldown: true,
getExtremesFromAll: true,
directTouch: true,
/**
* Override the init method to add point ranges on both axes.
*/
init: function() {
var options;
seriesTypes.scatter.prototype.init.apply(this, arguments);
options = this.options;
options.pointRange = pick(options.pointRange, options.colsize || 1); // #3758, prevent resetting in setData
this.yAxis.axisPointRange = options.rowsize || 1; // general point range
},
translate: function() {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
between = function(x, a, b) {
return Math.min(Math.max(a, x), b);
};
series.generatePoints();
each(series.points, function(point) {
var xPad = (options.colsize || 1) / 2,
yPad = (options.rowsize || 1) / 2,
x1 = between(Math.round(xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len),
x2 = between(Math.round(xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len),
y1 = between(Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len),
y2 = between(Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len);
// Set plotX and plotY for use in K-D-Tree and more
point.plotX = point.clientX = (x1 + x2) / 2;
point.plotY = (y1 + y2) / 2;
point.shapeType = 'rect';
point.shapeArgs = {
x: Math.min(x1, x2),
y: Math.min(y1, y2),
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1)
};
});
series.translateColors();
},
drawPoints: function() {
seriesTypes.column.prototype.drawPoints.call(this);
each(this.points, function(point) {
point.graphic.attr(this.colorAttribs(point, point.state));
}, this);
},
animate: noop,
getBox: noop,
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
getExtremes: function() {
// Get the extremes from the value data
Series.prototype.getExtremes.call(this, this.valueData);
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Get the extremes from the y data
Series.prototype.getExtremes.call(this);
}
}), colorPointMixin);
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
Chart = H.Chart,
createElement = H.createElement,
css = H.css,
defaultOptions = H.defaultOptions,
defaultPlotOptions = H.defaultPlotOptions,
each = H.each,
extend = H.extend,
fireEvent = H.fireEvent,
hasTouch = H.hasTouch,
inArray = H.inArray,
isObject = H.isObject,
Legend = H.Legend,
merge = H.merge,
pick = H.pick,
Point = H.Point,
Series = H.Series,
seriesTypes = H.seriesTypes,
svg = H.svg,
TrackerMixin;
/**
* TrackerMixin for points and graphs
*/
TrackerMixin = H.TrackerMixin = {
drawTrackerPoint: function() {
var series = this,
chart = series.chart,
pointer = chart.pointer,
onMouseOver = function(e) {
var target = e.target,
point;
while (target && !point) {
point = target.point;
target = target.parentNode;
}
if (point !== undefined && point !== chart.hoverPoint) { // undefined on graph in scatterchart
point.onMouseOver(e);
}
};
// Add reference to the point
each(series.points, function(point) {
if (point.graphic) {
point.graphic.element.point = point;
}
if (point.dataLabel) {
point.dataLabel.element.point = point;
}
});
// Add the event listeners, we need to do this only once
if (!series._hasTracking) {
each(series.trackerGroups, function(key) {
if (series[key]) { // we don't always have dataLabelsGroup
series[key]
.addClass('highcharts-tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function(e) {
pointer.onTrackerMouseOut(e);
});
if (hasTouch) {
series[key].on('touchstart', onMouseOver);
}
}
});
series._hasTracking = true;
}
},
/**
* Draw the tracker object that sits above all data labels and markers to
* track mouse events on the graph or points. For the line type charts
* the tracker uses the same graphPath, but with a greater stroke width
* for better control.
*/
drawTrackerGraph: function() {
var series = this,
options = series.options,
trackByArea = options.trackByArea,
trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
trackerPathLength = trackerPath.length,
chart = series.chart,
pointer = chart.pointer,
renderer = chart.renderer,
snap = chart.options.tooltip.snap,
tracker = series.tracker,
i,
onMouseOver = function() {
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
},
/*
* Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable
* IE6: 0.002
* IE7: 0.002
* IE8: 0.002
* IE9: 0.00000000001 (unlimited)
* IE10: 0.0001 (exporting only)
* FF: 0.00000000001 (unlimited)
* Chrome: 0.000001
* Safari: 0.000001
* Opera: 0.00000000001 (unlimited)
*/
TRACKER_FILL = 'rgba(192,192,192,' + (svg ? 0.0001 : 0.002) + ')';
// Extend end points. A better way would be to use round linecaps,
// but those are not clickable in VML.
if (trackerPathLength && !trackByArea) {
i = trackerPathLength + 1;
while (i--) {
if (trackerPath[i] === 'M') { // extend left side
trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], 'L');
}
if ((i && trackerPath[i] === 'M') || i === trackerPathLength) { // extend right side
trackerPath.splice(i, 0, 'L', trackerPath[i - 2] + snap, trackerPath[i - 1]);
}
}
}
// handle single points
/*for (i = 0; i < singlePoints.length; i++) {
singlePoint = singlePoints[i];
trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
L, singlePoint.plotX + snap, singlePoint.plotY);
}*/
// draw the tracker
if (tracker) {
tracker.attr({
d: trackerPath
});
} else if (series.graph) { // create
series.tracker = renderer.path(trackerPath)
.attr({
'stroke-linejoin': 'round', // #1225
visibility: series.visible ? 'visible' : 'hidden',
stroke: TRACKER_FILL,
fill: trackByArea ? TRACKER_FILL : 'none',
'stroke-width': series.graph.strokeWidth() + (trackByArea ? 0 : 2 * snap),
zIndex: 2
})
.add(series.group);
// The tracker is added to the series group, which is clipped, but is covered
// by the marker group. So the marker group also needs to capture events.
each([series.tracker, series.markerGroup], function(tracker) {
tracker.addClass('highcharts-tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function(e) {
pointer.onTrackerMouseOut(e);
});
if (hasTouch) {
tracker.on('touchstart', onMouseOver);
}
});
}
}
};
/* End TrackerMixin */
/**
* Add tracking event listener to the series group, so the point graphics
* themselves act as trackers
*/
if (seriesTypes.column) {
seriesTypes.column.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.scatter) {
seriesTypes.scatter.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
/*
* Extend Legend for item events
*/
extend(Legend.prototype, {
setItemEvents: function(item, legendItem, useHTML) {
var legend = this,
chart = legend.chart,
activeClass = 'highcharts-legend-' + (item.series ? 'point' : 'series') + '-active';
// Set the events on the item group, or in case of useHTML, the item itself (#1249)
(useHTML ? legendItem : item.legendGroup).on('mouseover', function() {
item.setState('hover');
// A CSS class to dim or hide other than the hovered series
chart.seriesGroup.addClass(activeClass);
})
.on('mouseout', function() {
// A CSS class to dim or hide other than the hovered series
chart.seriesGroup.removeClass(activeClass);
item.setState();
})
.on('click', function(event) {
var strLegendItemClick = 'legendItemClick',
fnLegendItemClick = function() {
if (item.setVisible) {
item.setVisible();
}
};
// Pass over the click/touch event. #4.
event = {
browserEvent: event
};
// click the name or symbol
if (item.firePointEvent) { // point
item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
} else {
fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
}
});
},
createCheckboxForItem: function(item) {
var legend = this;
item.checkbox = createElement('input', {
type: 'checkbox',
checked: item.selected,
defaultChecked: item.selected // required by IE7
}, legend.options.itemCheckboxStyle, legend.chart.container);
addEvent(item.checkbox, 'click', function(event) {
var target = event.target;
fireEvent(
item.series || item,
'checkboxClick', { // #3712
checked: target.checked,
item: item
},
function() {
item.select();
}
);
});
}
});
/*
* Extend the Chart object with interaction
*/
extend(Chart.prototype, {
/**
* Display the zoom button
*/
showResetZoom: function() {
var chart = this,
lang = defaultOptions.lang,
btnOptions = chart.options.chart.resetZoomButton,
theme = btnOptions.theme,
states = theme.states,
alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
function zoomOut() {
chart.zoomOut();
}
this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover)
.attr({
align: btnOptions.position.align,
title: lang.resetZoomTitle
})
.addClass('highcharts-reset-zoom')
.add()
.align(btnOptions.position, false, alignTo);
},
/**
* Zoom out to 1:1
*/
zoomOut: function() {
var chart = this;
fireEvent(chart, 'selection', {
resetSelection: true
}, function() {
chart.zoom();
});
},
/**
* Zoom into a given portion of the chart given by axis coordinates
* @param {Object} event
*/
zoom: function(event) {
var chart = this,
hasZoomed,
pointer = chart.pointer,
displayButton = false,
resetZoomButton;
// If zoom is called with no arguments, reset the axes
if (!event || event.resetSelection) {
each(chart.axes, function(axis) {
hasZoomed = axis.zoom();
});
} else { // else, zoom in on all axes
each(event.xAxis.concat(event.yAxis), function(axisData) {
var axis = axisData.axis,
isXAxis = axis.isXAxis;
// don't zoom more than minRange
if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
hasZoomed = axis.zoom(axisData.min, axisData.max);
if (axis.displayBtn) {
displayButton = true;
}
}
});
}
// Show or hide the Reset zoom button
resetZoomButton = chart.resetZoomButton;
if (displayButton && !resetZoomButton) {
chart.showResetZoom();
} else if (!displayButton && isObject(resetZoomButton)) {
chart.resetZoomButton = resetZoomButton.destroy();
}
// Redraw
if (hasZoomed) {
chart.redraw(
pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
);
}
},
/**
* Pan the chart by dragging the mouse across the pane. This function is called
* on mouse move, and the distance to pan is computed from chartX compared to
* the first chartX position in the dragging operation.
*/
pan: function(e, panning) {
var chart = this,
hoverPoints = chart.hoverPoints,
doRedraw;
// remove active points for shared tooltip
if (hoverPoints) {
each(hoverPoints, function(point) {
point.setState();
});
}
each(panning === 'xy' ? [1, 0] : [1], function(isX) { // xy is used in maps
var axis = chart[isX ? 'xAxis' : 'yAxis'][0],
horiz = axis.horiz,
mousePos = e[horiz ? 'chartX' : 'chartY'],
mouseDown = horiz ? 'mouseDownX' : 'mouseDownY',
startPos = chart[mouseDown],
halfPointRange = (axis.pointRange || 0) / 2,
extremes = axis.getExtremes(),
newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
newMax = axis.toValue(startPos + axis.len - mousePos, true) - halfPointRange,
goingLeft = startPos > mousePos; // #3613
if (axis.series.length &&
(goingLeft || newMin > Math.min(extremes.dataMin, extremes.min)) &&
(!goingLeft || newMax < Math.max(extremes.dataMax, extremes.max))) {
axis.setExtremes(newMin, newMax, false, false, {
trigger: 'pan'
});
doRedraw = true;
}
chart[mouseDown] = mousePos; // set new reference for next run
});
if (doRedraw) {
chart.redraw(false);
}
css(chart.container, {
cursor: 'move'
});
}
});
/*
* Extend the Point object with interaction
*/
extend(Point.prototype, {
/**
* Toggle the selection status of a point
* @param {Boolean} selected Whether to select or unselect the point.
* @param {Boolean} accumulate Whether to add to the previous selection. By default,
* this happens if the control key (Cmd on Mac) was pressed during clicking.
*/
select: function(selected, accumulate) {
var point = this,
series = point.series,
chart = series.chart;
selected = pick(selected, !point.selected);
// fire the event with the default handler
point.firePointEvent(selected ? 'select' : 'unselect', {
accumulate: accumulate
}, function() {
point.selected = point.options.selected = selected;
series.options.data[inArray(point, series.data)] = point.options;
point.setState(selected && 'select');
// unselect all other points unless Ctrl or Cmd + click
if (!accumulate) {
each(chart.getSelectedPoints(), function(loopPoint) {
if (loopPoint.selected && loopPoint !== point) {
loopPoint.selected = loopPoint.options.selected = false;
series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
loopPoint.setState('');
loopPoint.firePointEvent('unselect');
}
});
}
});
},
/**
* Runs on mouse over the point
*
* @param {Object} e The event arguments
* @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to
* actually hovered points. True for other points in shared tooltip.
*/
onMouseOver: function(e, byProximity) {
var point = this,
series = point.series,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
if (point.series) { // It may have been destroyed, #4130
// In shared tooltip, call mouse over when point/series is actually hovered: (#5766)
if (!byProximity) {
// set normal state to previous series
if (hoverPoint && hoverPoint !== point) {
hoverPoint.onMouseOut();
}
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
chart.hoverPoint = point;
}
// update the tooltip
if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
// hover point only for non shared points: (#5766)
point.setState('hover');
tooltip.refresh(point, e);
} else if (!tooltip) {
point.setState('hover');
}
// trigger the event
point.firePointEvent('mouseOver');
}
},
/**
* Runs on mouse out from the point
*/
onMouseOut: function() {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
this.firePointEvent('mouseOut');
if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
this.setState();
chart.hoverPoint = null;
}
},
/**
* Import events from the series' and point's options. Only do it on
* demand, to save processing time on hovering.
*/
importEvents: function() {
if (!this.hasImportedEvents) {
var point = this,
options = merge(point.series.options.point, point.options),
events = options.events,
eventType;
point.events = events;
for (eventType in events) {
addEvent(point, eventType, events[eventType]);
}
this.hasImportedEvents = true;
}
},
/**
* Set the point's state
* @param {String} state
*/
setState: function(state, move) {
var point = this,
plotX = Math.floor(point.plotX), // #4586
plotY = point.plotY,
series = point.series,
stateOptions = series.options.states[state] || {},
markerOptions = defaultPlotOptions[series.type].marker &&
series.options.marker,
normalDisabled = markerOptions && markerOptions.enabled === false,
markerStateOptions = (markerOptions && markerOptions.states &&
markerOptions.states[state]) || {},
stateDisabled = markerStateOptions.enabled === false,
stateMarkerGraphic = series.stateMarkerGraphic,
pointMarker = point.marker || {},
chart = series.chart,
halo = series.halo,
haloOptions,
markerAttribs,
newSymbol;
state = state || ''; // empty string
if (
// already has this state
(state === point.state && !move) ||
// selected points don't respond to hover
(point.selected && state !== 'select') ||
// series' state options is disabled
(stateOptions.enabled === false) ||
// general point marker's state options is disabled
(state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) ||
// individual point marker's state options is disabled
(state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
) {
return;
}
if (markerOptions) {
markerAttribs = series.markerAttribs(point, state);
}
// Apply hover styles to the existing point
if (point.graphic) {
if (point.state) {
point.graphic.removeClass('highcharts-point-' + point.state);
}
if (state) {
point.graphic.addClass('highcharts-point-' + state);
}
/*attribs = radius ? { // new symbol attributes (#507, #612)
x: plotX - radius,
y: plotY - radius,
width: 2 * radius,
height: 2 * radius
} : {};*/
if (markerAttribs) {
point.graphic.animate(
markerAttribs,
pick(
chart.options.chart.animation, // Turn off globally
markerStateOptions.animation,
markerOptions.animation
)
);
}
// Zooming in from a range with no markers to a range with markers
if (stateMarkerGraphic) {
stateMarkerGraphic.hide();
}
} else {
// if a graphic is not applied to each point in the normal state, create a shared
// graphic for the hover state
if (state && markerStateOptions) {
newSymbol = pointMarker.symbol || series.symbol;
// If the point has another symbol than the previous one, throw away the
// state marker graphic and force a new one (#1459)
if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
stateMarkerGraphic = stateMarkerGraphic.destroy();
}
// Add a new state marker graphic
if (!stateMarkerGraphic) {
if (newSymbol) {
series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
newSymbol,
markerAttribs.x,
markerAttribs.y,
markerAttribs.width,
markerAttribs.height
)
.add(series.markerGroup);
stateMarkerGraphic.currentSymbol = newSymbol;
}
// Move the existing graphic
} else {
stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054
x: markerAttribs.x,
y: markerAttribs.y
});
}
}
if (stateMarkerGraphic) {
stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450
stateMarkerGraphic.element.point = point; // #4310
}
}
// Show me your halo
haloOptions = stateOptions.halo;
if (haloOptions && haloOptions.size) {
if (!halo) {
series.halo = halo = chart.renderer.path()
.add(series.markerGroup || series.group);
}
H.stop(halo);
halo[move ? 'animate' : 'attr']({
d: point.haloPath(haloOptions.size)
});
halo.attr({
'class': 'highcharts-halo highcharts-color-' + pick(point.colorIndex, series.colorIndex)
});
} else if (halo) {
halo.animate({
d: point.haloPath(0)
}); // Hide
}
point.state = state;
},
/**
* Get the circular path definition for the halo
* @param {Number} size The radius of the circular halo
* @returns {Array} The path definition
*/
haloPath: function(size) {
var series = this.series,
chart = series.chart,
inverted = chart.inverted,
plotX = Math.floor(this.plotX);
return chart.renderer.symbols.circle(
(inverted ? series.yAxis.len - this.plotY : plotX) - size,
(inverted ? series.xAxis.len - plotX : this.plotY) - size,
size * 2,
size * 2
);
}
});
/*
* Extend the Series object with interaction
*/
extend(Series.prototype, {
/**
* Series mouse over handler
*/
onMouseOver: function() {
var series = this,
chart = series.chart,
hoverSeries = chart.hoverSeries;
// set normal state to previous series
if (hoverSeries && hoverSeries !== series) {
hoverSeries.onMouseOut();
}
// trigger the event, but to save processing time,
// only if defined
if (series.options.events.mouseOver) {
fireEvent(series, 'mouseOver');
}
// hover this
series.setState('hover');
chart.hoverSeries = series;
},
/**
* Series mouse out handler
*/
onMouseOut: function() {
// trigger the event only if listeners exist
var series = this,
options = series.options,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
chart.hoverSeries = null; // #182, set to null before the mouseOut event fires
// trigger mouse out on the point, which must be in this series
if (hoverPoint) {
hoverPoint.onMouseOut();
}
// fire the mouse out event
if (series && options.events.mouseOut) {
fireEvent(series, 'mouseOut');
}
// hide the tooltip
if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.hide();
}
// set normal state
series.setState();
},
/**
* Set the state of the graph
*/
setState: function(state) {
var series = this,
options = series.options,
graph = series.graph,
stateOptions = options.states,
lineWidth = options.lineWidth,
attribs,
i = 0;
state = state || '';
if (series.state !== state) {
// Toggle class names
each([series.group, series.markerGroup], function(group) {
if (group) {
// Old state
if (series.state) {
group.removeClass('highcharts-series-' + series.state);
}
// New state
if (state) {
group.addClass('highcharts-series-' + state);
}
}
});
series.state = state;
}
},
/**
* Set the visibility of the graph
*
* @param vis {Boolean} True to show the series, false to hide. If undefined,
* the visibility is toggled.
*/
setVisible: function(vis, redraw) {
var series = this,
chart = series.chart,
legendItem = series.legendItem,
showOrHide,
ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
oldVisibility = series.visible;
// if called without an argument, toggle visibility
series.visible = vis = series.options.visible = series.userOptions.visible = vis === undefined ? !oldVisibility : vis; // #5618
showOrHide = vis ? 'show' : 'hide';
// show or hide elements
each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker', 'tt'], function(key) {
if (series[key]) {
series[key][showOrHide]();
}
});
// hide tooltip (#1361)
if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) {
series.onMouseOut();
}
if (legendItem) {
chart.legend.colorizeItem(series, vis);
}
// rescale or adapt to resized chart
series.isDirty = true;
// in a stack, all other series are affected
if (series.options.stacking) {
each(chart.series, function(otherSeries) {
if (otherSeries.options.stacking && otherSeries.visible) {
otherSeries.isDirty = true;
}
});
}
// show or hide linked series
each(series.linkedSeries, function(otherSeries) {
otherSeries.setVisible(vis, false);
});
if (ignoreHiddenSeries) {
chart.isDirtyBox = true;
}
if (redraw !== false) {
chart.redraw();
}
fireEvent(series, showOrHide);
},
/**
* Show the graph
*/
show: function() {
this.setVisible(true);
},
/**
* Hide the graph
*/
hide: function() {
this.setVisible(false);
},
/**
* Set the selected state of the graph
*
* @param selected {Boolean} True to select the series, false to unselect. If
* undefined, the selection state is toggled.
*/
select: function(selected) {
var series = this;
// if called without an argument, toggle
series.selected = selected = (selected === undefined) ? !series.selected : selected;
if (series.checkbox) {
series.checkbox.checked = selected;
}
fireEvent(series, selected ? 'select' : 'unselect');
},
drawTracker: TrackerMixin.drawTrackerGraph
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Chart = H.Chart,
each = H.each,
inArray = H.inArray,
isObject = H.isObject,
pick = H.pick,
splat = H.splat;
/**
* Update the chart based on the current chart/document size and options for responsiveness
*/
Chart.prototype.setResponsive = function(redraw) {
var options = this.options.responsive;
if (options && options.rules) {
each(options.rules, function(rule) {
this.matchResponsiveRule(rule, redraw);
}, this);
}
};
/**
* Handle a single responsiveness rule
*/
Chart.prototype.matchResponsiveRule = function(rule, redraw) {
var respRules = this.respRules,
condition = rule.condition,
matches,
fn = rule.callback || function() {
return this.chartWidth <= pick(condition.maxWidth, Number.MAX_VALUE) &&
this.chartHeight <= pick(condition.maxHeight, Number.MAX_VALUE) &&
this.chartWidth >= pick(condition.minWidth, 0) &&
this.chartHeight >= pick(condition.minHeight, 0);
};
if (rule._id === undefined) {
rule._id = H.idCounter++;
}
matches = fn.call(this);
// Apply a rule
if (!respRules[rule._id] && matches) {
// Store the current state of the options
if (rule.chartOptions) {
respRules[rule._id] = this.currentOptions(rule.chartOptions);
this.update(rule.chartOptions, redraw);
}
// Unapply a rule based on the previous options before the rule
// was applied
} else if (respRules[rule._id] && !matches) {
this.update(respRules[rule._id], redraw);
delete respRules[rule._id];
}
};
/**
* Get the current values for a given set of options. Used before we update
* the chart with a new responsiveness rule.
* TODO: Restore axis options (by id?)
*/
Chart.prototype.currentOptions = function(options) {
var ret = {};
/**
* Recurse over a set of options and its current values,
* and store the current values in the ret object.
*/
function getCurrent(options, curr, ret) {
var key, i;
for (key in options) {
if (inArray(key, ['series', 'xAxis', 'yAxis']) > -1) {
options[key] = splat(options[key]);
ret[key] = [];
for (i = 0; i < options[key].length; i++) {
ret[key][i] = {};
getCurrent(options[key][i], curr[key][i], ret[key][i]);
}
} else if (isObject(options[key])) {
ret[key] = {};
getCurrent(options[key], curr[key] || {}, ret[key]);
} else {
ret[key] = curr[key] || null;
}
}
}
getCurrent(options, this.options, ret);
return ret;
};
}(Highcharts));
return Highcharts
}));
|
hare1039/cdnjs
|
ajax/libs/highmaps/5.0.1/js/highmaps.src.js
|
JavaScript
|
mit
| 812,097 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*jslint evil: true, regexp: true */
/*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push,
retrocycle, stringify, test, toString
*/
(function (exports) {
if (typeof exports.decycle !== 'function') {
exports.decycle = function decycle(object) {
'use strict';
var objects = [],
paths = [];
return (function derez(value, path) {
var i,
name,
nu;
switch (typeof value) {
case 'object':
if (!value) {
return null;
}
for (i = 0; i < objects.length; i += 1) {
if (objects[i] === value) {
return {$ref: paths[i]};
}
}
objects.push(value);
paths.push(path);
if (Object.prototype.toString.apply(value) === '[object Array]') {
nu = [];
for (i = 0; i < value.length; i += 1) {
nu[i] = derez(value[i], path + '[' + i + ']');
}
} else {
nu = {};
for (name in value) {
if (Object.prototype.hasOwnProperty.call(value, name)) {
nu[name] = derez(value[name],
path + '[' + JSON.stringify(name) + ']');
}
}
}
return nu;
case 'number':
case 'string':
case 'boolean':
return value;
}
}(object, '$'));
};
}
if (typeof exports.retrocycle !== 'function') {
exports.retrocycle = function retrocycle($) {
'use strict';
var px =
/^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;
(function rez(value) {
var i, item, name, path;
if (value && typeof value === 'object') {
if (Object.prototype.toString.apply(value) === '[object Array]') {
for (i = 0; i < value.length; i += 1) {
item = value[i];
if (item && typeof item === 'object') {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[i] = eval(path);
} else {
rez(item);
}
}
}
} else {
for (name in value) {
if (typeof value[name] === 'object') {
item = value[name];
if (item) {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[name] = eval(path);
} else {
rez(item);
}
}
}
}
}
}
}($));
return $;
};
}
}) (
(typeof exports !== 'undefined') ?
exports :
(window.JSON ?
(window.JSON) :
(window.JSON = {})
)
);
},{}],2:[function(require,module,exports){
var JSON2 = require('./json2');
var cycle = require('./cycle');
JSON2.decycle = cycle.decycle;
JSON2.retrocycle = cycle.retrocycle;
module.exports = JSON2;
},{"./cycle":1,"./json2":3}],3:[function(require,module,exports){
/*
json2.js
2011-10-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
(function (JSON) {
'use strict';
function f(n) {
return n < 10 ? '0' + n : n;
}
/* DDOPSON-2012-04-16 - mutating global prototypes is NOT allowed for a well-behaved module.
* It's also unneeded, since Date already defines toJSON() to the same ISOwhatever format below
* Thus, we skip this logic for the CommonJS case where 'exports' is defined
*/
if (typeof exports === 'undefined') {
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
}
if (typeof String.prototype.toJSON !== 'function') {
String.prototype.toJSON = function (key) { return this.valueOf(); };
}
if (typeof Number.prototype.toJSON !== 'function') {
Number.prototype.toJSON = function (key) { return this.valueOf(); };
}
if (typeof Boolean.prototype.toJSON !== 'function') {
Boolean.prototype.toJSON = function (key) { return this.valueOf(); };
}
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
var i,
k,
v,
length,
mind = gap,
partial,
value = holder[key];
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
return String(value);
case 'object':
if (!value) {
return 'null';
}
gap += indent;
partial = [];
if (Object.prototype.toString.apply(value) === '[object Array]') {
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
var i;
gap = '';
indent = '';
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
} else if (typeof space === 'string') {
indent = space;
}
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
return str('', {'': value});
};
}
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
var j;
function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
j = eval('(' + text + ')');
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
throw new SyntaxError('JSON.parse');
};
}
})(
(typeof exports !== 'undefined') ?
exports :
(window.JSON ?
(window.JSON) :
(window.JSON = {})
)
);
},{}],4:[function(require,module,exports){
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
var callbacks = this._callbacks[event];
if (!callbacks) return this;
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
},{}],5:[function(require,module,exports){
/*!
* domready (c) Dustin Diaz 2012 - License MIT
*/
!function (name, definition) {
if (typeof module != 'undefined') module.exports = definition()
else if (typeof define == 'function' && typeof define.amd == 'object') define(definition)
else this[name] = definition()
}('domready', function (ready) {
var fns = [], fn, f = false
, doc = document
, testEl = doc.documentElement
, hack = testEl.doScroll
, domContentLoaded = 'DOMContentLoaded'
, addEventListener = 'addEventListener'
, onreadystatechange = 'onreadystatechange'
, readyState = 'readyState'
, loadedRgx = hack ? /^loaded|^c/ : /^loaded|c/
, loaded = loadedRgx.test(doc[readyState])
function flush(f) {
loaded = 1
while (f = fns.shift()) f()
}
doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () {
doc.removeEventListener(domContentLoaded, fn, f)
flush()
}, f)
hack && doc.attachEvent(onreadystatechange, fn = function () {
if (/^c/.test(doc[readyState])) {
doc.detachEvent(onreadystatechange, fn)
flush()
}
})
return (ready = hack ?
function (fn) {
self != top ?
loaded ? fn() : fns.push(fn) :
function () {
try {
testEl.doScroll('left')
} catch (e) {
return setTimeout(function() { ready(fn) }, 50)
}
fn()
}()
} :
function (fn) {
loaded ? fn() : fns.push(fn)
})
})
},{}],6:[function(require,module,exports){
/**
* Module dependencies.
*/
var Emitter = require('emitter');
var reduce = require('reduce');
/**
* Root reference for iframes.
*/
var root = 'undefined' == typeof window
? this
: window;
/**
* Noop.
*/
function noop(){};
/**
* Check if `obj` is a host object,
* we don't want to serialize these :)
*
* TODO: future proof, move to compoent land
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isHost(obj) {
var str = {}.toString.call(obj);
switch (str) {
case '[object File]':
case '[object Blob]':
case '[object FormData]':
return true;
default:
return false;
}
}
/**
* Determine XHR.
*/
function getXHR() {
if (root.XMLHttpRequest
&& ('file:' != root.location.protocol || !root.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
}
return false;
}
/**
* Removes leading and trailing whitespace, added to support IE.
*
* @param {String} s
* @return {String}
* @api private
*/
var trim = ''.trim
? function(s) { return s.trim(); }
: function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
/**
* Check if `obj` is an object.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isObject(obj) {
return obj === Object(obj);
}
/**
* Serialize the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
function serialize(obj) {
if (!isObject(obj)) return obj;
var pairs = [];
for (var key in obj) {
if (null != obj[key]) {
pairs.push(encodeURIComponent(key)
+ '=' + encodeURIComponent(obj[key]));
}
}
return pairs.join('&');
}
/**
* Expose serialization method.
*/
request.serializeObject = serialize;
/**
* Parse the given x-www-form-urlencoded `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseString(str) {
var obj = {};
var pairs = str.split('&');
var parts;
var pair;
for (var i = 0, len = pairs.length; i < len; ++i) {
pair = pairs[i];
parts = pair.split('=');
obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
return obj;
}
/**
* Expose parser.
*/
request.parseString = parseString;
/**
* Default MIME type map.
*
* superagent.types.xml = 'application/xml';
*
*/
request.types = {
html: 'text/html',
json: 'application/json',
xml: 'application/xml',
urlencoded: 'application/x-www-form-urlencoded',
'form': 'application/x-www-form-urlencoded',
'form-data': 'application/x-www-form-urlencoded'
};
/**
* Default serialization map.
*
* superagent.serialize['application/xml'] = function(obj){
* return 'generated xml here';
* };
*
*/
request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify
};
/**
* Default parsers.
*
* superagent.parse['application/xml'] = function(str){
* return { object parsed from str };
* };
*
*/
request.parse = {
'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
};
/**
* Parse the given header `str` into
* an object containing the mapped fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseHeader(str) {
var lines = str.split(/\r?\n/);
var fields = {};
var index;
var line;
var field;
var val;
lines.pop();
for (var i = 0, len = lines.length; i < len; ++i) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
return fields;
}
/**
* Return the mime type for the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
function type(str){
return str.split(/ *; */).shift();
};
/**
* Return header field parameters.
*
* @param {String} str
* @return {Object}
* @api private
*/
function params(str){
return reduce(str.split(/ *; */), function(obj, str){
var parts = str.split(/ *= */)
, key = parts.shift()
, val = parts.shift();
if (key && val) obj[key] = val;
return obj;
}, {});
};
/**
* Initialize a new `Response` with the given `xhr`.
*
* - set flags (.ok, .error, etc)
* - parse header
*
* Examples:
*
* Aliasing `superagent` as `request` is nice:
*
* request = superagent;
*
* We can use the promise-like API, or pass callbacks:
*
* request.get('/').end(function(res){});
* request.get('/', function(res){});
*
* Sending data can be chained:
*
* request
* .post('/user')
* .send({ name: 'tj' })
* .end(function(res){});
*
* Or passed to `.send()`:
*
* request
* .post('/user')
* .send({ name: 'tj' }, function(res){});
*
* Or passed to `.post()`:
*
* request
* .post('/user', { name: 'tj' })
* .end(function(res){});
*
* Or further reduced to a single call for simple cases:
*
* request
* .post('/user', { name: 'tj' }, function(res){});
*
* @param {XMLHTTPRequest} xhr
* @param {Object} options
* @api private
*/
function Response(req, options) {
options = options || {};
this.req = req;
this.xhr = this.req.xhr;
this.text = this.req.method !='HEAD'
? this.xhr.responseText
: null;
this.setStatusProperties(this.xhr.status);
this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
this.header['content-type'] = this.xhr.getResponseHeader('content-type');
this.setHeaderProperties(this.header);
this.body = this.req.method != 'HEAD'
? this.parseBody(this.text)
: null;
}
/**
* Get case-insensitive `field` value.
*
* @param {String} field
* @return {String}
* @api public
*/
Response.prototype.get = function(field){
return this.header[field.toLowerCase()];
};
/**
* Set header related properties:
*
* - `.type` the content type without params
*
* A response of "Content-Type: text/plain; charset=utf-8"
* will provide you with a `.type` of "text/plain".
*
* @param {Object} header
* @api private
*/
Response.prototype.setHeaderProperties = function(header){
var ct = this.header['content-type'] || '';
this.type = type(ct);
var obj = params(ct);
for (var key in obj) this[key] = obj[key];
};
/**
* Parse the given body `str`.
*
* Used for auto-parsing of bodies. Parsers
* are defined on the `superagent.parse` object.
*
* @param {String} str
* @return {Mixed}
* @api private
*/
Response.prototype.parseBody = function(str){
var parse = request.parse[this.type];
return parse && str && str.length
? parse(str)
: null;
};
/**
* Set flags such as `.ok` based on `status`.
*
* For example a 2xx response will give you a `.ok` of __true__
* whereas 5xx will be __false__ and `.error` will be __true__. The
* `.clientError` and `.serverError` are also available to be more
* specific, and `.statusType` is the class of error ranging from 1..5
* sometimes useful for mapping respond colors etc.
*
* "sugar" properties are also defined for common cases. Currently providing:
*
* - .noContent
* - .badRequest
* - .unauthorized
* - .notAcceptable
* - .notFound
*
* @param {Number} status
* @api private
*/
Response.prototype.setStatusProperties = function(status){
var type = status / 100 | 0;
this.status = status;
this.statusType = type;
this.info = 1 == type;
this.ok = 2 == type;
this.clientError = 4 == type;
this.serverError = 5 == type;
this.error = (4 == type || 5 == type)
? this.toError()
: false;
this.accepted = 202 == status;
this.noContent = 204 == status || 1223 == status;
this.badRequest = 400 == status;
this.unauthorized = 401 == status;
this.notAcceptable = 406 == status;
this.notFound = 404 == status;
this.forbidden = 403 == status;
};
/**
* Return an `Error` representative of this response.
*
* @return {Error}
* @api public
*/
Response.prototype.toError = function(){
var req = this.req;
var method = req.method;
var url = req.url;
var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
var err = new Error(msg);
err.status = this.status;
err.method = method;
err.url = url;
return err;
};
/**
* Expose `Response`.
*/
request.Response = Response;
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {String} method
* @param {String} url
* @api public
*/
function Request(method, url) {
var self = this;
Emitter.call(this);
this._query = this._query || [];
this.method = method;
this.url = url;
this.header = {};
this._header = {};
this.on('end', function(){
var err = null;
var res = null;
try {
res = new Response(self);
} catch(e) {
err = new Error('Parser is unable to parse the response');
err.parse = true;
err.original = e;
}
self.callback(err, res);
});
}
/**
* Mixin `Emitter`.
*/
Emitter(Request.prototype);
/**
* Allow for extension
*/
Request.prototype.use = function(fn) {
fn(this);
return this;
}
/**
* Set timeout to `ms`.
*
* @param {Number} ms
* @return {Request} for chaining
* @api public
*/
Request.prototype.timeout = function(ms){
this._timeout = ms;
return this;
};
/**
* Clear previous timeout.
*
* @return {Request} for chaining
* @api public
*/
Request.prototype.clearTimeout = function(){
this._timeout = 0;
clearTimeout(this._timer);
return this;
};
/**
* Abort the request, and clear potential timeout.
*
* @return {Request}
* @api public
*/
Request.prototype.abort = function(){
if (this.aborted) return;
this.aborted = true;
this.xhr.abort();
this.clearTimeout();
this.emit('abort');
return this;
};
/**
* Set header `field` to `val`, or multiple fields with one object.
*
* Examples:
*
* req.get('/')
* .set('Accept', 'application/json')
* .set('X-API-Key', 'foobar')
* .end(callback);
*
* req.get('/')
* .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
* .end(callback);
*
* @param {String|Object} field
* @param {String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.set = function(field, val){
if (isObject(field)) {
for (var key in field) {
this.set(key, field[key]);
}
return this;
}
this._header[field.toLowerCase()] = val;
this.header[field] = val;
return this;
};
/**
* Remove header `field`.
*
* Example:
*
* req.get('/')
* .unset('User-Agent')
* .end(callback);
*
* @param {String} field
* @return {Request} for chaining
* @api public
*/
Request.prototype.unset = function(field){
delete this._header[field.toLowerCase()];
delete this.header[field];
return this;
};
/**
* Get case-insensitive header `field` value.
*
* @param {String} field
* @return {String}
* @api private
*/
Request.prototype.getHeader = function(field){
return this._header[field.toLowerCase()];
};
/**
* Set Content-Type to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.xml = 'application/xml';
*
* request.post('/')
* .type('xml')
* .send(xmlstring)
* .end(callback);
*
* request.post('/')
* .type('application/xml')
* .send(xmlstring)
* .end(callback);
*
* @param {String} type
* @return {Request} for chaining
* @api public
*/
Request.prototype.type = function(type){
this.set('Content-Type', request.types[type] || type);
return this;
};
/**
* Set Accept to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.json = 'application/json';
*
* request.get('/agent')
* .accept('json')
* .end(callback);
*
* request.get('/agent')
* .accept('application/json')
* .end(callback);
*
* @param {String} accept
* @return {Request} for chaining
* @api public
*/
Request.prototype.accept = function(type){
this.set('Accept', request.types[type] || type);
return this;
};
/**
* Set Authorization field value with `user` and `pass`.
*
* @param {String} user
* @param {String} pass
* @return {Request} for chaining
* @api public
*/
Request.prototype.auth = function(user, pass){
var str = btoa(user + ':' + pass);
this.set('Authorization', 'Basic ' + str);
return this;
};
/**
* Add query-string `val`.
*
* Examples:
*
* request.get('/shoes')
* .query('size=10')
* .query({ color: 'blue' })
*
* @param {Object|String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.query = function(val){
if ('string' != typeof val) val = serialize(val);
if (val) this._query.push(val);
return this;
};
/**
* Write the field `name` and `val` for "multipart/form-data"
* request bodies.
*
* ``` js
* request.post('/upload')
* .field('foo', 'bar')
* .end(callback);
* ```
*
* @param {String} name
* @param {String|Blob|File} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.field = function(name, val){
if (!this._formData) this._formData = new FormData();
this._formData.append(name, val);
return this;
};
/**
* Queue the given `file` as an attachment to the specified `field`,
* with optional `filename`.
*
* ``` js
* request.post('/upload')
* .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
* .end(callback);
* ```
*
* @param {String} field
* @param {Blob|File} file
* @param {String} filename
* @return {Request} for chaining
* @api public
*/
Request.prototype.attach = function(field, file, filename){
if (!this._formData) this._formData = new FormData();
this._formData.append(field, file, filename);
return this;
};
/**
* Send `data`, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
*
* request.get('/search')
* .end(callback)
*
*
* request.get('/search')
* .send({ search: 'query' })
* .send({ range: '1..5' })
* .send({ order: 'desc' })
* .end(callback)
*
*
* request.post('/user')
* .type('json')
* .send('{"name":"tj"})
* .end(callback)
*
*
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
*
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
*
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
*
* request.post('/user')
* .send('name=tobi')
* .send('species=ferret')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
Request.prototype.send = function(data){
var obj = isObject(data);
var type = this.getHeader('Content-Type');
if (obj && isObject(this._data)) {
for (var key in data) {
this._data[key] = data[key];
}
} else if ('string' == typeof data) {
if (!type) this.type('form');
type = this.getHeader('Content-Type');
if ('application/x-www-form-urlencoded' == type) {
this._data = this._data
? this._data + '&' + data
: data;
} else {
this._data = (this._data || '') + data;
}
} else {
this._data = data;
}
if (!obj) return this;
if (!type) this.type('json');
return this;
};
/**
* Invoke the callback with `err` and `res`
* and handle arity check.
*
* @param {Error} err
* @param {Response} res
* @api private
*/
Request.prototype.callback = function(err, res){
var fn = this._callback;
this.clearTimeout();
if (2 == fn.length) return fn(err, res);
if (err) return this.emit('error', err);
fn(res);
};
/**
* Invoke callback with x-domain error.
*
* @api private
*/
Request.prototype.crossDomainError = function(){
var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');
err.crossDomain = true;
this.callback(err);
};
/**
* Invoke callback with timeout error.
*
* @api private
*/
Request.prototype.timeoutError = function(){
var timeout = this._timeout;
var err = new Error('timeout of ' + timeout + 'ms exceeded');
err.timeout = timeout;
this.callback(err);
};
/**
* Enable transmission of cookies with x-domain requests.
*
* Note that for this to work the origin must not be
* using "Access-Control-Allow-Origin" with a wildcard,
* and also must set "Access-Control-Allow-Credentials"
* to "true".
*
* @api public
*/
Request.prototype.withCredentials = function(){
this._withCredentials = true;
return this;
};
/**
* Initiate request, invoking callback `fn(res)`
* with an instanceof `Response`.
*
* @param {Function} fn
* @return {Request} for chaining
* @api public
*/
Request.prototype.end = function(fn){
var self = this;
var xhr = this.xhr = getXHR();
var query = this._query.join('&');
var timeout = this._timeout;
var data = this._formData || this._data;
this._callback = fn || noop;
xhr.onreadystatechange = function(){
if (4 != xhr.readyState) return;
if (0 == xhr.status) {
if (self.aborted) return self.timeoutError();
return self.crossDomainError();
}
self.emit('end');
};
if (xhr.upload) {
xhr.upload.onprogress = function(e){
e.percent = e.loaded / e.total * 100;
self.emit('progress', e);
};
}
if (timeout && !this._timer) {
this._timer = setTimeout(function(){
self.abort();
}, timeout);
}
if (query) {
query = request.serializeObject(query);
this.url += ~this.url.indexOf('?')
? '&' + query
: '?' + query;
}
xhr.open(this.method, this.url, true);
if (this._withCredentials) xhr.withCredentials = true;
if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
var serialize = request.serialize[this.getHeader('Content-Type')];
if (serialize) data = serialize(data);
}
for (var field in this.header) {
if (null == this.header[field]) continue;
xhr.setRequestHeader(field, this.header[field]);
}
this.emit('request', this);
xhr.send(data);
return this;
};
/**
* Expose `Request`.
*/
request.Request = Request;
/**
* Issue a request:
*
* Examples:
*
* request('GET', '/users').end(callback)
* request('/users').end(callback)
* request('/users', callback)
*
* @param {String} method
* @param {String|Function} url or callback
* @return {Request}
* @api public
*/
function request(method, url) {
if ('function' == typeof url) {
return new Request('GET', method).end(url);
}
if (1 == arguments.length) {
return new Request('GET', method);
}
return new Request(method, url);
}
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.get = function(url, data, fn){
var req = request('GET', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.query(data);
if (fn) req.end(fn);
return req;
};
/**
* HEAD `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.head = function(url, data, fn){
var req = request('HEAD', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* DELETE `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Function} fn
* @return {Request}
* @api public
*/
request.del = function(url, fn){
var req = request('DELETE', url);
if (fn) req.end(fn);
return req;
};
/**
* PATCH `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.patch = function(url, data, fn){
var req = request('PATCH', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* POST `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.post = function(url, data, fn){
var req = request('POST', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* PUT `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.put = function(url, data, fn){
var req = request('PUT', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* Expose `request`.
*/
module.exports = request;
},{"emitter":7,"reduce":8}],7:[function(require,module,exports){
arguments[4][4][0].apply(exports,arguments)
},{"dup":4}],8:[function(require,module,exports){
/**
* Reduce `arr` with `fn`.
*
* @param {Array} arr
* @param {Function} fn
* @param {Mixed} initial
*
* TODO: combatible error handling?
*/
module.exports = function(arr, fn, initial){
var idx = 0;
var len = arr.length;
var curr = arguments.length == 3
? initial
: arr[idx++];
while (idx < len) {
curr = fn.call(null, curr, arr[idx], ++idx, arr);
}
return curr;
};
},{}],9:[function(require,module,exports){
var Keen = require("./index"),
each = require("./utils/each");
module.exports = function(){
var loaded = window['Keen'] || null,
cached = window['_' + 'Keen'] || null,
clients,
ready;
if (loaded && cached) {
clients = cached['clients'] || {},
ready = cached['ready'] || [];
each(clients, function(client, id){
each(Keen.prototype, function(method, key){
loaded.prototype[key] = method;
});
each(["Query", "Request", "Dataset", "Dataviz"], function(name){
loaded[name] = (Keen[name]) ? Keen[name] : function(){};
});
if (client._config) {
client.configure.call(client, client._config);
}
if (client._setGlobalProperties) {
each(client._setGlobalProperties, function(fn){
client.setGlobalProperties.apply(client, fn);
});
}
if (client._addEvent) {
each(client._addEvent, function(obj){
client.addEvent.apply(client, obj);
});
}
var callback = client._on || [];
if (client._on) {
each(client._on, function(obj){
client.on.apply(client, obj);
});
client.trigger('ready');
}
each(["_config", "_setGlobalProperties", "_addEvent", "_on"], function(name){
if (client[name]) {
client[name] = undefined;
try{
delete client[name];
} catch(e){}
}
});
});
each(ready, function(cb, i){
Keen.once("ready", cb);
});
}
window['_' + 'Keen'] = undefined;
try {
delete window['_' + 'Keen']
} catch(e) {}
};
},{"./index":17,"./utils/each":23}],10:[function(require,module,exports){
var Emitter = require('component-emitter');
Emitter.prototype.trigger = Emitter.prototype.emit;
module.exports = Emitter;
},{"component-emitter":4}],11:[function(require,module,exports){
module.exports = function(){
return "undefined" == typeof window ? "server" : "browser";
};
},{}],12:[function(require,module,exports){
var each = require('../utils/each'),
JSON2 = require('JSON2');
module.exports = function(params){
var query = [];
each(params, function(value, key){
if ('string' !== typeof value) {
value = JSON2.stringify(value);
}
query.push(key + '=' + encodeURIComponent(value));
});
return '?' + query.join('&');
};
},{"../utils/each":23,"JSON2":2}],13:[function(require,module,exports){
module.exports = function(){
if ("undefined" !== typeof window) {
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
return 2000;
}
}
return 16000;
};
},{}],14:[function(require,module,exports){
module.exports = function() {
var root = "undefined" == typeof window ? this : window;
if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
}
return false;
};
},{}],15:[function(require,module,exports){
module.exports = function(err, res, callback) {
var cb = callback || function() {};
if (res && !res.ok) {
var is_err = res.body && res.body.error_code;
err = new Error(is_err ? res.body.message : 'Unknown error occurred');
err.code = is_err ? res.body.error_code : 'UnknownError';
}
if (err) {
cb(err, null);
}
else {
cb(null, res.body);
}
return;
};
},{}],16:[function(require,module,exports){
var superagent = require('superagent');
var each = require('../utils/each'),
getXHR = require('./get-xhr-object');
module.exports = function(type, opts){
return function(request) {
var __super__ = request.constructor.prototype.end;
if ( 'undefined' === typeof window ) return;
request.requestType = request.requestType || {};
request.requestType['type'] = type;
request.requestType['options'] = request.requestType['options'] || {
async: true,
success: {
responseText: '{ "created": true }',
status: 201
},
error: {
responseText: '{ "error_code": "ERROR", "message": "Request failed" }',
status: 404
}
};
if (opts) {
if ( 'boolean' === typeof opts.async ) {
request.requestType['options'].async = opts.async;
}
if ( opts.success ) {
extend(request.requestType['options'].success, opts.success);
}
if ( opts.error ) {
extend(request.requestType['options'].error, opts.error);
}
}
request.end = function(fn){
var self = this,
reqType = (this.requestType) ? this.requestType['type'] : 'xhr',
query,
timeout;
if ( ('GET' !== self['method'] || 'xhr' === reqType) && self.requestType['options'].async ) {
__super__.call(self, fn);
return;
}
query = self._query.join('&');
timeout = self._timeout;
self._callback = fn || noop;
if (timeout && !self._timer) {
self._timer = setTimeout(function(){
abortRequest.call(self);
}, timeout);
}
if (query) {
query = superagent.serializeObject(query);
self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query;
}
self.emit('request', self);
if ( !self.requestType['options'].async ) {
sendXhrSync.call(self);
}
else if ( 'jsonp' === reqType ) {
sendJsonp.call(self);
}
else if ( 'beacon' === reqType ) {
sendBeacon.call(self);
}
return self;
};
return request;
};
};
function sendXhrSync(){
var xhr = getXHR();
if (xhr) {
xhr.open('GET', this.url, false);
xhr.send(null);
}
return this;
}
function sendJsonp(){
var self = this,
timestamp = new Date().getTime(),
script = document.createElement('script'),
parent = document.getElementsByTagName('head')[0],
callbackName = 'keenJSONPCallback',
loaded = false;
callbackName += timestamp;
while (callbackName in window) {
callbackName += 'a';
}
window[callbackName] = function(response) {
if (loaded === true) return;
loaded = true;
handleSuccess.call(self, response);
cleanup();
};
script.src = self.url + '&jsonp=' + callbackName;
parent.appendChild(script);
script.onreadystatechange = function() {
if (loaded === false && self.readyState === 'loaded') {
loaded = true;
handleError.call(self);
cleanup();
}
};
script.onerror = function() {
if (loaded === false) {
loaded = true;
handleError.call(self);
cleanup();
}
};
function cleanup(){
window[callbackName] = undefined;
try {
delete window[callbackName];
} catch(e){}
parent.removeChild(script);
}
}
function sendBeacon(){
var self = this,
img = document.createElement('img'),
loaded = false;
img.onload = function() {
loaded = true;
if ('naturalHeight' in this) {
if (this.naturalHeight + this.naturalWidth === 0) {
this.onerror();
return;
}
} else if (this.width + this.height === 0) {
this.onerror();
return;
}
handleSuccess.call(self);
};
img.onerror = function() {
loaded = true;
handleError.call(self);
};
img.src = self.url + '&c=clv1';
}
function handleSuccess(res){
var opts = this.requestType['options']['success'],
response = '';
xhrShim.call(this, opts);
if (res) {
try {
response = JSON.stringify(res);
} catch(e) {}
}
else {
response = opts['responseText'];
}
this.xhr.responseText = response;
this.xhr.status = opts['status'];
this.emit('end');
}
function handleError(){
var opts = this.requestType['options']['error'];
xhrShim.call(this, opts);
this.xhr.responseText = opts['responseText'];
this.xhr.status = opts['status'];
this.emit('end');
}
function abortRequest(){
this.aborted = true;
this.clearTimeout();
this.emit('abort');
}
function xhrShim(opts){
this.xhr = {
getAllResponseHeaders: function(){ return ''; },
getResponseHeader: function(){ return 'application/json'; },
responseText: opts['responseText'],
status: opts['status']
};
return this;
}
},{"../utils/each":23,"./get-xhr-object":14,"superagent":6}],17:[function(require,module,exports){
var root = this;
var previous_Keen = root.Keen;
var extend = require('./utils/extend');
var Emitter = require('./helpers/emitter-shim');
function Keen(config) {
this.configure(config || {});
Keen.trigger('client', this);
}
Keen.debug = false;
Keen.enabled = true;
Keen.loaded = true;
Keen.version = '3.2.0';
Emitter(Keen);
Emitter(Keen.prototype);
Keen.prototype.configure = function(cfg){
var config = cfg || {};
if (config['host']) {
config['host'].replace(/.*?:\/\//g, '');
}
if (config.protocol && config.protocol === 'auto') {
config['protocol'] = location.protocol.replace(/:/g, '');
}
this.config = {
projectId : config.projectId,
writeKey : config.writeKey,
readKey : config.readKey,
masterKey : config.masterKey,
requestType : config.requestType || 'jsonp',
host : config['host'] || 'api.keen.io/3.0',
protocol : config['protocol'] || 'https',
globalProperties: null
};
if (Keen.debug) {
this.on('error', Keen.log);
}
this.trigger('ready');
};
Keen.prototype.projectId = function(str){
if (!arguments.length) return this.config.projectId;
this.config.projectId = (str ? String(str) : null);
return this;
};
Keen.prototype.masterKey = function(str){
if (!arguments.length) return this.config.masterKey;
this.config.masterKey = (str ? String(str) : null);
return this;
};
Keen.prototype.readKey = function(str){
if (!arguments.length) return this.config.readKey;
this.config.readKey = (str ? String(str) : null);
return this;
};
Keen.prototype.writeKey = function(str){
if (!arguments.length) return this.config.writeKey;
this.config.writeKey = (str ? String(str) : null);
return this;
};
Keen.prototype.url = function(path){
if (!this.projectId()) {
this.trigger('error', 'Client is missing projectId property');
return;
}
return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path;
};
Keen.log = function(message) {
if (Keen.debug && typeof console == 'object') {
console.log('[Keen IO]', message);
}
};
Keen.noConflict = function(){
root.Keen = previous_Keen;
return Keen;
};
Keen.ready = function(fn){
if (Keen.loaded) {
fn();
} else {
Keen.once('ready', fn);
}
};
module.exports = Keen;
},{"./helpers/emitter-shim":10,"./utils/extend":24}],18:[function(require,module,exports){
var JSON2 = require('JSON2');
var request = require('superagent');
var Keen = require('../index');
var base64 = require('../utils/base64'),
each = require('../utils/each'),
getContext = require('../helpers/get-context'),
getQueryString = require('../helpers/get-query-string'),
getUrlMaxLength = require('../helpers/get-url-max-length'),
getXHR = require('../helpers/get-xhr-object'),
requestTypes = require('../helpers/superagent-request-types'),
responseHandler = require('../helpers/superagent-handle-response');
module.exports = function(collection, payload, callback, async) {
var self = this,
urlBase = this.url('/events/' + collection),
reqType = this.config.requestType,
data = {},
cb = callback,
isAsync,
getUrl;
isAsync = ('boolean' === typeof async) ? async : true;
if (!Keen.enabled) {
handleValidationError.call(self, 'Keen.enabled = false');
return;
}
if (!self.projectId()) {
handleValidationError.call(self, 'Missing projectId property');
return;
}
if (!self.writeKey()) {
handleValidationError.call(self, 'Missing writeKey property');
return;
}
if (!collection || typeof collection !== 'string') {
handleValidationError.call(self, 'Collection name must be a string');
return;
}
if (self.config.globalProperties) {
data = self.config.globalProperties(collection);
}
each(payload, function(value, key){
data[key] = value;
});
if ( !getXHR() && 'xhr' === reqType ) {
reqType = 'jsonp';
}
if ( 'xhr' !== reqType || !isAsync ) {
getUrl = prepareGetRequest.call(self, urlBase, data);
}
if ( getUrl && getContext() === 'browser' ) {
request
.get(getUrl)
.use(function(req){
req.async = isAsync;
return req;
})
.use(requestTypes(reqType))
.end(handleResponse);
}
else if ( getXHR() || getContext() === 'server' ) {
request
.post(urlBase)
.set('Content-Type', 'application/json')
.set('Authorization', self.writeKey())
.send(data)
.end(handleResponse);
}
else {
self.trigger('error', 'Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.');
}
function handleResponse(err, res){
responseHandler(err, res, cb);
cb = callback = null;
}
function handleValidationError(msg){
var err = 'Event not recorded: ' + msg;
self.trigger('error', err);
if (cb) {
cb.call(self, err, null);
cb = callback = null;
}
}
return;
};
function prepareGetRequest(url, data){
url += getQueryString({
api_key : this.writeKey(),
data : base64.encode( JSON2.stringify(data) ),
modified : new Date().getTime()
});
return ( url.length < getUrlMaxLength() ) ? url : false;
}
},{"../helpers/get-context":11,"../helpers/get-query-string":12,"../helpers/get-url-max-length":13,"../helpers/get-xhr-object":14,"../helpers/superagent-handle-response":15,"../helpers/superagent-request-types":16,"../index":17,"../utils/base64":22,"../utils/each":23,"JSON2":2,"superagent":6}],19:[function(require,module,exports){
var Keen = require('../index');
var request = require('superagent');
var each = require('../utils/each'),
getContext = require('../helpers/get-context'),
getXHR = require('../helpers/get-xhr-object'),
requestTypes = require('../helpers/superagent-request-types'),
responseHandler = require('../helpers/superagent-handle-response');
module.exports = function(payload, callback) {
var self = this,
urlBase = this.url('/events'),
data = {},
cb = callback;
if (!Keen.enabled) {
handleValidationError.call(self, 'Keen.enabled = false');
return;
}
if (!self.projectId()) {
handleValidationError.call(self, 'Missing projectId property');
return;
}
if (!self.writeKey()) {
handleValidationError.call(self, 'Missing writeKey property');
return;
}
if (arguments.length > 2) {
handleValidationError.call(self, 'Incorrect arguments provided to #addEvents method');
return;
}
if (typeof payload !== 'object' || payload instanceof Array) {
handleValidationError.call(self, 'Request payload must be an object');
return;
}
if (self.config.globalProperties) {
each(payload, function(events, collection){
each(events, function(body, index){
var base = self.config.globalProperties(collection);
each(body, function(value, key){
base[key] = value;
});
data[collection].push(base);
});
});
}
else {
data = payload;
}
if ( getXHR() || getContext() === 'server' ) {
request
.post(urlBase)
.set('Content-Type', 'application/json')
.set('Authorization', self.writeKey())
.send(data)
.end(function(err, res){
responseHandler(err, res, cb);
cb = callback = null;
});
}
else {
self.trigger('error', 'Events not recorded: XHR support is required for batch upload');
}
function handleValidationError(msg){
var err = 'Events not recorded: ' + msg;
self.trigger('error', err);
if (cb) {
cb.call(self, err, null);
cb = callback = null;
}
}
return;
};
},{"../helpers/get-context":11,"../helpers/get-xhr-object":14,"../helpers/superagent-handle-response":15,"../helpers/superagent-request-types":16,"../index":17,"../utils/each":23,"superagent":6}],20:[function(require,module,exports){
module.exports = function(newGlobalProperties) {
if (newGlobalProperties && typeof(newGlobalProperties) == "function") {
this.config.globalProperties = newGlobalProperties;
} else {
this.trigger("error", "Invalid value for global properties: " + newGlobalProperties);
}
};
},{}],21:[function(require,module,exports){
var addEvent = require("./addEvent");
module.exports = function(jsEvent, eventCollection, payload, timeout, timeoutCallback){
var evt = jsEvent,
target = (evt.currentTarget) ? evt.currentTarget : (evt.srcElement || evt.target),
timer = timeout || 500,
triggered = false,
targetAttr = "",
callback,
win;
if (target.getAttribute !== void 0) {
targetAttr = target.getAttribute("target");
} else if (target.target) {
targetAttr = target.target;
}
if ((targetAttr == "_blank" || targetAttr == "blank") && !evt.metaKey) {
win = window.open("about:blank");
win.document.location = target.href;
}
if (target.nodeName === "A") {
callback = function(){
if(!triggered && !evt.metaKey && (targetAttr !== "_blank" && targetAttr !== "blank")){
triggered = true;
window.location = target.href;
}
};
} else if (target.nodeName === "FORM") {
callback = function(){
if(!triggered){
triggered = true;
target.submit();
}
};
} else {
this.trigger("error", "#trackExternalLink method not attached to an <a> or <form> DOM element");
}
if (timeoutCallback) {
callback = function(){
if(!triggered){
triggered = true;
timeoutCallback();
}
};
}
addEvent.call(this, eventCollection, payload, callback);
setTimeout(callback, timer);
if (!evt.metaKey) {
return false;
}
};
},{"./addEvent":18}],22:[function(require,module,exports){
module.exports = {
map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function (n) {
"use strict";
var o = "", i = 0, m = this.map, i1, i2, i3, e1, e2, e3, e4;
n = this.utf8.encode(n);
while (i < n.length) {
i1 = n.charCodeAt(i++); i2 = n.charCodeAt(i++); i3 = n.charCodeAt(i++);
e1 = (i1 >> 2); e2 = (((i1 & 3) << 4) | (i2 >> 4)); e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6));
e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63;
o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4);
} return o;
},
decode: function (n) {
"use strict";
var o = "", i = 0, m = this.map, cc = String.fromCharCode, e1, e2, e3, e4, c1, c2, c3;
n = n.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < n.length) {
e1 = m.indexOf(n.charAt(i++)); e2 = m.indexOf(n.charAt(i++));
e3 = m.indexOf(n.charAt(i++)); e4 = m.indexOf(n.charAt(i++));
c1 = (e1 << 2) | (e2 >> 4); c2 = ((e2 & 15) << 4) | (e3 >> 2);
c3 = ((e3 & 3) << 6) | e4;
o = o + (cc(c1) + ((e3 != 64) ? cc(c2) : "")) + (((e4 != 64) ? cc(c3) : ""));
} return this.utf8.decode(o);
},
utf8: {
encode: function (n) {
"use strict";
var o = "", i = 0, cc = String.fromCharCode, c;
while (i < n.length) {
c = n.charCodeAt(i++); o = o + ((c < 128) ? cc(c) : ((c > 127) && (c < 2048)) ?
(cc((c >> 6) | 192) + cc((c & 63) | 128)) : (cc((c >> 12) | 224) + cc(((c >> 6) & 63) | 128) + cc((c & 63) | 128)));
} return o;
},
decode: function (n) {
"use strict";
var o = "", i = 0, cc = String.fromCharCode, c2, c;
while (i < n.length) {
c = n.charCodeAt(i);
o = o + ((c < 128) ? [cc(c), i++][0] : ((c > 191) && (c < 224)) ?
[cc(((c & 31) << 6) | ((c2 = n.charCodeAt(i + 1)) & 63)), (i += 2)][0] :
[cc(((c & 15) << 12) | (((c2 = n.charCodeAt(i + 1)) & 63) << 6) | ((c3 = n.charCodeAt(i + 2)) & 63)), (i += 3)][0]);
} return o;
}
}
};
},{}],23:[function(require,module,exports){
module.exports = function(o, cb, s){
var n;
if (!o){
return 0;
}
s = !s ? o : s;
if (o instanceof Array){
for (n=0; n<o.length; n++) {
if (cb.call(s, o[n], n, o) === false){
return 0;
}
}
} else {
for (n in o){
if (o.hasOwnProperty(n)) {
if (cb.call(s, o[n], n, o) === false){
return 0;
}
}
}
}
return 1;
};
},{}],24:[function(require,module,exports){
module.exports = function(target){
for (var i = 1; i < arguments.length; i++) {
for (var prop in arguments[i]){
target[prop] = arguments[i][prop];
}
}
return target;
};
},{}],25:[function(require,module,exports){
function parseParams(str){
var urlParams = {},
match,
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = str.split("?")[1];
while (!!(match=search.exec(query))) {
urlParams[decode(match[1])] = decode(match[2]);
}
return urlParams;
};
module.exports = parseParams;
},{}],26:[function(require,module,exports){
(function (global){
;(function (f) {
if (typeof define === "function" && define.amd) {
define("keen", [], function(){ return f(); });
}
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f();
}
var g = null;
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
}
if (g) {
g.Keen = f();
}
})(function() {
"use strict";
var Keen = require("./core"),
extend = require("./core/utils/extend");
extend(Keen.prototype, {
"addEvent" : require("./core/lib/addEvent"),
"addEvents" : require("./core/lib/addEvents"),
"setGlobalProperties" : require("./core/lib/setGlobalProperties"),
"trackExternalLink" : require("./core/lib/trackExternalLink")
});
Keen.Base64 = require("./core/utils/base64");
Keen.utils = {
"domready" : require("domready"),
"each" : require("./core/utils/each"),
"extend" : extend,
"parseParams" : require("./core/utils/parseParams")
};
if (Keen.loaded) {
setTimeout(function(){
Keen.utils.domready(function(){
Keen.emit("ready");
});
}, 0);
}
require("./core/async")();
module.exports = Keen;
return Keen;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./core":17,"./core/async":9,"./core/lib/addEvent":18,"./core/lib/addEvents":19,"./core/lib/setGlobalProperties":20,"./core/lib/trackExternalLink":21,"./core/utils/base64":22,"./core/utils/each":23,"./core/utils/extend":24,"./core/utils/parseParams":25,"domready":5}]},{},[26]);
|
extend1994/cdnjs
|
ajax/libs/keen-js/3.2.0/keen-tracker.js
|
JavaScript
|
mit
| 66,915 |
/*
* jQuery UI Effects Pulsate 1.7.2
*
* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Effects/Pulsate
*
* Depends:
* effects.core.js
*/
(function($) {
$.effects.pulsate = function(o) {
return this.queue(function() {
// Create element
var el = $(this);
// Set options
var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
var times = o.options.times || 5; // Default # of times
var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2;
// Adjust
if (mode == 'hide') times--;
if (el.is(':hidden')) { // Show fadeIn
el.css('opacity', 0);
el.show(); // Show
el.animate({opacity: 1}, duration, o.options.easing);
times = times-2;
}
// Animate
for (var i = 0; i < times; i++) { // Pulsate
el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing);
};
if (mode == 'hide') { // Last Pulse
el.animate({opacity: 0}, duration, o.options.easing, function(){
el.hide(); // Hide
if(o.callback) o.callback.apply(this, arguments); // Callback
});
} else {
el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing, function(){
if(o.callback) o.callback.apply(this, arguments); // Callback
});
};
el.queue('fx', function() { el.dequeue(); });
el.dequeue();
});
};
})(jQuery);
|
glenn-edgar/lua_frame_work
|
web_pages/development-bundle/ui/effects.pulsate.js
|
JavaScript
|
mit
| 1,505 |
var config = require('../config'),
_ = require('underscore'),
path = require('path'),
when = require('when'),
api = require('../api'),
mailer = require('../mail'),
errors = require('../errorHandling'),
storage = require('../storage'),
updateCheck = require('../update-check'),
adminNavbar,
adminControllers,
loginSecurity = [];
// TODO: combine path/navClass to single "slug(?)" variable with no prefix
adminNavbar = {
content: {
name: 'Content',
navClass: 'content',
key: 'admin.navbar.content',
path: '/'
},
add: {
name: 'New Post',
navClass: 'editor',
key: 'admin.navbar.editor',
path: '/editor/'
},
settings: {
name: 'Settings',
navClass: 'settings',
key: 'admin.navbar.settings',
path: '/settings/'
}
};
// TODO: make this a util or helper
function setSelected(list, name) {
_.each(list, function (item, key) {
item.selected = key === name;
});
return list;
}
adminControllers = {
'uploader': function (req, res) {
var type = req.files.uploadimage.type,
ext = path.extname(req.files.uploadimage.name).toLowerCase(),
store = storage.get_storage();
if ((type !== 'image/jpeg' && type !== 'image/png' && type !== 'image/gif' && type !== 'image/svg+xml')
|| (ext !== '.jpg' && ext !== '.jpeg' && ext !== '.png' && ext !== '.gif' && ext !== '.svg' && ext !== '.svgz')) {
return res.send(415, 'Unsupported Media Type');
}
store
.save(req.files.uploadimage)
.then(function (url) {
return res.send(url);
})
.otherwise(function (e) {
errors.logError(e);
return res.send(500, e.message);
});
},
'login': function (req, res) {
/*jslint unparam:true*/
res.render('login', {
bodyClass: 'ghost-login',
hideNavbar: true,
adminNav: setSelected(adminNavbar, 'login')
});
},
'auth': function (req, res) {
var currentTime = process.hrtime()[0],
remoteAddress = req.connection.remoteAddress,
denied = '';
loginSecurity = _.filter(loginSecurity, function (ipTime) {
return (ipTime.time + 2 > currentTime);
});
denied = _.find(loginSecurity, function (ipTime) {
return (ipTime.ip === remoteAddress);
});
if (!denied) {
loginSecurity.push({ip: remoteAddress, time: currentTime});
api.users.check({email: req.body.email, pw: req.body.password}).then(function (user) {
req.session.regenerate(function (err) {
if (!err) {
req.session.user = user.id;
var redirect = config.paths().subdir + '/ghost/';
if (req.body.redirect) {
redirect += decodeURIComponent(req.body.redirect);
}
// If this IP address successfully logins we
// can remove it from the array of failed login attempts.
loginSecurity = _.reject(loginSecurity, function (ipTime) {
return ipTime.ip === remoteAddress;
});
res.json(200, {redirect: redirect});
}
});
}, function (error) {
res.json(401, {error: error.message});
});
} else {
res.json(401, {error: 'Slow down, there are way too many login attempts!'});
}
},
'changepw': function (req, res) {
return api.users.changePassword({
currentUser: req.session.user,
oldpw: req.body.password,
newpw: req.body.newpassword,
ne2pw: req.body.ne2password
}).then(function () {
res.json(200, {msg: 'Password changed successfully'});
}, function (error) {
res.send(401, {error: error.message});
});
},
'signup': function (req, res) {
/*jslint unparam:true*/
res.render('signup', {
bodyClass: 'ghost-signup',
hideNavbar: true,
adminNav: setSelected(adminNavbar, 'login')
});
},
'doRegister': function (req, res) {
var name = req.body.name,
email = req.body.email,
password = req.body.password;
api.users.add({
name: name,
email: email,
password: password
}).then(function (user) {
api.settings.edit('email', email).then(function () {
var message = {
to: email,
subject: 'Your New Ghost Blog',
html: '<p><strong>Hello!</strong></p>' +
'<p>Good news! You\'ve successfully created a brand new Ghost blog over on ' + config().url + '</p>' +
'<p>You can log in to your admin account with the following details:</p>' +
'<p> Email Address: ' + email + '<br>' +
'Password: The password you chose when you signed up</p>' +
'<p>Keep this email somewhere safe for future reference, and have fun!</p>' +
'<p>xoxo</p>' +
'<p>Team Ghost<br>' +
'<a href="https://ghost.org">https://ghost.org</a></p>'
};
mailer.send(message).otherwise(function (error) {
errors.logError(
error.message,
"Unable to send welcome email, your blog will continue to function.",
"Please see http://docs.ghost.org/mail/ for instructions on configuring email."
);
});
req.session.regenerate(function (err) {
if (!err) {
if (req.session.user === undefined) {
req.session.user = user.id;
}
res.json(200, {redirect: config.paths().subdir + '/ghost/'});
}
});
});
}).otherwise(function (error) {
res.json(401, {error: error.message});
});
},
'forgotten': function (req, res) {
/*jslint unparam:true*/
res.render('forgotten', {
bodyClass: 'ghost-forgotten',
hideNavbar: true,
adminNav: setSelected(adminNavbar, 'login')
});
},
'generateResetToken': function (req, res) {
var email = req.body.email;
api.users.generateResetToken(email).then(function (token) {
var siteLink = '<a href="' + config().url + '">' + config().url + '</a>',
resetUrl = config().url.replace(/\/$/, '') + '/ghost/reset/' + token + '/',
resetLink = '<a href="' + resetUrl + '">' + resetUrl + '</a>',
message = {
to: email,
subject: 'Reset Password',
html: '<p><strong>Hello!</strong></p>' +
'<p>A request has been made to reset the password on the site ' + siteLink + '.</p>' +
'<p>Please follow the link below to reset your password:<br><br>' + resetLink + '</p>' +
'<p>Ghost</p>'
};
return mailer.send(message);
}).then(function success() {
var notification = {
type: 'success',
message: 'Check your email for further instructions',
status: 'passive',
id: 'successresetpw'
};
return api.notifications.add(notification).then(function () {
res.json(200, {redirect: config.paths().subdir + '/ghost/signin/'});
});
}, function failure(error) {
// TODO: This is kind of sketchy, depends on magic string error.message from Bookshelf.
// TODO: It's debatable whether we want to just tell the user we sent the email in this case or not, we are giving away sensitive info here.
if (error && error.message === 'EmptyResponse') {
error.message = "Invalid email address";
}
res.json(401, {error: error.message});
});
},
'reset': function (req, res) {
// Validate the request token
var token = req.params.token;
api.users.validateToken(token).then(function () {
// Render the reset form
res.render('reset', {
bodyClass: 'ghost-reset',
hideNavbar: true,
adminNav: setSelected(adminNavbar, 'reset')
});
}).otherwise(function (err) {
// Redirect to forgotten if invalid token
var notification = {
type: 'error',
message: 'Invalid or expired token',
status: 'persistent',
id: 'errorinvalidtoken'
};
errors.logError(err, 'admin.js', "Please check the provided token for validity and expiration.");
return api.notifications.add(notification).then(function () {
res.redirect(config.paths().subdir + '/ghost/forgotten');
});
});
},
'resetPassword': function (req, res) {
var token = req.params.token,
newPassword = req.param('newpassword'),
ne2Password = req.param('ne2password');
api.users.resetPassword(token, newPassword, ne2Password).then(function () {
var notification = {
type: 'success',
message: 'Password changed successfully.',
status: 'passive',
id: 'successresetpw'
};
return api.notifications.add(notification).then(function () {
res.json(200, {redirect: config.paths().subdir + '/ghost/signin/'});
});
}).otherwise(function (err) {
// TODO: Better error message if we can tell whether the passwords didn't match or something
res.json(401, {error: err.message});
});
},
'logout': function (req, res) {
req.session.destroy();
var notification = {
type: 'success',
message: 'You were successfully signed out',
status: 'passive',
id: 'successlogout'
};
return api.notifications.add(notification).then(function () {
res.redirect(config.paths().subdir + '/ghost/signin/');
});
},
'index': function (req, res) {
/*jslint unparam:true*/
function renderIndex() {
res.render('content', {
bodyClass: 'manage',
adminNav: setSelected(adminNavbar, 'content')
});
}
when.join(
updateCheck(res),
when(renderIndex())
// an error here should just get logged
).otherwise(errors.logError);
},
'editor': function (req, res) {
if (req.params.id !== undefined) {
res.render('editor', {
bodyClass: 'editor',
adminNav: setSelected(adminNavbar, 'content')
});
} else {
res.render('editor', {
bodyClass: 'editor',
adminNav: setSelected(adminNavbar, 'add')
});
}
},
'content': function (req, res) {
/*jslint unparam:true*/
res.render('content', {
bodyClass: 'manage',
adminNav: setSelected(adminNavbar, 'content')
});
},
'settings': function (req, res, next) {
// TODO: Centralise list/enumeration of settings panes, so we don't
// run into trouble in future.
var allowedSections = ['', 'general', 'user'],
section = req.url.replace(/(^\/ghost\/settings[\/]*|\/$)/ig, '');
if (allowedSections.indexOf(section) < 0) {
return next();
}
res.render('settings', {
bodyClass: 'settings',
adminNav: setSelected(adminNavbar, 'settings')
});
},
'debug': { /* ugly temporary stuff for managing the app before it's properly finished */
index: function (req, res) {
/*jslint unparam:true*/
res.render('debug', {
bodyClass: 'settings',
adminNav: setSelected(adminNavbar, 'settings')
});
}
}
};
module.exports = adminControllers;
|
joeljacobson/ghost
|
core/server/controllers/admin.js
|
JavaScript
|
mit
| 12,937 |
describe("Ext.dom.Element_scroll", function() {
var el;
afterEach(function(){
Ext.destroy(el);
el = null;
});
function expectLeft(left) {
expect(el.dom.scrollLeft).toBe(left);
}
function expectTop(top) {
expect(el.dom.scrollTop).toBe(top);
}
function expectLeftTop(left, top) {
expectLeft(left);
expectTop(top);
}
describe("scroll", function() {
var scrollSize = Ext.getScrollbarSize(),
maxHorz = 600 + scrollSize.width,
maxVert = 600 + scrollSize.height;
beforeEach(function(){
el = Ext.getBody().createChild({
style: {
width: '400px',
height: '400px',
overflow: 'auto'
},
cn: [{
style: {
width: '1000px',
height: '1000px'
}
}]
});
});
describe("right", function(){
it("should accept 'right' as a param", function(){
el.scroll('right', 200);
expectLeft(200);
});
it("should accept 'r' as a param", function(){
el.scroll('r', 175);
expectLeft(175);
});
it("should append to the current position", function(){
el.scroll('r', 200);
el.scroll('r', 300);
expectLeft(500);
});
it("should constrain the max scroll", function(){
el.scroll('r', 2000);
expectLeft(maxHorz);
});
});
describe("left", function(){
it("should accept 'left' as a param", function(){
el.scroll('r', 200);
el.scroll('left', 125);
expectLeft(75);
});
it("should accept 'l' as a param", function(){
el.scroll('r', 300);
el.scroll('l', 150);
expectLeft(150);
});
it("should append to the current position", function(){
el.scroll('r', 500);
el.scroll('l', 300);
el.scroll('l', 100);
expectLeft(100);
});
it("should constrain to 0", function(){
el.scroll('r', 100);
el.scroll('l', 350);
expectLeft(0);
});
});
describe("bottom", function(){
it("should accept 'bottom' as a param", function() {
el.scroll('bottom', 30);
expectTop(30);
});
it("should accept 'b' as a param", function() {
el.scroll('b', 120);
expectTop(120);
});
it("should accept 'down' as a param", function() {
el.scroll('down', 30);
expectTop(30);
});
it("should accept 'd' as a param", function() {
el.scroll('d', 375);
expectTop(375);
});
it("should append to the current position", function() {
el.scroll('b', 120);
el.scroll('b', 130);
expectTop(250);
});
it("should constrain the max scroll", function(){
el.scroll('b', 1500);
expectTop(maxVert);
});
});
describe("up", function(){
it("should accept 'up' as a param", function() {
el.scroll('b', 30);
el.scroll('u', 10);
expectTop(20);
});
it("should accept 'u' as a param", function() {
el.scroll('b', 120);
el.scroll('u', 50);
expectTop(70);
});
it("should accept 'top' as a param", function() {
el.scroll('b', 200);
el.scroll('top', 130);
expectTop(70);
});
it("should accept 't' as a param", function() {
el.scroll('b', 500);
el.scroll('t', 375);
expectTop(125);
});
it("should append to the current position", function() {
el.scroll('b', 300);
el.scroll('t', 120);
el.scroll('t', 130);
expectTop(50);
});
it("should constrain the max scroll", function() {
el.scroll('b', 300);
el.scroll('t', 3000);
expectTop(0);
});
});
});
});
|
applifireAlgo/ZenClubApp
|
zenws/src/main/webapp/ext/packages/sencha-core/test/specs/dom/Element_scroll.js
|
JavaScript
|
gpl-3.0
| 5,088 |
๏ปฟ/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'wsc', 'km', {
btnIgnore: 'แแทแแแแแถแแแแแแผแ',
btnIgnoreAll: 'แแทแแแแแถแแแแแแผแ แแถแแแขแแ',
btnReplace: 'แแแแฝแ',
btnReplaceAll: 'แแแแฝแแแถแแแขแแ',
btnUndo: 'แแถแแกแพแแแทแ',
changeTo: 'แแแแถแแแแแแผแแแ
',
errorLoading: 'Error loading application service host: %s.',
ieSpellDownload: 'แแปแแแถแแแแแแแทแแธแแทแแทแแแแขแแแแแถแแทแแปแแแ แ แแพแ
แแแแถแแแแแธแแถ?',
manyChanges: 'แแถแแแทแแทแแแแขแแแแแถแแทแแปแแแแแถแแ
แแ: %1 แแถแแแแแถแแแแแถแแแแแแผแ',
noChanges: 'แแถแแแทแแทแแแแขแแแแแถแแทแแปแแแแแถแแ
แแ: แแปแแแถแแแแแถแแแแแแผแ',
noMispell: 'แแถแแแทแแทแแแแขแแแแแถแแทแแปแแแแแถแแ
แแ: แแแแถแแแแ แปแ',
noSuggestions: '- แแแแถแแแแแพแ -',
notAvailable: 'Sorry, but service is unavailable now.',
notInDic: 'แแแแถแแแแแปแแแ
แแถแแปแแแแ',
oneChange: 'แแถแแแทแแทแแแแขแแแแแถแแทแแปแแแแแถแแ
แแ: แแถแแแแแฝแแแแแผแ
แแถแแแแแถแแแแแแผแ',
progress: 'แแแแปแแแทแแทแแแแขแแแแแถแแทแแปแแแ...',
title: 'Spell Checker',
toolbar: 'แแทแแทแแแแขแแแแแถแแทแแปแแแ'
});
|
janusnic/dj-21v
|
unit_15/mysite/public/static/ckeditor/ckeditor/plugins/wsc/lang/km.js
|
JavaScript
|
mit
| 1,772 |
/*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314)
*/
// @tag dom,core
// @require AbstractQuery.js
/**
* Abstract base class for {@link Ext.dom.Helper}.
* @private
*/
Ext.define('Ext.dom.AbstractHelper', {
emptyTags : /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
confRe : /^(?:tag|children|cn|html|tpl|tplData)$/i,
endRe : /end/i,
styleSepRe: /\s*(?::|;)\s*/,
// Since cls & for are reserved words, we need to transform them
attributeTransform: { cls : 'class', htmlFor : 'for' },
closeTags: {},
decamelizeName : (function () {
var camelCaseRe = /([a-z])([A-Z])/g,
cache = {};
function decamel (match, p1, p2) {
return p1 + '-' + p2.toLowerCase();
}
return function (s) {
return cache[s] || (cache[s] = s.replace(camelCaseRe, decamel));
};
}()),
generateMarkup: function(spec, buffer) {
var me = this,
specType = typeof spec,
attr, val, tag, i, closeTags;
if (specType == "string" || specType == "number") {
buffer.push(spec);
} else if (Ext.isArray(spec)) {
for (i = 0; i < spec.length; i++) {
if (spec[i]) {
me.generateMarkup(spec[i], buffer);
}
}
} else {
tag = spec.tag || 'div';
buffer.push('<', tag);
for (attr in spec) {
if (spec.hasOwnProperty(attr)) {
val = spec[attr];
if (!me.confRe.test(attr)) {
if (typeof val == "object") {
buffer.push(' ', attr, '="');
me.generateStyles(val, buffer).push('"');
} else {
buffer.push(' ', me.attributeTransform[attr] || attr, '="', val, '"');
}
}
}
}
// Now either just close the tag or try to add children and close the tag.
if (me.emptyTags.test(tag)) {
buffer.push('/>');
} else {
buffer.push('>');
// Apply the tpl html, and cn specifications
if ((val = spec.tpl)) {
val.applyOut(spec.tplData, buffer);
}
if ((val = spec.html)) {
buffer.push(val);
}
if ((val = spec.cn || spec.children)) {
me.generateMarkup(val, buffer);
}
// we generate a lot of close tags, so cache them rather than push 3 parts
closeTags = me.closeTags;
buffer.push(closeTags[tag] || (closeTags[tag] = '</' + tag + '>'));
}
}
return buffer;
},
/**
* Converts the styles from the given object to text. The styles are CSS style names
* with their associated value.
*
* The basic form of this method returns a string:
*
* var s = Ext.DomHelper.generateStyles({
* backgroundColor: 'red'
* });
*
* // s = 'background-color:red;'
*
* Alternatively, this method can append to an output array.
*
* var buf = [];
*
* ...
*
* Ext.DomHelper.generateStyles({
* backgroundColor: 'red'
* }, buf);
*
* In this case, the style text is pushed on to the array and the array is returned.
*
* @param {Object} styles The object describing the styles.
* @param {String[]} [buffer] The output buffer.
* @return {String/String[]} If buffer is passed, it is returned. Otherwise the style
* string is returned.
*/
generateStyles: function (styles, buffer) {
var a = buffer || [],
name;
for (name in styles) {
if (styles.hasOwnProperty(name)) {
a.push(this.decamelizeName(name), ':', styles[name], ';');
}
}
return buffer || a.join('');
},
/**
* Returns the markup for the passed Element(s) config.
* @param {Object} spec The DOM object spec (and children)
* @return {String}
*/
markup: function(spec) {
if (typeof spec == "string") {
return spec;
}
var buf = this.generateMarkup(spec, []);
return buf.join('');
},
/**
* Applies a style specification to an element.
* @param {String/HTMLElement} el The element to apply styles to
* @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
* a function which returns such a specification.
*/
applyStyles: function(el, styles) {
if (styles) {
var i = 0,
len;
el = Ext.fly(el, '_applyStyles');
if (typeof styles == 'function') {
styles = styles.call();
}
if (typeof styles == 'string') {
styles = Ext.util.Format.trim(styles).split(this.styleSepRe);
for (len = styles.length; i < len;) {
el.setStyle(styles[i++], styles[i++]);
}
} else if (Ext.isObject(styles)) {
el.setStyle(styles);
}
}
},
/**
* Inserts an HTML fragment into the DOM.
* @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
*
* For example take the following HTML: `<div>Contents</div>`
*
* Using different `where` values inserts element to the following places:
*
* - beforeBegin: `<HERE><div>Contents</div>`
* - afterBegin: `<div><HERE>Contents</div>`
* - beforeEnd: `<div>Contents<HERE></div>`
* - afterEnd: `<div>Contents</div><HERE>`
*
* @param {HTMLElement/TextNode} el The context element
* @param {String} html The HTML fragment
* @return {HTMLElement} The new node
*/
insertHtml: function(where, el, html) {
var hash = {},
setStart,
range,
frag,
rangeEl;
where = where.toLowerCase();
// add these here because they are used in both branches of the condition.
hash['beforebegin'] = ['BeforeBegin', 'previousSibling'];
hash['afterend'] = ['AfterEnd', 'nextSibling'];
range = el.ownerDocument.createRange();
setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before');
if (hash[where]) {
range[setStart](el);
frag = range.createContextualFragment(html);
el.parentNode.insertBefore(frag, where == 'beforebegin' ? el : el.nextSibling);
return el[(where == 'beforebegin' ? 'previous' : 'next') + 'Sibling'];
}
else {
rangeEl = (where == 'afterbegin' ? 'first' : 'last') + 'Child';
if (el.firstChild) {
range[setStart](el[rangeEl]);
frag = range.createContextualFragment(html);
if (where == 'afterbegin') {
el.insertBefore(frag, el.firstChild);
}
else {
el.appendChild(frag);
}
}
else {
el.innerHTML = html;
}
return el[rangeEl];
}
throw 'Illegal insertion point -> "' + where + '"';
},
/**
* Creates new DOM element(s) and inserts them before el.
* @param {String/HTMLElement/Ext.Element} el The context element
* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
* @param {Boolean} [returnElement] true to return a Ext.Element
* @return {HTMLElement/Ext.Element} The new node
*/
insertBefore: function(el, o, returnElement) {
return this.doInsert(el, o, returnElement, 'beforebegin');
},
/**
* Creates new DOM element(s) and inserts them after el.
* @param {String/HTMLElement/Ext.Element} el The context element
* @param {Object} o The DOM object spec (and children)
* @param {Boolean} [returnElement] true to return a Ext.Element
* @return {HTMLElement/Ext.Element} The new node
*/
insertAfter: function(el, o, returnElement) {
return this.doInsert(el, o, returnElement, 'afterend', 'nextSibling');
},
/**
* Creates new DOM element(s) and inserts them as the first child of el.
* @param {String/HTMLElement/Ext.Element} el The context element
* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
* @param {Boolean} [returnElement] true to return a Ext.Element
* @return {HTMLElement/Ext.Element} The new node
*/
insertFirst: function(el, o, returnElement) {
return this.doInsert(el, o, returnElement, 'afterbegin', 'firstChild');
},
/**
* Creates new DOM element(s) and appends them to el.
* @param {String/HTMLElement/Ext.Element} el The context element
* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
* @param {Boolean} [returnElement] true to return a Ext.Element
* @return {HTMLElement/Ext.Element} The new node
*/
append: function(el, o, returnElement) {
return this.doInsert(el, o, returnElement, 'beforeend', '', true);
},
/**
* Creates new DOM element(s) and overwrites the contents of el with them.
* @param {String/HTMLElement/Ext.Element} el The context element
* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
* @param {Boolean} [returnElement] true to return a Ext.Element
* @return {HTMLElement/Ext.Element} The new node
*/
overwrite: function(el, o, returnElement) {
el = Ext.getDom(el);
el.innerHTML = this.markup(o);
return returnElement ? Ext.get(el.firstChild) : el.firstChild;
},
doInsert: function(el, o, returnElement, pos, sibling, append) {
var newNode = this.insertHtml(pos, Ext.getDom(el), this.markup(o));
return returnElement ? Ext.get(newNode, true) : newNode;
}
});
|
filippov70/map.org
|
www/jslib/extjs/src/dom/AbstractHelper.js
|
JavaScript
|
lgpl-3.0
| 11,000 |
define(
"dojo/cldr/nls/hu/hebrew", //begin v1.x content
{
"months-format-abbr": [
"Tisri",
"Hesvรกn",
"Kiszlรฉv",
"Tรฉvรฉsz",
"Svรกt",
"รdรกr I",
"รdรกr",
"Niszรกn",
"Ijรกr",
"Szivรกn",
"Tamuz",
"รv",
"Elul"
],
"months-format-abbr-leap": "รdรกr II",
"months-format-wide": [
"Tisri",
"Hesvรกn",
"Kiszlรฉv",
"Tรฉvรฉsz",
"Svรกt",
"รdรกr risรณn",
"รdรกr",
"Niszรกn",
"Ijรกr",
"Szivรกn",
"Tamuz",
"รv",
"Elul"
],
"months-format-wide-leap": "รdรกr sรฉni",
"months-standAlone-abbr": [
"Tisri",
"Hesvรกn",
"Kiszlรฉv",
"Tรฉvรฉsz",
"Svรกt",
"รdรกr risรณn",
"รdรกr",
"Niszรกn",
"Ijรกr",
"Szivรกn",
"Tamuz",
"รv",
"Elul"
],
"months-standAlone-abbr-leap": "รdรกr II",
"months-standAlone-wide": [
"Tisri",
"Hesvรกn",
"Kiszlรฉv",
"Tรฉvรฉsz",
"Svรกt",
"รdรกr risรณn",
"รdรกr",
"Niszรกn",
"Ijรกr",
"Szivรกn",
"Tamuz",
"รv",
"Elul"
],
"months-standAlone-wide-leap": "รdรกr II",
"eraAbbr": [
"Tร"
],
"eraNames": [
"Tร"
],
"eraNarrow": [
"Tร"
],
"days-format-abbr": [
"V",
"H",
"K",
"Sze",
"Cs",
"P",
"Szo"
],
"days-format-narrow": [
"V",
"H",
"K",
"Sz",
"Cs",
"P",
"Sz"
],
"days-format-wide": [
"vasรกrnap",
"hรฉtfล",
"kedd",
"szerda",
"csรผtรถrtรถk",
"pรฉntek",
"szombat"
],
"days-standAlone-abbr": [
"V",
"H",
"K",
"Sze",
"Cs",
"P",
"Szo"
],
"days-standAlone-narrow": [
"V",
"H",
"K",
"Sz",
"Cs",
"P",
"Sz"
],
"days-standAlone-wide": [
"vasรกrnap",
"hรฉtfล",
"kedd",
"szerda",
"csรผtรถrtรถk",
"pรฉntek",
"szombat"
],
"quarters-format-abbr": [
"N1",
"N2",
"N3",
"N4"
],
"quarters-format-wide": [
"I. negyedรฉv",
"II. negyedรฉv",
"III. negyedรฉv",
"IV. negyedรฉv"
],
"quarters-standAlone-abbr": [
"N1",
"N2",
"N3",
"N4"
],
"quarters-standAlone-wide": [
"1. negyedรฉv",
"2. negyedรฉv",
"3. negyedรฉv",
"4. negyedรฉv"
],
"dayPeriods-format-narrow-am": "de.",
"dayPeriods-format-narrow-pm": "du.",
"dayPeriods-format-wide-am": "de.",
"dayPeriods-format-wide-pm": "du.",
"dateFormat-full": "y. MMMM d., EEEE",
"dateFormat-long": "y. MMMM d.",
"dateFormat-medium": "yyyy.MM.dd.",
"dateFormat-short": "yyyy.MM.dd.",
"dateFormatItem-Ed": "d., E",
"dateFormatItem-h": "a h",
"dateFormatItem-H": "H",
"dateFormatItem-hm": "a h:mm",
"dateFormatItem-Hm": "H:mm",
"dateFormatItem-hms": "a h:mm:ss",
"dateFormatItem-Hms": "H:mm:ss",
"dateFormatItem-Md": "M. d.",
"dateFormatItem-MEd": "M. d., E",
"dateFormatItem-MMMd": "MMM d.",
"dateFormatItem-MMMEd": "MMM d., E",
"dateFormatItem-yM": "y.M.",
"dateFormatItem-yMd": "yyyy.MM.dd.",
"dateFormatItem-yMEd": "yyyy.MM.dd., E",
"dateFormatItem-yMMM": "y. MMM",
"dateFormatItem-yMMMd": "y. MMM d.",
"dateFormatItem-yMMMEd": "y. MMM d., E",
"dateFormatItem-yQQQ": "y. QQQ",
"timeFormat-full": "H:mm:ss zzzz",
"timeFormat-long": "H:mm:ss z",
"timeFormat-medium": "H:mm:ss",
"timeFormat-short": "H:mm"
}
//end v1.x content
);
|
niug/DirClia
|
web/dojo/dojo/cldr/nls/hu/hebrew.js.uncompressed.js
|
JavaScript
|
mit
| 3,050 |
/**
* @license AngularJS v1.5.9
* (c) 2010-2016 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular) {'use strict';
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $sanitizeMinErr = angular.$$minErr('$sanitize');
var bind;
var extend;
var forEach;
var isDefined;
var lowercase;
var noop;
var htmlParser;
var htmlSanitizeWriter;
/**
* @ngdoc module
* @name ngSanitize
* @description
*
* # ngSanitize
*
* The `ngSanitize` module provides functionality to sanitize HTML.
*
*
* <div doc-module-components="ngSanitize"></div>
*
* See {@link ngSanitize.$sanitize `$sanitize`} for usage.
*/
/**
* @ngdoc service
* @name $sanitize
* @kind function
*
* @description
* Sanitizes an html string by stripping all potentially dangerous tokens.
*
* The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
* then serialized back to properly escaped html string. This means that no unsafe input can make
* it into the returned string.
*
* The whitelist for URL sanitization of attribute values is configured using the functions
* `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider
* `$compileProvider`}.
*
* The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}.
*
* @param {string} html HTML input.
* @returns {string} Sanitized HTML.
*
* @example
<example module="sanitizeExample" deps="angular-sanitize.js" name="sanitize-service">
<file name="index.html">
<script>
angular.module('sanitizeExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
$scope.snippet =
'<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>';
$scope.deliberatelyTrustDangerousSnippet = function() {
return $sce.trustAsHtml($scope.snippet);
};
}]);
</script>
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Directive</td>
<td>How</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="bind-html-with-sanitize">
<td>ng-bind-html</td>
<td>Automatically uses $sanitize</td>
<td><pre><div ng-bind-html="snippet"><br/></div></pre></td>
<td><div ng-bind-html="snippet"></div></td>
</tr>
<tr id="bind-html-with-trust">
<td>ng-bind-html</td>
<td>Bypass $sanitize by explicitly trusting the dangerous value</td>
<td>
<pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()">
</div></pre>
</td>
<td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
</tr>
<tr id="bind-default">
<td>ng-bind</td>
<td>Automatically escapes</td>
<td><pre><div ng-bind="snippet"><br/></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should sanitize the html snippet by default', function() {
expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')).
toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
});
it('should inline raw snippet if bound to a trusted value', function() {
expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should escape snippet without any filter', function() {
expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')).
toBe('new <b>text</b>');
expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).toBe(
'new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).toBe(
"new <b onclick=\"alert(1)\">text</b>");
});
</file>
</example>
*/
/**
* @ngdoc provider
* @name $sanitizeProvider
* @this
*
* @description
* Creates and configures {@link $sanitize} instance.
*/
function $SanitizeProvider() {
var svgEnabled = false;
this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
if (svgEnabled) {
extend(validElements, svgElements);
}
return function(html) {
var buf = [];
htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
return !/^unsafe:/.test($$sanitizeUri(uri, isImage));
}));
return buf.join('');
};
}];
/**
* @ngdoc method
* @name $sanitizeProvider#enableSvg
* @kind function
*
* @description
* Enables a subset of svg to be supported by the sanitizer.
*
* <div class="alert alert-warning">
* <p>By enabling this setting without taking other precautions, you might expose your
* application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned
* outside of the containing element and be rendered over other elements on the page (e.g. a login
* link). Such behavior can then result in phishing incidents.</p>
*
* <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg
* tags within the sanitized content:</p>
*
* <br>
*
* <pre><code>
* .rootOfTheIncludedContent svg {
* overflow: hidden !important;
* }
* </code></pre>
* </div>
*
* @param {boolean=} flag Enable or disable SVG support in the sanitizer.
* @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called
* without an argument or self for chaining otherwise.
*/
this.enableSvg = function(enableSvg) {
if (isDefined(enableSvg)) {
svgEnabled = enableSvg;
return this;
} else {
return svgEnabled;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////
// Private stuff
//////////////////////////////////////////////////////////////////////////////////////////////////
bind = angular.bind;
extend = angular.extend;
forEach = angular.forEach;
isDefined = angular.isDefined;
lowercase = angular.lowercase;
noop = angular.noop;
htmlParser = htmlParserImpl;
htmlSanitizeWriter = htmlSanitizeWriterImpl;
// Regular Expressions for parsing tags and attributes
var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
// Match everything outside of normal chars and " (quote character)
NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g;
// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
var voidElements = toMap('area,br,col,hr,img,wbr');
// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'),
optionalEndTagInlineElements = toMap('rp,rt'),
optionalEndTagElements = extend({},
optionalEndTagInlineElements,
optionalEndTagBlockElements);
// Safe Block Elements - HTML5
var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' +
'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul'));
// Inline Elements - HTML5
var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' +
'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' +
'samp,small,span,strike,strong,sub,sup,time,tt,u,var'));
// SVG Elements
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
// Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.
// They can potentially allow for arbitrary javascript to be executed. See #11290
var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' +
'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' +
'radialGradient,rect,stop,svg,switch,text,title,tspan');
// Blocked Elements (will be stripped)
var blockedElements = toMap('script,style');
var validElements = extend({},
voidElements,
blockElements,
inlineElements,
optionalEndTagElements);
//Attributes that have href and hence need to be sanitized
var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href');
var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +
'valign,value,vspace,width');
// SVG attributes (without "id" and "name" attributes)
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +
'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +
'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +
'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +
'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +
'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +
'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +
'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +
'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +
'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +
'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +
'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +
'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +
'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);
var validAttrs = extend({},
uriAttrs,
svgAttrs,
htmlAttrs);
function toMap(str, lowercaseKeys) {
var obj = {}, items = str.split(','), i;
for (i = 0; i < items.length; i++) {
obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true;
}
return obj;
}
var inertBodyElement;
(function(window) {
var doc;
if (window.document && window.document.implementation) {
doc = window.document.implementation.createHTMLDocument('inert');
} else {
throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document');
}
var docElement = doc.documentElement || doc.getDocumentElement();
var bodyElements = docElement.getElementsByTagName('body');
// usually there should be only one body element in the document, but IE doesn't have any, so we need to create one
if (bodyElements.length === 1) {
inertBodyElement = bodyElements[0];
} else {
var html = doc.createElement('html');
inertBodyElement = doc.createElement('body');
html.appendChild(inertBodyElement);
doc.appendChild(html);
}
})(window);
/**
* @example
* htmlParser(htmlString, {
* start: function(tag, attrs) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* @param {string} html string
* @param {object} handler
*/
function htmlParserImpl(html, handler) {
if (html === null || html === undefined) {
html = '';
} else if (typeof html !== 'string') {
html = '' + html;
}
inertBodyElement.innerHTML = html;
//mXSS protection
var mXSSAttempts = 5;
do {
if (mXSSAttempts === 0) {
throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable');
}
mXSSAttempts--;
// strip custom-namespaced attributes on IE<=11
if (window.document.documentMode) {
stripCustomNsAttrs(inertBodyElement);
}
html = inertBodyElement.innerHTML; //trigger mXSS
inertBodyElement.innerHTML = html;
} while (html !== inertBodyElement.innerHTML);
var node = inertBodyElement.firstChild;
while (node) {
switch (node.nodeType) {
case 1: // ELEMENT_NODE
handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes));
break;
case 3: // TEXT NODE
handler.chars(node.textContent);
break;
}
var nextNode;
if (!(nextNode = node.firstChild)) {
if (node.nodeType === 1) {
handler.end(node.nodeName.toLowerCase());
}
nextNode = node.nextSibling;
if (!nextNode) {
while (nextNode == null) {
node = node.parentNode;
if (node === inertBodyElement) break;
nextNode = node.nextSibling;
if (node.nodeType === 1) {
handler.end(node.nodeName.toLowerCase());
}
}
}
}
node = nextNode;
}
while ((node = inertBodyElement.firstChild)) {
inertBodyElement.removeChild(node);
}
}
function attrToMap(attrs) {
var map = {};
for (var i = 0, ii = attrs.length; i < ii; i++) {
var attr = attrs[i];
map[attr.name] = attr.value;
}
return map;
}
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns {string} escaped text
*/
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(SURROGATE_PAIR_REGEXP, function(value) {
var hi = value.charCodeAt(0);
var low = value.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}).
replace(NON_ALPHANUMERIC_REGEXP, function(value) {
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
}
/**
* create an HTML/XML writer which writes to buffer
* @param {Array} buf use buf.join('') to get out sanitized html string
* @returns {object} in the form of {
* start: function(tag, attrs) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* }
*/
function htmlSanitizeWriterImpl(buf, uriValidator) {
var ignoreCurrentElement = false;
var out = bind(buf, buf.push);
return {
start: function(tag, attrs) {
tag = lowercase(tag);
if (!ignoreCurrentElement && blockedElements[tag]) {
ignoreCurrentElement = tag;
}
if (!ignoreCurrentElement && validElements[tag] === true) {
out('<');
out(tag);
forEach(attrs, function(value, key) {
var lkey = lowercase(key);
var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
if (validAttrs[lkey] === true &&
(uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
out(' ');
out(key);
out('="');
out(encodeEntities(value));
out('"');
}
});
out('>');
}
},
end: function(tag) {
tag = lowercase(tag);
if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) {
out('</');
out(tag);
out('>');
}
// eslint-disable-next-line eqeqeq
if (tag == ignoreCurrentElement) {
ignoreCurrentElement = false;
}
},
chars: function(chars) {
if (!ignoreCurrentElement) {
out(encodeEntities(chars));
}
}
};
}
/**
* When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare
* ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want
* to allow any of these custom attributes. This method strips them all.
*
* @param node Root element to process
*/
function stripCustomNsAttrs(node) {
if (node.nodeType === window.Node.ELEMENT_NODE) {
var attrs = node.attributes;
for (var i = 0, l = attrs.length; i < l; i++) {
var attrNode = attrs[i];
var attrName = attrNode.name.toLowerCase();
if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) {
node.removeAttributeNode(attrNode);
i--;
l--;
}
}
}
var nextNode = node.firstChild;
if (nextNode) {
stripCustomNsAttrs(nextNode);
}
nextNode = node.nextSibling;
if (nextNode) {
stripCustomNsAttrs(nextNode);
}
}
}
function sanitizeText(chars) {
var buf = [];
var writer = htmlSanitizeWriter(buf, noop);
writer.chars(chars);
return buf.join('');
}
// define ngSanitize module and register $sanitize service
angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
/**
* @ngdoc filter
* @name linky
* @kind function
*
* @description
* Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and
* plain email address links.
*
* Requires the {@link ngSanitize `ngSanitize`} module to be installed.
*
* @param {string} text Input text.
* @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in.
* @param {object|function(url)} [attributes] Add custom attributes to the link element.
*
* Can be one of:
*
* - `object`: A map of attributes
* - `function`: Takes the url as a parameter and returns a map of attributes
*
* If the map of attributes contains a value for `target`, it overrides the value of
* the target parameter.
*
*
* @returns {string} Html-linkified and {@link $sanitize sanitized} text.
*
* @usage
<span ng-bind-html="linky_expression | linky"></span>
*
* @example
<example module="linkyExample" deps="angular-sanitize.js" name="linky-filter">
<file name="index.html">
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<th>Filter</th>
<th>Source</th>
<th>Rendered</th>
</tr>
<tr id="linky-filter">
<td>linky filter</td>
<td>
<pre><div ng-bind-html="snippet | linky"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippet | linky"></div>
</td>
</tr>
<tr id="linky-target">
<td>linky target</td>
<td>
<pre><div ng-bind-html="snippetWithSingleURL | linky:'_blank'"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div>
</td>
</tr>
<tr id="linky-custom-attributes">
<td>linky custom attributes</td>
<td>
<pre><div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</file>
<file name="script.js">
angular.module('linkyExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.snippet =
'Pretty text with some links:\n' +
'http://angularjs.org/,\n' +
'mailto:us@somewhere.org,\n' +
'another@somewhere.org,\n' +
'and one more: ftp://127.0.0.1/.';
$scope.snippetWithSingleURL = 'http://angularjs.org/';
}]);
</file>
<file name="protractor.js" type="protractor">
it('should linkify the snippet with urls', function() {
expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
'another@somewhere.org, and one more: ftp://127.0.0.1/.');
expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
});
it('should not linkify snippet without the linky filter', function() {
expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
'another@somewhere.org, and one more: ftp://127.0.0.1/.');
expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new http://link.');
expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
toBe('new http://link.');
expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
.toBe('new http://link.');
});
it('should work with the target property', function() {
expect(element(by.id('linky-target')).
element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()).
toBe('http://angularjs.org/');
expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
});
it('should optionally add custom attributes', function() {
expect(element(by.id('linky-custom-attributes')).
element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()).
toBe('http://angularjs.org/');
expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow');
});
</file>
</example>
*/
angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
var LINKY_URL_REGEXP =
/((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
MAILTO_REGEXP = /^mailto:/i;
var linkyMinErr = angular.$$minErr('linky');
var isDefined = angular.isDefined;
var isFunction = angular.isFunction;
var isObject = angular.isObject;
var isString = angular.isString;
return function(text, target, attributes) {
if (text == null || text === '') return text;
if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text);
var attributesFn =
isFunction(attributes) ? attributes :
isObject(attributes) ? function getAttributesObject() {return attributes;} :
function getEmptyAttributesObject() {return {};};
var match;
var raw = text;
var html = [];
var url;
var i;
while ((match = raw.match(LINKY_URL_REGEXP))) {
// We can not end in these as they are sometimes found at the end of the sentence
url = match[0];
// if we did not match ftp/http/www/mailto then assume mailto
if (!match[2] && !match[4]) {
url = (match[3] ? 'http://' : 'mailto:') + url;
}
i = match.index;
addText(raw.substr(0, i));
addLink(url, match[0].replace(MAILTO_REGEXP, ''));
raw = raw.substring(i + match[0].length);
}
addText(raw);
return $sanitize(html.join(''));
function addText(text) {
if (!text) {
return;
}
html.push(sanitizeText(text));
}
function addLink(url, text) {
var key, linkAttributes = attributesFn(url);
html.push('<a ');
for (key in linkAttributes) {
html.push(key + '="' + linkAttributes[key] + '" ');
}
if (isDefined(target) && !('target' in linkAttributes)) {
html.push('target="',
target,
'" ');
}
html.push('href="',
url.replace(/"/g, '"'),
'">');
addText(text);
html.push('</a>');
}
};
}]);
})(window, window.angular);
|
ohmygodvt95/wevivu
|
vendor/assets/components/angular-sanitize/angular-sanitize.js
|
JavaScript
|
mit
| 27,003 |
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.initConfig({
jshint: {
options: { jshintrc: true },
all: ['*.js', 'lib/*.js', 'test/*.js']
}
});
grunt.registerTask('default', ['jshint']);
};
|
victzero/wanzi
|
wanzi/node_modules/connect-mongo/Gruntfile.js
|
JavaScript
|
gpl-2.0
| 289 |
๏ปฟ/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("widget","no",{move:"Klikk og dra for รฅ flytte",label:"%1 widget"});
|
samnemo94/SchoolSystem
|
vendor/ckeditor/ckeditor/plugins/widget/lang/no.js
|
JavaScript
|
bsd-3-clause
| 242 |
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: 1.0.4
* Revision: 1120
*
* Copyright (c) 2009-2012 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*/
(function($) {
/**
* Class: $.jqplot.Cursor
* Plugin class representing the cursor as displayed on the plot.
*/
$.jqplot.Cursor = function(options) {
// Group: Properties
//
// prop: style
// CSS spec for cursor style
this.style = 'crosshair';
this.previousCursor = 'auto';
// prop: show
// wether to show the cursor or not.
this.show = $.jqplot.config.enablePlugins;
// prop: showTooltip
// show a cursor position tooltip. Location of the tooltip
// will be controlled by followMouse and tooltipLocation.
this.showTooltip = true;
// prop: followMouse
// Tooltip follows the mouse, it is not at a fixed location.
// Tooltip will show on the grid at the location given by
// tooltipLocation, offset from the grid edge by tooltipOffset.
this.followMouse = false;
// prop: tooltipLocation
// Where to position tooltip. If followMouse is true, this is
// relative to the cursor, otherwise, it is relative to the grid.
// One of 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'
this.tooltipLocation = 'se';
// prop: tooltipOffset
// Pixel offset of tooltip from the grid boudaries or cursor center.
this.tooltipOffset = 6;
// prop: showTooltipGridPosition
// show the grid pixel coordinates of the mouse.
this.showTooltipGridPosition = false;
// prop: showTooltipUnitPosition
// show the unit (data) coordinates of the mouse.
this.showTooltipUnitPosition = true;
// prop: showTooltipDataPosition
// Used with showVerticalLine to show intersecting data points in the tooltip.
this.showTooltipDataPosition = false;
// prop: tooltipFormatString
// sprintf format string for the tooltip.
// Uses Ash Searle's javascript sprintf implementation
// found here: http://hexmen.com/blog/2007/03/printf-sprintf/
// See http://perldoc.perl.org/functions/sprintf.html for reference
// Note, if showTooltipDataPosition is true, the default tooltipFormatString
// will be set to the cursorLegendFormatString, not the default given here.
this.tooltipFormatString = '%.4P, %.4P';
// prop: useAxesFormatters
// Use the x and y axes formatters to format the text in the tooltip.
this.useAxesFormatters = true;
// prop: tooltipAxisGroups
// Show position for the specified axes.
// This is an array like [['xaxis', 'yaxis'], ['xaxis', 'y2axis']]
// Default is to compute automatically for all visible axes.
this.tooltipAxisGroups = [];
// prop: zoom
// Enable plot zooming.
this.zoom = false;
// zoomProxy and zoomTarget properties are not directly set by user.
// They Will be set through call to zoomProxy method.
this.zoomProxy = false;
this.zoomTarget = false;
// prop: looseZoom
// Will expand zoom range to provide more rounded tick values.
// Works only with linear, log and date axes.
this.looseZoom = true;
// prop: clickReset
// Will reset plot zoom if single click on plot without drag.
this.clickReset = false;
// prop: dblClickReset
// Will reset plot zoom if double click on plot without drag.
this.dblClickReset = true;
// prop: showVerticalLine
// draw a vertical line across the plot which follows the cursor.
// When the line is near a data point, a special legend and/or tooltip can
// be updated with the data values.
this.showVerticalLine = false;
// prop: showHorizontalLine
// draw a horizontal line across the plot which follows the cursor.
this.showHorizontalLine = false;
// prop: constrainZoomTo
// 'none', 'x' or 'y'
this.constrainZoomTo = 'none';
// // prop: autoscaleConstraint
// // when a constrained axis is specified, true will
// // auatoscale the adjacent axis.
// this.autoscaleConstraint = true;
this.shapeRenderer = new $.jqplot.ShapeRenderer();
this._zoom = {start:[], end:[], started: false, zooming:false, isZoomed:false, axes:{start:{}, end:{}}, gridpos:{}, datapos:{}};
this._tooltipElem;
this.zoomCanvas;
this.cursorCanvas;
// prop: intersectionThreshold
// pixel distance from data point or marker to consider cursor lines intersecting with point.
// If data point markers are not shown, this should be >= 1 or will often miss point intersections.
this.intersectionThreshold = 2;
// prop: showCursorLegend
// Replace the plot legend with an enhanced legend displaying intersection information.
this.showCursorLegend = false;
// prop: cursorLegendFormatString
// Format string used in the cursor legend. If showTooltipDataPosition is true,
// this will also be the default format string used by tooltipFormatString.
this.cursorLegendFormatString = $.jqplot.Cursor.cursorLegendFormatString;
// whether the cursor is over the grid or not.
this._oldHandlers = {onselectstart: null, ondrag: null, onmousedown: null};
// prop: constrainOutsideZoom
// True to limit actual zoom area to edges of grid, even when zooming
// outside of plot area. That is, can't zoom out by mousing outside plot.
this.constrainOutsideZoom = true;
// prop: showTooltipOutsideZoom
// True will keep updating the tooltip when zooming of the grid.
this.showTooltipOutsideZoom = false;
// true if mouse is over grid, false if not.
this.onGrid = false;
$.extend(true, this, options);
};
$.jqplot.Cursor.cursorLegendFormatString = '%s x:%s, y:%s';
// called with scope of plot
$.jqplot.Cursor.init = function (target, data, opts){
// add a cursor attribute to the plot
var options = opts || {};
this.plugins.cursor = new $.jqplot.Cursor(options.cursor);
var c = this.plugins.cursor;
if (c.show) {
$.jqplot.eventListenerHooks.push(['jqplotMouseEnter', handleMouseEnter]);
$.jqplot.eventListenerHooks.push(['jqplotMouseLeave', handleMouseLeave]);
$.jqplot.eventListenerHooks.push(['jqplotMouseMove', handleMouseMove]);
if (c.showCursorLegend) {
opts.legend = opts.legend || {};
opts.legend.renderer = $.jqplot.CursorLegendRenderer;
opts.legend.formatString = this.plugins.cursor.cursorLegendFormatString;
opts.legend.show = true;
}
if (c.zoom) {
$.jqplot.eventListenerHooks.push(['jqplotMouseDown', handleMouseDown]);
if (c.clickReset) {
$.jqplot.eventListenerHooks.push(['jqplotClick', handleClick]);
}
if (c.dblClickReset) {
$.jqplot.eventListenerHooks.push(['jqplotDblClick', handleDblClick]);
}
}
this.resetZoom = function() {
var axes = this.axes;
if (!c.zoomProxy) {
for (var ax in axes) {
axes[ax].reset();
axes[ax]._ticks = [];
// fake out tick creation algorithm to make sure original auto
// computed format string is used if _overrideFormatString is true
if (c._zoom.axes[ax] !== undefined) {
axes[ax]._autoFormatString = c._zoom.axes[ax].tickFormatString;
}
}
this.redraw();
}
else {
var ctx = this.plugins.cursor.zoomCanvas._ctx;
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
ctx = null;
}
this.plugins.cursor._zoom.isZoomed = false;
this.target.trigger('jqplotResetZoom', [this, this.plugins.cursor]);
};
if (c.showTooltipDataPosition) {
c.showTooltipUnitPosition = false;
c.showTooltipGridPosition = false;
if (options.cursor.tooltipFormatString == undefined) {
c.tooltipFormatString = $.jqplot.Cursor.cursorLegendFormatString;
}
}
}
};
// called with context of plot
$.jqplot.Cursor.postDraw = function() {
var c = this.plugins.cursor;
// Memory Leaks patch
if (c.zoomCanvas) {
c.zoomCanvas.resetCanvas();
c.zoomCanvas = null;
}
if (c.cursorCanvas) {
c.cursorCanvas.resetCanvas();
c.cursorCanvas = null;
}
if (c._tooltipElem) {
c._tooltipElem.emptyForce();
c._tooltipElem = null;
}
if (c.zoom) {
c.zoomCanvas = new $.jqplot.GenericCanvas();
this.eventCanvas._elem.before(c.zoomCanvas.createElement(this._gridPadding, 'jqplot-zoom-canvas', this._plotDimensions, this));
c.zoomCanvas.setContext();
}
var elem = document.createElement('div');
c._tooltipElem = $(elem);
elem = null;
c._tooltipElem.addClass('jqplot-cursor-tooltip');
c._tooltipElem.css({position:'absolute', display:'none'});
if (c.zoomCanvas) {
c.zoomCanvas._elem.before(c._tooltipElem);
}
else {
this.eventCanvas._elem.before(c._tooltipElem);
}
if (c.showVerticalLine || c.showHorizontalLine) {
c.cursorCanvas = new $.jqplot.GenericCanvas();
this.eventCanvas._elem.before(c.cursorCanvas.createElement(this._gridPadding, 'jqplot-cursor-canvas', this._plotDimensions, this));
c.cursorCanvas.setContext();
}
// if we are showing the positions in unit coordinates, and no axes groups
// were specified, create a default set.
if (c.showTooltipUnitPosition){
if (c.tooltipAxisGroups.length === 0) {
var series = this.series;
var s;
var temp = [];
for (var i=0; i<series.length; i++) {
s = series[i];
var ax = s.xaxis+','+s.yaxis;
if ($.inArray(ax, temp) == -1) {
temp.push(ax);
}
}
for (var i=0; i<temp.length; i++) {
c.tooltipAxisGroups.push(temp[i].split(','));
}
}
}
};
// Group: methods
//
// method: $.jqplot.Cursor.zoomProxy
// links targetPlot to controllerPlot so that plot zooming of
// targetPlot will be controlled by zooming on the controllerPlot.
// controllerPlot will not actually zoom, but acts as an
// overview plot. Note, the zoom options must be set to true for
// zoomProxy to work.
$.jqplot.Cursor.zoomProxy = function(targetPlot, controllerPlot) {
var tc = targetPlot.plugins.cursor;
var cc = controllerPlot.plugins.cursor;
tc.zoomTarget = true;
tc.zoom = true;
tc.style = 'auto';
tc.dblClickReset = false;
cc.zoom = true;
cc.zoomProxy = true;
controllerPlot.target.bind('jqplotZoom', plotZoom);
controllerPlot.target.bind('jqplotResetZoom', plotReset);
function plotZoom(ev, gridpos, datapos, plot, cursor) {
tc.doZoom(gridpos, datapos, targetPlot, cursor);
}
function plotReset(ev, plot, cursor) {
targetPlot.resetZoom();
}
};
$.jqplot.Cursor.prototype.resetZoom = function(plot, cursor) {
var axes = plot.axes;
var cax = cursor._zoom.axes;
if (!plot.plugins.cursor.zoomProxy && cursor._zoom.isZoomed) {
for (var ax in axes) {
// axes[ax]._ticks = [];
// axes[ax].min = cax[ax].min;
// axes[ax].max = cax[ax].max;
// axes[ax].numberTicks = cax[ax].numberTicks;
// axes[ax].tickInterval = cax[ax].tickInterval;
// // for date axes
// axes[ax].daTickInterval = cax[ax].daTickInterval;
axes[ax].reset();
axes[ax]._ticks = [];
// fake out tick creation algorithm to make sure original auto
// computed format string is used if _overrideFormatString is true
axes[ax]._autoFormatString = cax[ax].tickFormatString;
}
plot.redraw();
cursor._zoom.isZoomed = false;
}
else {
var ctx = cursor.zoomCanvas._ctx;
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
ctx = null;
}
plot.target.trigger('jqplotResetZoom', [plot, cursor]);
};
$.jqplot.Cursor.resetZoom = function(plot) {
plot.resetZoom();
};
$.jqplot.Cursor.prototype.doZoom = function (gridpos, datapos, plot, cursor) {
var c = cursor;
var axes = plot.axes;
var zaxes = c._zoom.axes;
var start = zaxes.start;
var end = zaxes.end;
var min, max, dp, span,
newmin, newmax, curax, _numberTicks, ret;
var ctx = plot.plugins.cursor.zoomCanvas._ctx;
// don't zoom if zoom area is too small (in pixels)
if ((c.constrainZoomTo == 'none' && Math.abs(gridpos.x - c._zoom.start[0]) > 6 && Math.abs(gridpos.y - c._zoom.start[1]) > 6) || (c.constrainZoomTo == 'x' && Math.abs(gridpos.x - c._zoom.start[0]) > 6) || (c.constrainZoomTo == 'y' && Math.abs(gridpos.y - c._zoom.start[1]) > 6)) {
if (!plot.plugins.cursor.zoomProxy) {
for (var ax in datapos) {
// make a copy of the original axes to revert back.
if (c._zoom.axes[ax] == undefined) {
c._zoom.axes[ax] = {};
c._zoom.axes[ax].numberTicks = axes[ax].numberTicks;
c._zoom.axes[ax].tickInterval = axes[ax].tickInterval;
// for date axes...
c._zoom.axes[ax].daTickInterval = axes[ax].daTickInterval;
c._zoom.axes[ax].min = axes[ax].min;
c._zoom.axes[ax].max = axes[ax].max;
c._zoom.axes[ax].tickFormatString = (axes[ax].tickOptions != null) ? axes[ax].tickOptions.formatString : '';
}
if ((c.constrainZoomTo == 'none') || (c.constrainZoomTo == 'x' && ax.charAt(0) == 'x') || (c.constrainZoomTo == 'y' && ax.charAt(0) == 'y')) {
dp = datapos[ax];
if (dp != null) {
if (dp > start[ax]) {
newmin = start[ax];
newmax = dp;
}
else {
span = start[ax] - dp;
newmin = dp;
newmax = start[ax];
}
curax = axes[ax];
_numberTicks = null;
// if aligning this axis, use number of ticks from previous axis.
// Do I need to reset somehow if alignTicks is changed and then graph is replotted??
if (curax.alignTicks) {
if (curax.name === 'x2axis' && plot.axes.xaxis.show) {
_numberTicks = plot.axes.xaxis.numberTicks;
}
else if (curax.name.charAt(0) === 'y' && curax.name !== 'yaxis' && curax.name !== 'yMidAxis' && plot.axes.yaxis.show) {
_numberTicks = plot.axes.yaxis.numberTicks;
}
}
if (this.looseZoom && (axes[ax].renderer.constructor === $.jqplot.LinearAxisRenderer || axes[ax].renderer.constructor === $.jqplot.LogAxisRenderer )) { //} || axes[ax].renderer.constructor === $.jqplot.DateAxisRenderer)) {
ret = $.jqplot.LinearTickGenerator(newmin, newmax, curax._scalefact, _numberTicks);
// if new minimum is less than "true" minimum of axis display, adjust it
if (axes[ax].tickInset && ret[0] < axes[ax].min + axes[ax].tickInset * axes[ax].tickInterval) {
ret[0] += ret[4];
ret[2] -= 1;
}
// if new maximum is greater than "true" max of axis display, adjust it
if (axes[ax].tickInset && ret[1] > axes[ax].max - axes[ax].tickInset * axes[ax].tickInterval) {
ret[1] -= ret[4];
ret[2] -= 1;
}
// for log axes, don't fall below current minimum, this will look bad and can't have 0 in range anyway.
if (axes[ax].renderer.constructor === $.jqplot.LogAxisRenderer && ret[0] < axes[ax].min) {
// remove a tick and shift min up
ret[0] += ret[4];
ret[2] -= 1;
}
axes[ax].min = ret[0];
axes[ax].max = ret[1];
axes[ax]._autoFormatString = ret[3];
axes[ax].numberTicks = ret[2];
axes[ax].tickInterval = ret[4];
// for date axes...
axes[ax].daTickInterval = [ret[4]/1000, 'seconds'];
}
else {
axes[ax].min = newmin;
axes[ax].max = newmax;
axes[ax].tickInterval = null;
axes[ax].numberTicks = null;
// for date axes...
axes[ax].daTickInterval = null;
}
axes[ax]._ticks = [];
}
}
// if ((c.constrainZoomTo == 'x' && ax.charAt(0) == 'y' && c.autoscaleConstraint) || (c.constrainZoomTo == 'y' && ax.charAt(0) == 'x' && c.autoscaleConstraint)) {
// dp = datapos[ax];
// if (dp != null) {
// axes[ax].max == null;
// axes[ax].min = null;
// }
// }
}
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
plot.redraw();
c._zoom.isZoomed = true;
ctx = null;
}
plot.target.trigger('jqplotZoom', [gridpos, datapos, plot, cursor]);
}
};
$.jqplot.preInitHooks.push($.jqplot.Cursor.init);
$.jqplot.postDrawHooks.push($.jqplot.Cursor.postDraw);
function updateTooltip(gridpos, datapos, plot) {
var c = plot.plugins.cursor;
var s = '';
var addbr = false;
if (c.showTooltipGridPosition) {
s = gridpos.x+', '+gridpos.y;
addbr = true;
}
if (c.showTooltipUnitPosition) {
var g;
for (var i=0; i<c.tooltipAxisGroups.length; i++) {
g = c.tooltipAxisGroups[i];
if (addbr) {
s += '<br />';
}
if (c.useAxesFormatters) {
for (var j=0; j<g.length; j++) {
if (j) {
s += ', ';
}
var af = plot.axes[g[j]]._ticks[0].formatter;
var afstr = plot.axes[g[j]]._ticks[0].formatString;
s += af(afstr, datapos[g[j]]);
}
}
else {
s += $.jqplot.sprintf(c.tooltipFormatString, datapos[g[0]], datapos[g[1]]);
}
addbr = true;
}
}
if (c.showTooltipDataPosition) {
var series = plot.series;
var ret = getIntersectingPoints(plot, gridpos.x, gridpos.y);
var addbr = false;
for (var i = 0; i< series.length; i++) {
if (series[i].show) {
var idx = series[i].index;
var label = series[i].label.toString();
var cellid = $.inArray(idx, ret.indices);
var sx = undefined;
var sy = undefined;
if (cellid != -1) {
var data = ret.data[cellid].data;
if (c.useAxesFormatters) {
var xf = series[i]._xaxis._ticks[0].formatter;
var yf = series[i]._yaxis._ticks[0].formatter;
var xfstr = series[i]._xaxis._ticks[0].formatString;
var yfstr = series[i]._yaxis._ticks[0].formatString;
sx = xf(xfstr, data[0]);
sy = yf(yfstr, data[1]);
}
else {
sx = data[0];
sy = data[1];
}
if (addbr) {
s += '<br />';
}
s += $.jqplot.sprintf(c.tooltipFormatString, label, sx, sy);
addbr = true;
}
}
}
}
c._tooltipElem.html(s);
}
function moveLine(gridpos, plot) {
var c = plot.plugins.cursor;
var ctx = c.cursorCanvas._ctx;
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
if (c.showVerticalLine) {
c.shapeRenderer.draw(ctx, [[gridpos.x, 0], [gridpos.x, ctx.canvas.height]]);
}
if (c.showHorizontalLine) {
c.shapeRenderer.draw(ctx, [[0, gridpos.y], [ctx.canvas.width, gridpos.y]]);
}
var ret = getIntersectingPoints(plot, gridpos.x, gridpos.y);
if (c.showCursorLegend) {
var cells = $(plot.targetId + ' td.jqplot-cursor-legend-label');
for (var i=0; i<cells.length; i++) {
var idx = $(cells[i]).data('seriesIndex');
var series = plot.series[idx];
var label = series.label.toString();
var cellid = $.inArray(idx, ret.indices);
var sx = undefined;
var sy = undefined;
if (cellid != -1) {
var data = ret.data[cellid].data;
if (c.useAxesFormatters) {
var xf = series._xaxis._ticks[0].formatter;
var yf = series._yaxis._ticks[0].formatter;
var xfstr = series._xaxis._ticks[0].formatString;
var yfstr = series._yaxis._ticks[0].formatString;
sx = xf(xfstr, data[0]);
sy = yf(yfstr, data[1]);
}
else {
sx = data[0];
sy = data[1];
}
}
if (plot.legend.escapeHtml) {
$(cells[i]).text($.jqplot.sprintf(c.cursorLegendFormatString, label, sx, sy));
}
else {
$(cells[i]).html($.jqplot.sprintf(c.cursorLegendFormatString, label, sx, sy));
}
}
}
ctx = null;
}
function getIntersectingPoints(plot, x, y) {
var ret = {indices:[], data:[]};
var s, i, d0, d, j, r, p;
var threshold;
var c = plot.plugins.cursor;
for (var i=0; i<plot.series.length; i++) {
s = plot.series[i];
r = s.renderer;
if (s.show) {
threshold = c.intersectionThreshold;
if (s.showMarker) {
threshold += s.markerRenderer.size/2;
}
for (var j=0; j<s.gridData.length; j++) {
p = s.gridData[j];
// check vertical line
if (c.showVerticalLine) {
if (Math.abs(x-p[0]) <= threshold) {
ret.indices.push(i);
ret.data.push({seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]});
}
}
}
}
}
return ret;
}
function moveTooltip(gridpos, plot) {
var c = plot.plugins.cursor;
var elem = c._tooltipElem;
switch (c.tooltipLocation) {
case 'nw':
var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true) - c.tooltipOffset;
var y = gridpos.y + plot._gridPadding.top - c.tooltipOffset - elem.outerHeight(true);
break;
case 'n':
var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true)/2;
var y = gridpos.y + plot._gridPadding.top - c.tooltipOffset - elem.outerHeight(true);
break;
case 'ne':
var x = gridpos.x + plot._gridPadding.left + c.tooltipOffset;
var y = gridpos.y + plot._gridPadding.top - c.tooltipOffset - elem.outerHeight(true);
break;
case 'e':
var x = gridpos.x + plot._gridPadding.left + c.tooltipOffset;
var y = gridpos.y + plot._gridPadding.top - elem.outerHeight(true)/2;
break;
case 'se':
var x = gridpos.x + plot._gridPadding.left + c.tooltipOffset;
var y = gridpos.y + plot._gridPadding.top + c.tooltipOffset;
break;
case 's':
var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true)/2;
var y = gridpos.y + plot._gridPadding.top + c.tooltipOffset;
break;
case 'sw':
var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true) - c.tooltipOffset;
var y = gridpos.y + plot._gridPadding.top + c.tooltipOffset;
break;
case 'w':
var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true) - c.tooltipOffset;
var y = gridpos.y + plot._gridPadding.top - elem.outerHeight(true)/2;
break;
default:
var x = gridpos.x + plot._gridPadding.left + c.tooltipOffset;
var y = gridpos.y + plot._gridPadding.top + c.tooltipOffset;
break;
}
elem.css('left', x);
elem.css('top', y);
elem = null;
}
function positionTooltip(plot) {
// fake a grid for positioning
var grid = plot._gridPadding;
var c = plot.plugins.cursor;
var elem = c._tooltipElem;
switch (c.tooltipLocation) {
case 'nw':
var a = grid.left + c.tooltipOffset;
var b = grid.top + c.tooltipOffset;
elem.css('left', a);
elem.css('top', b);
break;
case 'n':
var a = (grid.left + (plot._plotDimensions.width - grid.right))/2 - elem.outerWidth(true)/2;
var b = grid.top + c.tooltipOffset;
elem.css('left', a);
elem.css('top', b);
break;
case 'ne':
var a = grid.right + c.tooltipOffset;
var b = grid.top + c.tooltipOffset;
elem.css({right:a, top:b});
break;
case 'e':
var a = grid.right + c.tooltipOffset;
var b = (grid.top + (plot._plotDimensions.height - grid.bottom))/2 - elem.outerHeight(true)/2;
elem.css({right:a, top:b});
break;
case 'se':
var a = grid.right + c.tooltipOffset;
var b = grid.bottom + c.tooltipOffset;
elem.css({right:a, bottom:b});
break;
case 's':
var a = (grid.left + (plot._plotDimensions.width - grid.right))/2 - elem.outerWidth(true)/2;
var b = grid.bottom + c.tooltipOffset;
elem.css({left:a, bottom:b});
break;
case 'sw':
var a = grid.left + c.tooltipOffset;
var b = grid.bottom + c.tooltipOffset;
elem.css({left:a, bottom:b});
break;
case 'w':
var a = grid.left + c.tooltipOffset;
var b = (grid.top + (plot._plotDimensions.height - grid.bottom))/2 - elem.outerHeight(true)/2;
elem.css({left:a, top:b});
break;
default: // same as 'se'
var a = grid.right - c.tooltipOffset;
var b = grid.bottom + c.tooltipOffset;
elem.css({right:a, bottom:b});
break;
}
elem = null;
}
function handleClick (ev, gridpos, datapos, neighbor, plot) {
ev.preventDefault();
ev.stopImmediatePropagation();
var c = plot.plugins.cursor;
if (c.clickReset) {
c.resetZoom(plot, c);
}
var sel = window.getSelection;
if (document.selection && document.selection.empty)
{
document.selection.empty();
}
else if (sel && !sel().isCollapsed) {
sel().collapse();
}
return false;
}
function handleDblClick (ev, gridpos, datapos, neighbor, plot) {
ev.preventDefault();
ev.stopImmediatePropagation();
var c = plot.plugins.cursor;
if (c.dblClickReset) {
c.resetZoom(plot, c);
}
var sel = window.getSelection;
if (document.selection && document.selection.empty)
{
document.selection.empty();
}
else if (sel && !sel().isCollapsed) {
sel().collapse();
}
return false;
}
function handleMouseLeave(ev, gridpos, datapos, neighbor, plot) {
var c = plot.plugins.cursor;
c.onGrid = false;
if (c.show) {
$(ev.target).css('cursor', c.previousCursor);
if (c.showTooltip && !(c._zoom.zooming && c.showTooltipOutsideZoom && !c.constrainOutsideZoom)) {
c._tooltipElem.empty();
c._tooltipElem.hide();
}
if (c.zoom) {
c._zoom.gridpos = gridpos;
c._zoom.datapos = datapos;
}
if (c.showVerticalLine || c.showHorizontalLine) {
var ctx = c.cursorCanvas._ctx;
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
ctx = null;
}
if (c.showCursorLegend) {
var cells = $(plot.targetId + ' td.jqplot-cursor-legend-label');
for (var i=0; i<cells.length; i++) {
var idx = $(cells[i]).data('seriesIndex');
var series = plot.series[idx];
var label = series.label.toString();
if (plot.legend.escapeHtml) {
$(cells[i]).text($.jqplot.sprintf(c.cursorLegendFormatString, label, undefined, undefined));
}
else {
$(cells[i]).html($.jqplot.sprintf(c.cursorLegendFormatString, label, undefined, undefined));
}
}
}
}
}
function handleMouseEnter(ev, gridpos, datapos, neighbor, plot) {
var c = plot.plugins.cursor;
c.onGrid = true;
if (c.show) {
c.previousCursor = ev.target.style.cursor;
ev.target.style.cursor = c.style;
if (c.showTooltip) {
updateTooltip(gridpos, datapos, plot);
if (c.followMouse) {
moveTooltip(gridpos, plot);
}
else {
positionTooltip(plot);
}
c._tooltipElem.show();
}
if (c.showVerticalLine || c.showHorizontalLine) {
moveLine(gridpos, plot);
}
}
}
function handleMouseMove(ev, gridpos, datapos, neighbor, plot) {
var c = plot.plugins.cursor;
if (c.show) {
if (c.showTooltip) {
updateTooltip(gridpos, datapos, plot);
if (c.followMouse) {
moveTooltip(gridpos, plot);
}
}
if (c.showVerticalLine || c.showHorizontalLine) {
moveLine(gridpos, plot);
}
}
}
function getEventPosition(ev) {
var plot = ev.data.plot;
var go = plot.eventCanvas._elem.offset();
var gridPos = {x:ev.pageX - go.left, y:ev.pageY - go.top};
//////
// TO DO: handle yMidAxis
//////
var dataPos = {xaxis:null, yaxis:null, x2axis:null, y2axis:null, y3axis:null, y4axis:null, y5axis:null, y6axis:null, y7axis:null, y8axis:null, y9axis:null, yMidAxis:null};
var an = ['xaxis', 'yaxis', 'x2axis', 'y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis', 'yMidAxis'];
var ax = plot.axes;
var n, axis;
for (n=11; n>0; n--) {
axis = an[n-1];
if (ax[axis].show) {
dataPos[axis] = ax[axis].series_p2u(gridPos[axis.charAt(0)]);
}
}
return {offsets:go, gridPos:gridPos, dataPos:dataPos};
}
function handleZoomMove(ev) {
var plot = ev.data.plot;
var c = plot.plugins.cursor;
// don't do anything if not on grid.
if (c.show && c.zoom && c._zoom.started && !c.zoomTarget) {
ev.preventDefault();
var ctx = c.zoomCanvas._ctx;
var positions = getEventPosition(ev);
var gridpos = positions.gridPos;
var datapos = positions.dataPos;
c._zoom.gridpos = gridpos;
c._zoom.datapos = datapos;
c._zoom.zooming = true;
var xpos = gridpos.x;
var ypos = gridpos.y;
var height = ctx.canvas.height;
var width = ctx.canvas.width;
if (c.showTooltip && !c.onGrid && c.showTooltipOutsideZoom) {
updateTooltip(gridpos, datapos, plot);
if (c.followMouse) {
moveTooltip(gridpos, plot);
}
}
if (c.constrainZoomTo == 'x') {
c._zoom.end = [xpos, height];
}
else if (c.constrainZoomTo == 'y') {
c._zoom.end = [width, ypos];
}
else {
c._zoom.end = [xpos, ypos];
}
var sel = window.getSelection;
if (document.selection && document.selection.empty)
{
document.selection.empty();
}
else if (sel && !sel().isCollapsed) {
sel().collapse();
}
drawZoomBox.call(c);
ctx = null;
}
}
function handleMouseDown(ev, gridpos, datapos, neighbor, plot) {
var c = plot.plugins.cursor;
if(plot.plugins.mobile){
$(document).one('vmouseup.jqplot_cursor', {plot:plot}, handleMouseUp);
} else {
$(document).one('mouseup.jqplot_cursor', {plot:plot}, handleMouseUp);
}
var axes = plot.axes;
if (document.onselectstart != undefined) {
c._oldHandlers.onselectstart = document.onselectstart;
document.onselectstart = function () { return false; };
}
if (document.ondrag != undefined) {
c._oldHandlers.ondrag = document.ondrag;
document.ondrag = function () { return false; };
}
if (document.onmousedown != undefined) {
c._oldHandlers.onmousedown = document.onmousedown;
document.onmousedown = function () { return false; };
}
if (c.zoom) {
if (!c.zoomProxy) {
var ctx = c.zoomCanvas._ctx;
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
ctx = null;
}
if (c.constrainZoomTo == 'x') {
c._zoom.start = [gridpos.x, 0];
}
else if (c.constrainZoomTo == 'y') {
c._zoom.start = [0, gridpos.y];
}
else {
c._zoom.start = [gridpos.x, gridpos.y];
}
c._zoom.started = true;
for (var ax in datapos) {
// get zoom starting position.
c._zoom.axes.start[ax] = datapos[ax];
}
if(plot.plugins.mobile){
$(document).bind('vmousemove.jqplotCursor', {plot:plot}, handleZoomMove);
} else {
$(document).bind('mousemove.jqplotCursor', {plot:plot}, handleZoomMove);
}
}
}
function handleMouseUp(ev) {
var plot = ev.data.plot;
var c = plot.plugins.cursor;
if (c.zoom && c._zoom.zooming && !c.zoomTarget) {
var xpos = c._zoom.gridpos.x;
var ypos = c._zoom.gridpos.y;
var datapos = c._zoom.datapos;
var height = c.zoomCanvas._ctx.canvas.height;
var width = c.zoomCanvas._ctx.canvas.width;
var axes = plot.axes;
if (c.constrainOutsideZoom && !c.onGrid) {
if (xpos < 0) { xpos = 0; }
else if (xpos > width) { xpos = width; }
if (ypos < 0) { ypos = 0; }
else if (ypos > height) { ypos = height; }
for (var axis in datapos) {
if (datapos[axis]) {
if (axis.charAt(0) == 'x') {
datapos[axis] = axes[axis].series_p2u(xpos);
}
else {
datapos[axis] = axes[axis].series_p2u(ypos);
}
}
}
}
if (c.constrainZoomTo == 'x') {
ypos = height;
}
else if (c.constrainZoomTo == 'y') {
xpos = width;
}
c._zoom.end = [xpos, ypos];
c._zoom.gridpos = {x:xpos, y:ypos};
c.doZoom(c._zoom.gridpos, datapos, plot, c);
}
c._zoom.started = false;
c._zoom.zooming = false;
$(document).unbind('mousemove.jqplotCursor', handleZoomMove);
if (document.onselectstart != undefined && c._oldHandlers.onselectstart != null){
document.onselectstart = c._oldHandlers.onselectstart;
c._oldHandlers.onselectstart = null;
}
if (document.ondrag != undefined && c._oldHandlers.ondrag != null){
document.ondrag = c._oldHandlers.ondrag;
c._oldHandlers.ondrag = null;
}
if (document.onmousedown != undefined && c._oldHandlers.onmousedown != null){
document.onmousedown = c._oldHandlers.onmousedown;
c._oldHandlers.onmousedown = null;
}
}
function drawZoomBox() {
var start = this._zoom.start;
var end = this._zoom.end;
var ctx = this.zoomCanvas._ctx;
var l, t, h, w;
if (end[0] > start[0]) {
l = start[0];
w = end[0] - start[0];
}
else {
l = end[0];
w = start[0] - end[0];
}
if (end[1] > start[1]) {
t = start[1];
h = end[1] - start[1];
}
else {
t = end[1];
h = start[1] - end[1];
}
ctx.fillStyle = 'rgba(0,0,0,0.2)';
ctx.strokeStyle = '#999999';
ctx.lineWidth = 1.0;
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
ctx.fillRect(0,0,ctx.canvas.width, ctx.canvas.height);
ctx.clearRect(l, t, w, h);
// IE won't show transparent fill rect, so stroke a rect also.
ctx.strokeRect(l,t,w,h);
ctx = null;
}
$.jqplot.CursorLegendRenderer = function(options) {
$.jqplot.TableLegendRenderer.call(this, options);
this.formatString = '%s';
};
$.jqplot.CursorLegendRenderer.prototype = new $.jqplot.TableLegendRenderer();
$.jqplot.CursorLegendRenderer.prototype.constructor = $.jqplot.CursorLegendRenderer;
// called in context of a Legend
$.jqplot.CursorLegendRenderer.prototype.draw = function() {
if (this._elem) {
this._elem.emptyForce();
this._elem = null;
}
if (this.show) {
var series = this._series, s;
// make a table. one line label per row.
var elem = document.createElement('div');
this._elem = $(elem);
elem = null;
this._elem.addClass('jqplot-legend jqplot-cursor-legend');
this._elem.css('position', 'absolute');
var pad = false;
for (var i = 0; i< series.length; i++) {
s = series[i];
if (s.show && s.showLabel) {
var lt = $.jqplot.sprintf(this.formatString, s.label.toString());
if (lt) {
var color = s.color;
if (s._stack && !s.fill) {
color = '';
}
addrow.call(this, lt, color, pad, i);
pad = true;
}
// let plugins add more rows to legend. Used by trend line plugin.
for (var j=0; j<$.jqplot.addLegendRowHooks.length; j++) {
var item = $.jqplot.addLegendRowHooks[j].call(this, s);
if (item) {
addrow.call(this, item.label, item.color, pad);
pad = true;
}
}
}
}
series = s = null;
delete series;
delete s;
}
function addrow(label, color, pad, idx) {
var rs = (pad) ? this.rowSpacing : '0';
var tr = $('<tr class="jqplot-legend jqplot-cursor-legend"></tr>').appendTo(this._elem);
tr.data('seriesIndex', idx);
$('<td class="jqplot-legend jqplot-cursor-legend-swatch" style="padding-top:'+rs+';">'+
'<div style="border:1px solid #cccccc;padding:0.2em;">'+
'<div class="jqplot-cursor-legend-swatch" style="background-color:'+color+';"></div>'+
'</div></td>').appendTo(tr);
var td = $('<td class="jqplot-legend jqplot-cursor-legend-label" style="vertical-align:middle;padding-top:'+rs+';"></td>');
td.appendTo(tr);
td.data('seriesIndex', idx);
if (this.escapeHtml) {
td.text(label);
}
else {
td.html(label);
}
tr = null;
td = null;
}
return this._elem;
};
})(jQuery);
|
vousk/jsdelivr
|
files/jqplot/1.0.4/plugins/jqplot.cursor.js
|
JavaScript
|
mit
| 47,196 |
// SpryDOMUtils.js - version 0.13 - Spry Pre-Release 1.7
//
// Copyright (c) 2007. Adobe Systems Incorporated.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Adobe Systems Incorporated nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
(function() { // BeginSpryComponent
if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Utils) Spry.Utils = {};
//////////////////////////////////////////////////////////////////////
//
// Define Prototype's $() convenience function, but make sure it is
// namespaced under Spry so that we avoid collisions with other
// toolkits.
//
//////////////////////////////////////////////////////////////////////
Spry.$ = function(element)
{
if (arguments.length > 1)
{
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push(Spry.$(arguments[i]));
return elements;
}
if (typeof element == 'string')
element = document.getElementById(element);
return element;
};
//////////////////////////////////////////////////////////////////////
//
// DOM Utils
//
//////////////////////////////////////////////////////////////////////
Spry.Utils.getAttribute = function(ele, name)
{
ele = Spry.$(ele);
if (!ele || !name)
return null;
// We need to wrap getAttribute with a try/catch because IE will throw
// an exception if you call it with a namespace prefixed attribute name
// that doesn't exist.
try { var value = ele.getAttribute(name); }
catch (e) { value == undefined; }
// XXX: Workaround for Safari 2.x and earlier:
//
// If value is undefined, the attribute didn't exist. Check to see if this is
// a namespace prefixed attribute name. If it is, remove the ':' from the name
// and try again. This allows us to support spry attributes of the form
// "spry:region" and "spryregion".
if (value == undefined && name.search(/:/) != -1)
{
try { var value = ele.getAttribute(name.replace(/:/, "")); }
catch (e) { value == undefined; }
}
return value;
};
Spry.Utils.setAttribute = function(ele, name, value)
{
ele = Spry.$(ele);
if (!ele || !name)
return;
// IE doesn't allow you to set the "class" attribute. You
// have to set the className property instead.
if (name == "class")
ele.className = value;
else
{
// I'm probably being a bit paranoid, but given the fact that
// getAttribute() throws exceptions when dealing with namespace
// prefixed attributes, I'm going to wrap this setAttribute()
// call with try/catch just in case ...
try { ele.setAttribute(name, value); } catch(e) {}
// XXX: Workaround for Safari 2.x and earlier:
//
// If this is a namespace prefixed attribute, check to make
// sure an attribute was created. This is necessary because some
// older versions of Safari (2.x and earlier) drop the namespace
// prefixes. If the attribute was munged, try removing the ':'
// character from the attribute name and setting the attribute
// using the resulting name. The idea here is that even if we
// remove the ':' character, Spry.Utils.getAttribute() will still
// find the attribute.
if (name.search(/:/) != -1 && ele.getAttribute(name) == undefined)
ele.setAttribute(name.replace(/:/, ""), value);
}
};
Spry.Utils.removeAttribute = function(ele, name)
{
ele = Spry.$(ele);
if (!ele || !name)
return;
try { ele.removeAttribute(name); } catch(e) {}
// XXX: Workaround for Safari 2.x and earlier:
//
// If this is a namespace prefixed attribute, make sure we
// also remove any attributes with the same name, but without
// the ':' character.
if (name.search(/:/) != -1)
ele.removeAttribute(name.replace(/:/, ""));
// XXX: Workaround for IE
//
// IE doesn't allow you to remove the "class" attribute.
// It requires you to remove "className" instead, so go
// ahead and try to remove that too.
if (name == "class")
ele.removeAttribute("className");
};
Spry.Utils.addClassName = function(ele, className)
{
ele = Spry.$(ele);
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
return;
ele.className += (ele.className ? " " : "") + className;
};
Spry.Utils.removeClassName = function(ele, className)
{
ele = Spry.$(ele);
if (Spry.Utils.hasClassName(ele, className))
ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};
Spry.Utils.toggleClassName = function(ele, className)
{
if (Spry.Utils.hasClassName(ele, className))
Spry.Utils.removeClassName(ele, className);
else
Spry.Utils.addClassName(ele, className);
};
Spry.Utils.hasClassName = function(ele, className)
{
ele = Spry.$(ele);
if (!ele || !className || !ele.className || ele.className.search(new RegExp("\\b" + className + "\\b")) == -1)
return false;
return true;
};
Spry.Utils.camelizeString = function(str)
{
var cStr = "";
var a = str.split("-");
for (var i = 0; i < a.length; i++)
{
var s = a[i];
if (s)
cStr = cStr ? (cStr + s.charAt(0).toUpperCase() + s.substring(1)) : s;
}
return cStr;
};
Spry.Utils.styleStringToObject = function(styleStr)
{
var o = {};
if (styleStr)
{
var pvA = styleStr.split(";");
for (var i = 0; i < pvA.length; i++)
{
var pv = pvA[i];
if (pv && pv.indexOf(":") != -1)
{
var nvA = pv.split(":");
var n = nvA[0].replace(/^\s*|\s*$/g, "");
var v = nvA[1].replace(/^\s*|\s*$/g, "");
if (n && v)
o[Spry.Utils.camelizeString(n)] = v;
}
}
}
return o;
};
Spry.Utils.addEventListener = function(element, eventType, handler, capture)
{
try
{
if (!Spry.Utils.eventListenerIsBoundToElement(element, eventType, handler, capture))
{
element = Spry.$(element);
handler = Spry.Utils.bindEventListenerToElement(element, eventType, handler, capture);
if (element.addEventListener)
element.addEventListener(eventType, handler, capture);
else if (element.attachEvent)
element.attachEvent("on" + eventType, handler);
}
}
catch (e) {}
};
Spry.Utils.removeEventListener = function(element, eventType, handler, capture)
{
try
{
element = Spry.$(element);
handler = Spry.Utils.unbindEventListenerFromElement(element, eventType, handler, capture);
if (element.removeEventListener)
element.removeEventListener(eventType, handler, capture);
else if (element.detachEvent)
element.detachEvent("on" + eventType, handler);
}
catch (e) {}
};
Spry.Utils.eventListenerHash = {};
Spry.Utils.nextEventListenerID = 1;
Spry.Utils.getHashForElementAndHandler = function(element, eventType, handler, capture)
{
var hash = null;
element = Spry.$(element);
if (element)
{
if (typeof element.spryEventListenerID == "undefined")
element.spryEventListenerID = "e" + (Spry.Utils.nextEventListenerID++);
if (typeof handler.spryEventHandlerID == "undefined")
handler.spryEventHandlerID = "h" + (Spry.Utils.nextEventListenerID++);
hash = element.spryEventListenerID + "-" + handler.spryEventHandlerID + "-" + eventType + (capture?"-capture":"");
}
return hash;
};
Spry.Utils.eventListenerIsBoundToElement = function(element, eventType, handler, capture)
{
element = Spry.$(element);
var hash = Spry.Utils.getHashForElementAndHandler(element, eventType, handler, capture);
return Spry.Utils.eventListenerHash[hash] != undefined;
};
Spry.Utils.bindEventListenerToElement = function(element, eventType, handler, capture)
{
element = Spry.$(element);
var hash = Spry.Utils.getHashForElementAndHandler(element, eventType, handler, capture);
if (Spry.Utils.eventListenerHash[hash])
return Spry.Utils.eventListenerHash[hash];
return Spry.Utils.eventListenerHash[hash] = function(e)
{
e = e || window.event;
if (!e.preventDefault) e.preventDefault = function() { this.returnValue = false; };
if (!e.stopPropagation) e.stopPropagation = function() { this.cancelBubble = true; };
var result = handler.call(element, e);
if (result == false)
{
e.preventDefault();
e.stopPropagation();
}
return result;
};
};
Spry.Utils.unbindEventListenerFromElement = function(element, eventType, handler, capture)
{
element = Spry.$(element);
var hash = Spry.Utils.getHashForElementAndHandler(element, eventType, handler, capture);
if (Spry.Utils.eventListenerHash[hash])
{
handler = Spry.Utils.eventListenerHash[hash];
Spry.Utils.eventListenerHash[hash] = undefined;
}
return handler;
};
Spry.Utils.cancelEvent = function(e)
{
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
return false;
};
Spry.Utils.addLoadListener = function(handler)
{
if (typeof window.addEventListener != 'undefined')
window.addEventListener('load', handler, false);
else if (typeof document.addEventListener != 'undefined')
document.addEventListener('load', handler, false);
else if (typeof window.attachEvent != 'undefined')
window.attachEvent('onload', handler);
};
Spry.Utils.isDescendant = function(parent, child)
{
if (parent && child)
{
child = child.parentNode;
while (child)
{
if (parent == child)
return true;
child = child.parentNode;
}
}
return false;
};
Spry.Utils.getAncestor = function(ele, selector)
{
ele = Spry.$(ele);
if (ele)
{
var s = Spry.$$.tokenizeSequence(selector ? selector : "*")[0];
var t = s ? s[0] : null;
if (t)
{
var p = ele.parentNode;
while (p)
{
if (t.match(p))
return p;
p = p.parentNode;
}
}
}
return null;
};
//////////////////////////////////////////////////////////////////////
//
// CSS Selector Matching
//
//////////////////////////////////////////////////////////////////////
Spry.$$ = function(selectorSequence, rootNode)
{
var matches = [];
Spry.$$.addExtensions(matches);
// If the first argument to $$() is an object, it
// is assumed that all args are either a DOM element
// or an array of DOM elements, in which case we
// simply append all DOM elements to our special
// matches array and return immediately.
if (typeof arguments[0] == "object")
{
for (var i = 0; i < arguments.length; i++)
{
if (arguments[i].constructor == Array)
matches.push.apply(matches, arguments[i]);
else
matches.push(arguments[i]);
}
return matches;
}
if (!rootNode)
rootNode = document;
else
rootNode = Spry.$(rootNode);
var sequences = Spry.$$.tokenizeSequence(selectorSequence);
++Spry.$$.queryID;
var nid = 0;
var ns = sequences.length;
for (var i = 0; i < ns; i++)
{
var m = Spry.$$.processTokens(sequences[i], rootNode);
var nm = m.length;
for (var j = 0; j < nm; j++)
{
var n = m[j];
if (!n.spry$$ID)
{
n.spry$$ID = ++nid;
matches.push(n);
}
}
}
var nm = matches.length;
for (i = 0; i < nm; i++)
matches[i].spry$$ID = undefined;
return matches;
};
Spry.$$.cache = {};
Spry.$$.queryID = 0;
Spry.$$.Token = function()
{
this.type = Spry.$$.Token.SELECTOR;
this.name = "*";
this.id = "";
this.classes = [];
this.attrs = [];
this.pseudos = [];
};
Spry.$$.Token.Attr = function(n, v)
{
this.name = n;
this.value = v ? new RegExp(v) : undefined;
};
Spry.$$.Token.PseudoClass = function(pstr)
{
this.name = pstr.replace(/\(.*/, "");
this.arg = pstr.replace(/^[^\(\)]*\(?\s*|\)\s*$/g, "");
this.func = Spry.$$.pseudoFuncs[this.name];
};
Spry.$$.Token.SELECTOR = 0;
Spry.$$.Token.COMBINATOR = 1;
Spry.$$.Token.prototype.match = function(ele, nameAlreadyMatches)
{
if (this.type == Spry.$$.Token.COMBINATOR)
return false;
if (!nameAlreadyMatches && this.name != '*' && this.name != ele.nodeName.toLowerCase())
return false;
if (this.id && this.id != ele.id)
return false;
var classes = this.classes;
var len = classes.length;
for (var i = 0; i < len; i++)
{
if (!ele.className || !classes[i].value.test(ele.className))
return false;
}
var attrs = this.attrs;
len = attrs.length;
for (var i = 0; i < len; i++)
{
var a = attrs[i];
var an = ele.attributes.getNamedItem(a.name);
if (!an || (!a.value && an.nodeValue == undefined) || (a.value && !a.value.test(an.nodeValue)))
return false;
}
var ps = this.pseudos;
var len = ps.length;
for (var i = 0; i < len; i++)
{
var p = ps[i];
if (p && p.func && !p.func(p.arg, ele, this))
return false;
}
return true;
};
Spry.$$.Token.prototype.getNodeNameIfTypeMatches = function(ele)
{
var nodeName = ele.nodeName.toLowerCase();
if (this.name != '*')
{
if (this.name != nodeName)
return null;
return this.name;
}
return nodeName;
};
Spry.$$.escapeRegExpCharsRE = /\/|\.|\*|\+|\(|\)|\[|\]|\{|\}|\\|\|/g;
Spry.$$.tokenizeSequence = function(s)
{
var cc = Spry.$$.cache[s];
if (cc) return cc;
// Attribute Selector: /(\[[^\"'~\^\$\*\|\]=]+([~\^\$\*\|]?=\s*('[^']*'|"[^"]*"|[^"'\]]+))?\s*\])/g
// Simple Selector: /((:[^\.#:\s,>~\+\[\]]+\(([^\(\)]+|\([^\(\)]*\))*\))|[\.#:]?[^\.#:\s,>~\+\[\]]+)/g
// Combinator: /(\s*[\s,>~\+]\s*)/g
var tokenExpr = /(\[[^\"'~\^\$\*\|\]=]+([~\^\$\*\|]?=\s*('[^']*'|"[^"]*"|[^"'\]]+))?\s*\])|((:[^\.#:\s,>~\+\[\]]+\(([^\(\)]+|\([^\(\)]*\))*\))|[\.#:]?[^\.#:\s,>~\+\[\]]+)|(\s*[\s,>~\+]\s*)/g;
var tkn = new Spry.$$.Token;
var sequence = [];
sequence.push(tkn);
var tokenSequences = [];
tokenSequences.push(sequence);
s = s.replace(/^\s*|\s*$/, "");
var expMatch = tokenExpr.exec(s);
while (expMatch)
{
var tstr = expMatch[0];
var c = tstr.charAt(0);
switch (c)
{
case '.':
tkn.classes.push(new Spry.$$.Token.Attr("class", "\\b" + tstr.substr(1) + "\\b"));
break;
case '#':
tkn.id = tstr.substr(1);
break;
case ':':
tkn.pseudos.push(new Spry.$$.Token.PseudoClass(tstr));
break;
case '[':
var attrComps = tstr.match(/\[([^\"'~\^\$\*\|\]=]+)(([~\^\$\*\|]?=)\s*('[^']*'|"[^"]*"|[^"'\]]+))?\s*\]/);
var name = attrComps[1];
var matchType = attrComps[3];
var val = attrComps[4];
if (val)
{
val = val.replace(/^['"]|['"]$/g, "");
val = val.replace(Spry.$$.escapeRegExpCharsRE, '\\$&');
}
var matchStr = undefined;
switch(matchType)
{
case "=":
matchStr = "^" + val + "$";
break;
case "^=":
matchStr = "^" + val;
break;
case "$=":
matchStr = val + "$";
break;
case "~=":
case "|=":
matchStr = "\\b" + val + "\\b";
break;
case "*=":
matchStr = val;
break;
}
tkn.attrs.push(new Spry.$$.Token.Attr(name, matchStr));
break;
default:
var combiMatch = tstr.match(/^\s*([\s,~>\+])\s*$/);
if (combiMatch)
{
if (combiMatch[1] == ',')
{
sequence = new Array;
tokenSequences.push(sequence);
tkn = new Spry.$$.Token;
sequence.push(tkn);
}
else
{
tkn = new Spry.$$.Token;
tkn.type = Spry.$$.Token.COMBINATOR;
tkn.name = combiMatch[1];
sequence.push(tkn);
tkn = new Spry.$$.Token();
sequence.push(tkn);
}
}
else
tkn.name = tstr.toLowerCase();
break;
}
expMatch = tokenExpr.exec(s);
}
Spry.$$.cache[s] = tokenSequences;
return tokenSequences;
};
Spry.$$.combinatorFuncs = {
// Element Descendant
" ": function(nodes, token)
{
var uid = ++Spry.$$.uniqueID;
var results = [];
var nn = nodes.length;
for (var i = 0; i < nn; i++)
{
var n = nodes[i];
if (uid != n.spry$$uid)
{
// n.spry$$uid = uid;
var ea = nodes[i].getElementsByTagName(token.name);
var ne = ea.length;
for (var j = 0; j < ne; j++)
{
var e = ea[j];
// If the token matches, add it to our results. We have
// to make sure e is an element because IE6 returns the DOCTYPE
// tag as a comment when '*' is used in the call to getElementsByTagName().
if (e.nodeType == 1 /* Node.ELEMENT_NODE */ && token.match(e, true))
results.push(e);
e.spry$$uid = uid;
}
}
}
return results;
},
// Element Child
">": function(nodes, token)
{
var results = [];
var nn = nodes.length;
for (var i = 0; i < nn; i++)
{
var n = nodes[i].firstChild;
while (n)
{
if (n.nodeType == 1 /* Node.ELEMENT_NODE */ && token.match(n))
results.push(n);
n = n.nextSibling;
}
}
return results;
},
// Element Immediately Preceded By
"+": function(nodes, token)
{
var results = [];
var nn = nodes.length;
for (var i = 0; i < nn; i++)
{
var n = nodes[i].nextSibling;
while (n && n.nodeType != 1 /* Node.ELEMENT_NODE */)
n = n.nextSibling;
if (n && token.match(n))
results.push(n);
}
return results;
},
// Element Preceded By
"~": function(nodes, token)
{
var uid = ++Spry.$$.uniqueID;
var results = [];
var nn = nodes.length;
for (var i = 0; i < nn; i++)
{
var n = nodes[i].nextSibling;
while (n)
{
if (n.nodeType == 1 /* Node.ELEMENT_NODE */)
{
if (uid == n.spry$$uid)
break;
if (token.match(n))
{
results.push(n);
n.spry$$uid = uid;
}
}
n = n.nextSibling;
}
}
return results;
}
};
Spry.$$.uniqueID = 0;
Spry.$$.pseudoFuncs = {
":first-child": function(arg, node, token)
{
var n = node.previousSibling;
while (n)
{
if (n.nodeType == 1) return false; // Node.ELEMENT_NODE
n = n.previousSibling;
}
return true;
},
":last-child": function(arg, node, token)
{
var n = node.nextSibling;
while (n)
{
if (n.nodeType == 1) // Node.ELEMENT_NODE
return false;
n = n.nextSibling;
}
return true;
},
":empty": function(arg, node, token)
{
var n = node.firstChild;
while (n)
{
switch(n.nodeType)
{
case 1: // Node.ELEMENT_NODE
case 3: // Node.TEXT_NODE
case 4: // Node.CDATA_NODE
case 5: // Node.ENTITY_REFERENCE_NODE
return false;
}
n = n.nextSibling;
}
return true;
},
":nth-child": function(arg, node, token)
{
return Spry.$$.nthChild(arg, node, token);
},
":nth-last-child": function(arg, node, token)
{
return Spry.$$.nthChild(arg, node, token, true);
},
":nth-of-type": function(arg, node, token)
{
return Spry.$$.nthChild(arg, node, token, false, true);
},
":nth-last-of-type": function(arg, node, token)
{
return Spry.$$.nthChild(arg, node, token, true, true);
},
":first-of-type": function(arg, node, token)
{
var nodeName = token.getNodeNameIfTypeMatches(node);
if (!nodeName) return false;
var n = node.previousSibling;
while (n)
{
if (n.nodeType == 1 && nodeName == n.nodeName.toLowerCase()) return false; // Node.ELEMENT_NODE
n = n.previousSibling;
}
return true;
},
":last-of-type": function(arg, node, token)
{
var nodeName = token.getNodeNameIfTypeMatches(node);
if (!nodeName) return false;
var n = node.nextSibling;
while (n)
{
if (n.nodeType == 1 && nodeName == n.nodeName.toLowerCase()) // Node.ELEMENT_NODE
return false;
n = n.nextSibling;
}
return true;
},
":only-child": function(arg, node, token)
{
var f = Spry.$$.pseudoFuncs;
return f[":first-child"](arg, node, token) && f[":last-child"](arg, node, token);
},
":only-of-type": function(arg, node, token)
{
var f = Spry.$$.pseudoFuncs;
return f[":first-of-type"](arg, node, token) && f[":last-of-type"](arg, node, token);
},
":not": function(arg, node, token)
{
var s = Spry.$$.tokenizeSequence(arg)[0];
var t = s ? s[0] : null;
return !t || !t.match(node);
},
":enabled": function(arg, node, token)
{
return !node.disabled;
},
":disabled": function(arg, node, token)
{
return node.disabled;
},
":checked": function(arg, node, token)
{
return node.checked;
},
":root": function(arg, node, token)
{
return node.parentNode && node.ownerDocument && node.parentNode == node.ownerDocument;
}
};
Spry.$$.nthRegExp = /((-|[0-9]+)?n)?([+-]?[0-9]*)/;
Spry.$$.nthCache = {
"even": { a: 2, b: 0, mode: 1, invalid: false }
, "odd": { a: 2, b: 1, mode: 1, invalid: false }
, "2n": { a: 2, b: 0, mode: 1, invalid: false }
, "2n+1": { a: 2, b: 1, mode: 1, invalid: false }
};
Spry.$$.parseNthChildString = function(str)
{
var o = Spry.$$.nthCache[str];
if (!o)
{
var m = str.match(Spry.$$.nthRegExp);
var n = m[1];
var a = m[2];
var b = m[3];
if (!a)
{
// An 'a' value was not specified. Was there an 'n' present?
// If so, we treat it as an increment of 1, otherwise we're
// in no-repeat mode.
a = n ? 1 : 0;
}
else if (a == "-")
{
// The string is using the "-n" short-hand which is
// short for -1.
a = -1;
}
else
{
// An integer repeat value for 'a' was specified. Convert
// it into number.
a = parseInt(a, 10);
}
// If a 'b' value was specified, turn it into a number.
// If no 'b' value was specified, default to zero.
b = b ? parseInt(b, 10) : 0;
// Figure out the mode:
//
// -1 - repeat backwards
// 0 - no repeat
// 1 - repeat forwards
var mode = (a == 0) ? 0 : ((a > 0) ? 1 : -1);
var invalid = false;
// Fix up 'a' and 'b' for proper repeating.
if (a > 0 && b < 0)
{
b = b % a;
b = ((b=(b%a)) < 0) ? a + b : b;
}
else if (a < 0)
{
if (b < 0)
invalid = true;
else
a = Math.abs(a);
}
o = new Object;
o.a = a;
o.b = b;
o.mode = mode;
o.invalid = invalid;
Spry.$$.nthCache[str] = o;
}
return o;
};
Spry.$$.nthChild = function(arg, node, token, fromLastSib, matchNodeName)
{
if (matchNodeName)
{
var nodeName = token.getNodeNameIfTypeMatches(node);
if (!nodeName) return false;
}
var o = Spry.$$.parseNthChildString(arg);
if (o.invalid)
return false;
var qidProp = "spry$$ncQueryID";
var posProp = "spry$$ncPos";
var countProp = "spry$$ncCount";
if (matchNodeName)
{
qidProp += nodeName;
posProp += nodeName;
countProp += nodeName;
}
var parent = node.parentNode;
if (parent[qidProp] != Spry.$$.queryID)
{
var pos = 0;
parent[qidProp] = Spry.$$.queryID;
var c = parent.firstChild;
while (c)
{
if (c.nodeType == 1 && (!matchNodeName || nodeName == c.nodeName.toLowerCase()))
c[posProp] = ++pos;
c = c.nextSibling;
}
parent[countProp] = pos;
}
pos = node[posProp];
if (fromLastSib)
pos = parent[countProp] - pos + 1;
/*
var sib = fromLastSib ? "nextSibling" : "previousSibling";
var pos = 1;
var n = node[sib];
while (n)
{
if (n.nodeType == 1 && (!matchNodeName || nodeName == n.nodeName.toLowerCase()))
{
if (n == node) break;
++pos;
}
n = n[sib];
}
*/
if (o.mode == 0) // Exact match
return pos == o.b;
if (o.mode > 0) // Forward Repeat
return (pos < o.b) ? false : (!((pos - o.b) % o.a));
return (pos > o.b) ? false : (!((o.b - pos) % o.a)); // Backward Repeat
};
Spry.$$.processTokens = function(tokens, root)
{
var numTokens = tokens.length;
var nodeSet = [ root ];
var combiFunc = null;
for (var i = 0; i < numTokens && nodeSet.length > 0; i++)
{
var t = tokens[i];
if (t.type == Spry.$$.Token.SELECTOR)
{
if (combiFunc)
{
nodeSet = combiFunc(nodeSet, t);
combiFunc = null;
}
else
nodeSet = Spry.$$.getMatchingElements(nodeSet, t);
}
else // Spry.$$.Token.COMBINATOR
combiFunc = Spry.$$.combinatorFuncs[t.name];
}
return nodeSet;
};
Spry.$$.getMatchingElements = function(nodes, token)
{
var results = [];
if (token.id)
{
n = nodes[0];
if (n && n.ownerDocument)
{
var e = n.ownerDocument.getElementById(token.id);
if (e)
{
// XXX: We need to make sure that the element
// we found is actually underneath the root
// we were given!
if (token.match(e))
results.push(e);
}
return results;
}
}
var nn = nodes.length;
for (var i = 0; i < nn; i++)
{
var n = nodes[i];
// if (token.match(n)) results.push(n);
var ea = n.getElementsByTagName(token.name);
var ne = ea.length;
for (var j = 0; j < ne; j++)
{
var e = ea[j];
// If the token matches, add it to our results. We have
// to make sure e is an element because IE6 returns the DOCTYPE
// tag as a comment when '*' is used in the call to getElementsByTagName().
if (e.nodeType == 1 /* Node.ELEMENT_NODE */ && token.match(e, true))
results.push(e);
}
}
return results;
};
/*
Spry.$$.dumpSequences = function(sequences)
{
Spry.Debug.trace("<hr />Number of Sequences: " + sequences.length);
for (var i = 0; i < sequences.length; i++)
{
var str = "";
var s = sequences[i];
Spry.Debug.trace("<hr />Sequence " + i + " -- Tokens: " + s.length);
for (var j = 0; j < s.length; j++)
{
var t = s[j];
if (t.type == Spry.$$.Token.SELECTOR)
{
str += " SELECTOR:\n Name: " + t.name + "\n ID: " + t.id + "\n Attrs:\n";
for (var k = 0; k < t.classes.length; k++)
str += " " + t.classes[k].name + ": " + t.classes[k].value + "\n";
for (var k = 0; k < t.attrs.length; k++)
str += " " + t.attrs[k].name + ": " + t.attrs[k].value + "\n";
str += " Pseudos:\n";
for (var k = 0; k < t.pseudos.length; k++)
str += " " + t.pseudos[k].name + (t.pseudos[k].arg ? "(" + t.pseudos[k].arg + ")" : "") + "\n";
}
else
{
str += " COMBINATOR:\n Name: '" + t.name + "'\n";
}
}
Spry.Debug.trace("<pre>" + Spry.Utils.encodeEntities(str) + "</pre>");
}
};
*/
Spry.$$.addExtensions = function(a)
{
for (var f in Spry.$$.Results)
a[f] = Spry.$$.Results[f];
};
Spry.$$.Results = {};
Spry.$$.Results.forEach = function(func)
{
var n = this.length;
for (var i = 0; i < n; i++)
func(this[i]);
return this;
};
Spry.$$.Results.setAttribute = function(name, value)
{
return this.forEach(function(n) { Spry.Utils.setAttribute(n, name, value); });
};
Spry.$$.Results.removeAttribute = function(name)
{
return this.forEach(function(n) { Spry.Utils.removeAttribute(n, name); });
};
Spry.$$.Results.addClassName = function(className)
{
return this.forEach(function(n) { Spry.Utils.addClassName(n, className); });
};
Spry.$$.Results.removeClassName = function(className)
{
return this.forEach(function(n) { Spry.Utils.removeClassName(n, className); });
};
Spry.$$.Results.toggleClassName = function(className)
{
return this.forEach(function(n) { Spry.Utils.toggleClassName(n, className); });
};
Spry.$$.Results.addEventListener = function(eventType, handler, capture, bindHandler)
{
return this.forEach(function(n) { Spry.Utils.addEventListener(n, eventType, handler, capture, bindHandler); });
};
Spry.$$.Results.removeEventListener = function(eventType, handler, capture)
{
return this.forEach(function(n) { Spry.Utils.removeEventListener(n, eventType, handler, capture); });
};
Spry.$$.Results.setStyle = function(style)
{
if (style)
{
style = Spry.Utils.styleStringToObject(style);
this.forEach(function(n)
{
for (var p in style)
try { n.style[p] = style[p]; } catch (e) {}
});
}
return this;
};
Spry.$$.Results.setProperty = function(prop, value)
{
if (prop)
{
if (typeof prop == "string")
{
var p = {};
p[prop] = value;
prop = p;
}
this.forEach(function(n)
{
for (var p in prop)
try { n[p] = prop[p]; } catch (e) {}
});
}
return this;
};
})(); // EndSpryComponent
|
vousk/jsdelivr
|
files/spry/1.7/js/sprydomutils.js
|
JavaScript
|
mit
| 29,611 |
๏ปฟ/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'pastefromword', 'pt-br', {
confirmCleanup: 'O texto que vocรช deseja colar parece ter sido copiado do Word. Vocรช gostaria de remover a formataรงรฃo antes de colar?',
error: 'Nรฃo foi possรญvel limpar os dados colados devido a um erro interno',
title: 'Colar do Word',
toolbar: 'Colar do Word'
});
|
ramda/jsdelivr
|
files/ckeditor/4.3.0/plugins/pastefromword/lang/pt-br.js
|
JavaScript
|
mit
| 475 |
module.exports={title:"Bulma",slug:"bulma",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Bulma icon</title><path d="M11.25 0l-6 6 -1.5 10.5 7.5 7.5 9 -6 -6 -6 4.5 -4.5 -7.5 -7.5Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://github.com/jgthms/bulma/",hex:"00D1B2"};
|
cdnjs/cdnjs
|
ajax/libs/simple-icons/4.9.0/bulma.min.js
|
JavaScript
|
mit
| 341 |
var assert = require('assert')
var UINT32 = require('..').UINT32
describe('and method', function () {
describe('0&1', function () {
it('should return 0', function (done) {
var u = UINT32(0).and( UINT32(1) )
assert.equal( u.toNumber(), 0 )
done()
})
})
describe('1&2', function () {
it('should return 0', function (done) {
var u = UINT32(1).and( UINT32(2) )
assert.equal( u.toNumber(), 0 )
done()
})
})
describe('1&2^16', function () {
it('should return 0', function (done) {
var n = Math.pow(2, 16)
var u = UINT32(1).and( UINT32(n) )
assert.equal( u.toNumber(), 0 )
done()
})
})
describe('2^16&1', function () {
it('should return 0', function (done) {
var n = Math.pow(2, 16)
var u = UINT32(n).and( UINT32(1) )
assert.equal( u.toNumber(), 0 )
done()
})
})
describe('2^16&2^16', function () {
it('should return n', function (done) {
var n = Math.pow(2, 16)
var u = UINT32(n).and( UINT32(n) )
assert.equal( u.toNumber(), n )
done()
})
})
})
|
Phalanstere/WritersStudio
|
writers_studio-win32-ia32/resources/app/node_modules/cuint/test/UINT32_and-test.js
|
JavaScript
|
mit
| 1,129 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _rest = require('./internal/rest');
var _rest2 = _interopRequireDefault(_rest);
var _initialParams = require('./internal/initialParams');
var _initialParams2 = _interopRequireDefault(_initialParams);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Returns a function that when called, calls-back with the values provided.
* Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
* [`auto`]{@link module:ControlFlow.auto}.
*
* @name constant
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {...*} arguments... - Any number of arguments to automatically invoke
* callback with.
* @returns {AsyncFunction} Returns a function that when invoked, automatically
* invokes the callback with the previous given arguments.
* @example
*
* async.waterfall([
* async.constant(42),
* function (value, next) {
* // value === 42
* },
* //...
* ], callback);
*
* async.waterfall([
* async.constant(filename, "utf8"),
* fs.readFile,
* function (fileData, next) {
* //...
* }
* //...
* ], callback);
*
* async.auto({
* hostname: async.constant("https://server.net/"),
* port: findFreePort,
* launchServer: ["hostname", "port", function (options, cb) {
* startServer(options, cb);
* }],
* //...
* }, callback);
*/
exports.default = (0, _rest2.default)(function (values) {
var args = [null].concat(values);
return (0, _initialParams2.default)(function (ignoredArgs, callback) {
return callback.apply(this, args);
});
});
module.exports = exports['default'];
|
FOrmyown/LmWebsite
|
website/node_modules/async/constant.js
|
JavaScript
|
mit
| 1,805 |
/*
* Copyright (c) 2013-2014 Chukong Technologies Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* @type {Object}
* @name jsb.AssetsManager
* jsb.AssetsManager is the native AssetsManager for your game resources or scripts.
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
* Only available in JSB
*/
jsb.AssetsManager = cc.AssetsManager;
delete cc.AssetsManager;
/**
* @type {Object}
* @name jsb.EventListenerAssetsManager
* jsb.EventListenerAssetsManager is the native event listener for AssetsManager.
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
* Only available in JSB
*/
jsb.EventListenerAssetsManager = cc.EventListenerAssetsManager;
delete cc.EventListenerAssetsManager;
/**
* @type {Object}
* @name jsb.EventAssetsManager
* jsb.EventAssetsManager is the native event for AssetsManager.
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
* Only available in JSB
*/
jsb.EventAssetsManager = cc.EventAssetsManager;
delete cc.EventAssetsManager;
// move from jsb_cocos2d
//start------------------------------
cc.ControlButton.extend = cc.Class.extend;
cc.ControlColourPicker.extend = cc.Class.extend;
cc.ControlPotentiometer.extend = cc.Class.extend;
cc.ControlSlider.extend = cc.Class.extend;
cc.ControlStepper.extend = cc.Class.extend;
cc.ControlSwitch.extend = cc.Class.extend;
//end------------------------------
//
// cocos2d constants
//
// This helper file should be required after jsb_cocos2d.js
//
var cc = cc || {};
cc.SCROLLVIEW_DIRECTION_NONE = -1;
cc.SCROLLVIEW_DIRECTION_HORIZONTAL = 0;
cc.SCROLLVIEW_DIRECTION_VERTICAL = 1;
cc.SCROLLVIEW_DIRECTION_BOTH = 2;
cc.TABLEVIEW_FILL_TOPDOWN = 0;
cc.TABLEVIEW_FILL_BOTTOMUP = 1;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_DEFAULT = 0;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_DONE = 1;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_SEND = 2;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_SEARCH = 3;
/**
* @constant
* @type Number
*/
cc.KEYBOARD_RETURNTYPE_GO = 4;
/**
* The EditBox::InputMode defines the type of text that the user is allowed * to enter.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_ANY = 0;
/**
* The user is allowed to enter an e-mail address.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_EMAILADDR = 1;
/**
* The user is allowed to enter an integer value.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_NUMERIC = 2;
/**
* The user is allowed to enter a phone number.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_PHONENUMBER = 3;
/**
* The user is allowed to enter a URL.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_URL = 4;
/**
* The user is allowed to enter a real number value.
* This extends kEditBoxInputModeNumeric by allowing a decimal point.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_DECIMAL = 5;
/**
* The user is allowed to enter any text, except for line breaks.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_MODE_SINGLELINE = 6;
/**
* Indicates that the text entered is confidential data that should be
* obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_PASSWORD = 0;
/**
* Indicates that the text entered is sensitive data that the
* implementation must never store into a dictionary or table for use
* in predictive, auto-completing, or other accelerated input schemes.
* A credit card number is an example of sensitive data.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_SENSITIVE = 1;
/**
* This flag is a hint to the implementation that during text editing,
* the initial letter of each word should be capitalized.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD = 2;
/**
* This flag is a hint to the implementation that during text editing,
* the initial letter of each sentence should be capitalized.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE = 3;
/**
* Capitalize all characters automatically.
* @constant
* @type Number
*/
cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS = 4;
cc.CONTROL_EVENT_TOTAL_NUMBER = 9;
cc.CONTROL_EVENT_TOUCH_DOWN = 1 << 0; // A touch-down event in the control.
cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE = 1 << 1; // An event where a finger is dragged inside the bounds of the control.
cc.CONTROL_EVENT_TOUCH_DRAG_OUTSIDE = 1 << 2; // An event where a finger is dragged just outside the bounds of the control.
cc.CONTROL_EVENT_TOUCH_DRAG_ENTER = 1 << 3; // An event where a finger is dragged into the bounds of the control.
cc.CONTROL_EVENT_TOUCH_DRAG_EXIT = 1 << 4; // An event where a finger is dragged from within a control to outside its bounds.
cc.CONTROL_EVENT_TOUCH_UP_INSIDE = 1 << 5; // A touch-up event in the control where the finger is inside the bounds of the control.
cc.CONTROL_EVENT_TOUCH_UP_OUTSIDE = 1 << 6; // A touch-up event in the control where the finger is outside the bounds of the control.
cc.CONTROL_EVENT_TOUCH_CANCEL = 1 << 7; // A system event canceling the current touches for the control.
cc.CONTROL_EVENT_VALUECHANGED = 1 << 8; // A touch dragging or otherwise manipulating a control; causing it to emit a series of different values.
cc.CONTROL_STATE_NORMAL = 1 << 0; // The normal; or default state of a controlๆขฉhat is; enabled but neither selected nor highlighted.
cc.CONTROL_STATE_HIGHLIGHTED = 1 << 1; // Highlighted state of a control. A control enters this state when a touch down; drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property.
cc.CONTROL_STATE_DISABLED = 1 << 2; // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property.
cc.CONTROL_STATE_SELECTED = 1 << 3; // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property.
cc.CONTROL_STATE_INITIAL = 1 << 3;
cc.CONTROL_ZOOM_ACTION_TAG = 0xCCCB0001; //CCControlButton.js
cc.CONTROL_STEPPER_PARTMINUS = 0; //CCControlStepper.js
cc.CONTROL_STEPPER_PARTPLUS = 1;
cc.CONTROL_STEPPER_PARTNONE = 2;
cc.CONTROL_STEPPER_LABELCOLOR_ENABLED = cc.color(55, 55, 55);
cc.CONTROL_STEPPER_LABELCOLOR_DISABLED = cc.color(147, 147, 147);
cc.CONTROL_STEPPER_LABELFONT = "CourierNewPSMT";
cc.AUTOREPEAT_DELTATIME = 0.15;
cc.AUTOREPEAT_INCREASETIME_INCREMENT = 12;
jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0;
jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1;
jsb.EventAssetsManager.ERROR_PARSE_MANIFEST = 2;
jsb.EventAssetsManager.NEW_VERSION_FOUND = 3;
jsb.EventAssetsManager.ALREADY_UP_TO_DATE = 4;
jsb.EventAssetsManager.UPDATE_PROGRESSION = 5;
jsb.EventAssetsManager.ASSET_UPDATED = 6;
jsb.EventAssetsManager.ERROR_UPDATING = 7;
jsb.EventAssetsManager.UPDATE_FINISHED = 8;
jsb.EventAssetsManager.UPDATE_FAILED = 9;
jsb.EventAssetsManager.ERROR_DECOMPRESS = 10;
cc.ScrollView.extend = cc.Class.extend;
cc.TableView.extend = cc.Class.extend;
cc.TableViewCell.extend = cc.Class.extend;
|
darkoverlordofdata/asteroids
|
web/frameworks/runtime-src/proj.androidstudio/web/src/main/assets/script/extension/jsb_cocos2d_extension.js
|
JavaScript
|
mit
| 8,433 |
"use strict";
const conversions = require("webidl-conversions");
const utils = require("./utils.js");
const HTMLElement = require("./HTMLElement.js");
const impl = utils.implSymbol;
const mixin = utils.mixin;
const WindowEventHandlers = require("./WindowEventHandlers.js");
function HTMLBodyElement() {
throw new TypeError("Illegal constructor");
}
HTMLBodyElement.prototype = Object.create(HTMLElement.interface.prototype);
HTMLBodyElement.prototype.constructor = HTMLBodyElement;
mixin(HTMLBodyElement.prototype, WindowEventHandlers.interface.prototype);
WindowEventHandlers.mixedInto.push(HTMLBodyElement);
HTMLBodyElement.prototype.toString = function () {
if (this === HTMLBodyElement.prototype) {
return "[object HTMLBodyElementPrototype]";
}
return HTMLElement.interface.prototype.toString.call(this);
};
Object.defineProperty(HTMLBodyElement.prototype, "text", {
get() {
const value = this.getAttribute("text");
return value === null ? "" : value;
},
set(V) {
V = conversions["DOMString"](V, { treatNullAsEmptyString: true });
this.setAttribute("text", V);
},
enumerable: true,
configurable: true
});
Object.defineProperty(HTMLBodyElement.prototype, "link", {
get() {
const value = this.getAttribute("link");
return value === null ? "" : value;
},
set(V) {
V = conversions["DOMString"](V, { treatNullAsEmptyString: true });
this.setAttribute("link", V);
},
enumerable: true,
configurable: true
});
Object.defineProperty(HTMLBodyElement.prototype, "vLink", {
get() {
const value = this.getAttribute("vLink");
return value === null ? "" : value;
},
set(V) {
V = conversions["DOMString"](V, { treatNullAsEmptyString: true });
this.setAttribute("vLink", V);
},
enumerable: true,
configurable: true
});
Object.defineProperty(HTMLBodyElement.prototype, "aLink", {
get() {
const value = this.getAttribute("aLink");
return value === null ? "" : value;
},
set(V) {
V = conversions["DOMString"](V, { treatNullAsEmptyString: true });
this.setAttribute("aLink", V);
},
enumerable: true,
configurable: true
});
Object.defineProperty(HTMLBodyElement.prototype, "bgColor", {
get() {
const value = this.getAttribute("bgColor");
return value === null ? "" : value;
},
set(V) {
V = conversions["DOMString"](V, { treatNullAsEmptyString: true });
this.setAttribute("bgColor", V);
},
enumerable: true,
configurable: true
});
Object.defineProperty(HTMLBodyElement.prototype, "background", {
get() {
const value = this.getAttribute("background");
return value === null ? "" : value;
},
set(V) {
V = conversions["DOMString"](V);
this.setAttribute("background", V);
},
enumerable: true,
configurable: true
});
module.exports = {
mixedInto: [],
is(obj) {
if (obj) {
if (obj[impl] instanceof Impl.implementation) {
return true;
}
for (let i = 0; i < module.exports.mixedInto.length; ++i) {
if (obj instanceof module.exports.mixedInto[i]) {
return true;
}
}
}
return false;
},
isImpl(obj) {
if (obj) {
if (obj instanceof Impl.implementation) {
return true;
}
const wrapper = utils.wrapperForImpl(obj);
for (let i = 0; i < module.exports.mixedInto.length; ++i) {
if (wrapper instanceof module.exports.mixedInto[i]) {
return true;
}
}
}
return false;
},
create(constructorArgs, privateData) {
let obj = Object.create(HTMLBodyElement.prototype);
this.setup(obj, constructorArgs, privateData);
return obj;
},
createImpl(constructorArgs, privateData) {
let obj = Object.create(HTMLBodyElement.prototype);
this.setup(obj, constructorArgs, privateData);
return utils.implForWrapper(obj);
},
_internalSetup(obj) {
HTMLElement._internalSetup(obj);
},
setup(obj, constructorArgs, privateData) {
if (!privateData) privateData = {};
privateData.wrapper = obj;
this._internalSetup(obj);
obj[impl] = new Impl.implementation(constructorArgs, privateData);
obj[impl][utils.wrapperSymbol] = obj;
},
interface: HTMLBodyElement,
expose: {
Window: { HTMLBodyElement: HTMLBodyElement }
}
};
const Impl = require("../nodes/HTMLBodyElement-impl.js");
|
ElvisLouis/code
|
work/js/node_modules/jsdom/lib/jsdom/living/generated/HTMLBodyElement.js
|
JavaScript
|
gpl-2.0
| 4,335 |
/*
* Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) IBM Corp. 2009 All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @extends {WebInspector.View}
* @constructor
*/
WebInspector.ResourceView = function(resource)
{
WebInspector.View.call(this);
this.registerRequiredCSS("resourceView.css");
this.element.addStyleClass("resource-view");
this.resource = resource;
}
WebInspector.ResourceView.prototype = {
hasContent: function()
{
return false;
},
__proto__: WebInspector.View.prototype
}
/**
* @param {WebInspector.Resource} resource
*/
WebInspector.ResourceView.hasTextContent = function(resource)
{
if (resource.type.isTextType())
return true;
if (resource.type === WebInspector.resourceTypes.Other)
return resource.content && !resource.contentEncoded;
return false;
}
/**
* @param {WebInspector.Resource} resource
*/
WebInspector.ResourceView.nonSourceViewForResource = function(resource)
{
switch (resource.type) {
case WebInspector.resourceTypes.Image:
return new WebInspector.ImageView(resource);
case WebInspector.resourceTypes.Font:
return new WebInspector.FontView(resource);
default:
return new WebInspector.ResourceView(resource);
}
}
/**
* @extends {WebInspector.SourceFrame}
* @constructor
* @param {WebInspector.Resource} resource
*/
WebInspector.ResourceSourceFrame = function(resource)
{
this._resource = resource;
WebInspector.SourceFrame.call(this, resource);
}
WebInspector.ResourceSourceFrame.prototype = {
get resource()
{
return this._resource;
},
populateTextAreaContextMenu: function(contextMenu, lineNumber)
{
contextMenu.appendApplicableItems(this._resource);
},
__proto__: WebInspector.SourceFrame.prototype
}
/**
* @constructor
* @extends {WebInspector.View}
* @param {WebInspector.Resource} resource
*/
WebInspector.ResourceSourceFrameFallback = function(resource)
{
WebInspector.View.call(this);
this._resource = resource;
this.element.addStyleClass("fill");
this.element.addStyleClass("script-view");
this._content = this.element.createChild("div", "script-view-fallback monospace");
}
WebInspector.ResourceSourceFrameFallback.prototype = {
wasShown: function()
{
if (!this._contentRequested) {
this._contentRequested = true;
this._resource.requestContent(this._contentLoaded.bind(this));
}
},
/**
* @param {?string} content
* @param {boolean} contentEncoded
* @param {string} mimeType
*/
_contentLoaded: function(content, contentEncoded, mimeType)
{
this._content.textContent = content;
},
__proto__: WebInspector.View.prototype
}
|
WAPMADRID/server
|
wapmadrid/node_modules/grunt-node-inspector/node_modules/node-inspector/front-end/ResourceView.js
|
JavaScript
|
gpl-2.0
| 4,287 |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMultiChild
* @typechecks static-only
*/
'use strict';
var ReactComponentEnvironment = require("./ReactComponentEnvironment");
var ReactMultiChildUpdateTypes = require("./ReactMultiChildUpdateTypes");
var ReactReconciler = require("./ReactReconciler");
var ReactChildReconciler = require("./ReactChildReconciler");
/**
* Updating children of a component may trigger recursive updates. The depth is
* used to batch recursive updates to render markup more efficiently.
*
* @type {number}
* @private
*/
var updateDepth = 0;
/**
* Queue of update configuration objects.
*
* Each object has a `type` property that is in `ReactMultiChildUpdateTypes`.
*
* @type {array<object>}
* @private
*/
var updateQueue = [];
/**
* Queue of markup to be rendered.
*
* @type {array<string>}
* @private
*/
var markupQueue = [];
/**
* Enqueues markup to be rendered and inserted at a supplied index.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function enqueueMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
textContent: null,
fromIndex: null,
toIndex: toIndex
});
}
/**
* Enqueues moving an existing element to another index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function enqueueMove(parentID, fromIndex, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: toIndex
});
}
/**
* Enqueues removing an element at an index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function enqueueRemove(parentID, fromIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: null
});
}
/**
* Enqueues setting the text content.
*
* @param {string} parentID ID of the parent component.
* @param {string} textContent Text content to set.
* @private
*/
function enqueueTextContent(parentID, textContent) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
markupIndex: null,
textContent: textContent,
fromIndex: null,
toIndex: null
});
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue() {
if (updateQueue.length) {
ReactComponentEnvironment.processChildrenUpdates(
updateQueue,
markupQueue
);
clearQueue();
}
}
/**
* Clears any enqueued updates.
*
* @private
*/
function clearQueue() {
updateQueue.length = 0;
markupQueue.length = 0;
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function(nestedChildren, transaction, context) {
var children = ReactChildReconciler.instantiateChildren(
nestedChildren, transaction, context
);
this._renderedChildren = children;
var mountImages = [];
var index = 0;
for (var name in children) {
if (children.hasOwnProperty(name)) {
var child = children[name];
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(
child,
rootID,
transaction,
context
);
child._mountIndex = index;
mountImages.push(mountImage);
index++;
}
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function(nextContent) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren);
// TODO: The setTextContent operation should be enough
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChildByName(prevChildren[name], name);
}
}
// Set new text content.
this.setTextContent(nextContent);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function(nextNestedChildren, transaction, context) {
updateDepth++;
var errorThrown = true;
try {
this._updateChildren(nextNestedChildren, transaction, context);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Improve performance by isolating this hot code path from the try/catch
* block in `updateChildren`.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function(nextNestedChildren, transaction, context) {
var prevChildren = this._renderedChildren;
var nextChildren = ReactChildReconciler.updateChildren(
prevChildren, nextNestedChildren, transaction, context
);
this._renderedChildren = nextChildren;
if (!nextChildren && !prevChildren) {
return;
}
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var lastIndex = 0;
var nextIndex = 0;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (prevChild === nextChild) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
this._unmountChildByName(prevChild, name);
}
// The child must be instantiated before it's mounted.
this._mountChildByNameAtIndex(
nextChild, name, nextIndex, transaction, context
);
}
nextIndex++;
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) &&
!(nextChildren && nextChildren.hasOwnProperty(name))) {
this._unmountChildByName(prevChildren[name], name);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @internal
*/
unmountChildren: function() {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren);
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function(child, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
enqueueMove(this._rootNodeID, child._mountIndex, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function(child, mountImage) {
enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function(child) {
enqueueRemove(this._rootNodeID, child._mountIndex);
},
/**
* Sets this text content string.
*
* @param {string} textContent Text content to set.
* @protected
*/
setTextContent: function(textContent) {
enqueueTextContent(this._rootNodeID, textContent);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildByNameAtIndex: function(
child,
name,
index,
transaction,
context) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(
child,
rootID,
transaction,
context
);
child._mountIndex = index;
this.createChild(child, mountImage);
},
/**
* Unmounts a rendered child by name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @param {string} name Name of the child in `this._renderedChildren`.
* @private
*/
_unmountChildByName: function(child, name) {
this.removeChild(child);
child._mountIndex = null;
}
}
};
module.exports = ReactMultiChild;
|
jeffro-/jeffro-.github.io
|
youreeverything/node_modules/react/lib/ReactMultiChild.js
|
JavaScript
|
apache-2.0
| 12,019 |
/* skelJS v0.4 | (c) n33 | skeljs.org | MIT licensed */
skel.registerPlugin("panels",function(){var b={config:{baseZIndex:1E4,useTransform:!0,transformBreakpoints:null,speed:250,panels:{},overlays:{}},cache:{panels:{},overlays:{},body:null,window:null,pageWrapper:null,defaultWrapper:null,fixedWrapper:null,activePanel:null},eventType:"click",positions:{panels:{top:["top","left"],right:["top","right"],bottom:["bottom","left"],left:["top","left"]},overlays:{"top-left":{top:0,left:0},"top-right":{top:0,right:0},top:{top:0,left:"50%"},"top-center":{top:0,left:"50%"},
"bottom-left":{bottom:0,left:0},"bottom-right":{bottom:0,right:0},bottom:{bottom:0,left:"50%"},"bottom-center":{bottom:0,left:"50%"},left:{top:"50%",left:0},"middle-left":{top:"50%",left:0},right:{top:"50%",right:0},"middle-right":{top:"50%",right:0}}},presets:{standard:{panels:{navPanel:{breakpoints:"mobile",position:"left",style:"push",size:"80%",html:'<div data-action="navList" data-args="nav"></div>'}},overlays:{titleBar:{breakpoints:"mobile",position:"top-left",width:"100%",height:44,html:'<span class="toggle" data-action="togglePanel" data-args="navPanel"></span><span class="title" data-action="copyHTML" data-args="logo"></span>'}}}},
defaults:{config:{panel:{breakpoints:"",position:null,style:null,size:"80%",html:"",resetScroll:!0,resetForms:!0,swipeToClose:!0},overlay:{breakpoints:"",position:null,width:0,height:0,html:""}}},recalcW:function(b){var c=parseInt(b);"string"==typeof b&&"%"==b.charAt(b.length-1)&&(c=Math.floor(jQuery(window).width()*(c/100)));return c},recalcH:function(b){var c=parseInt(b);"string"==typeof b&&"%"==b.charAt(b.length-1)&&(c=Math.floor(jQuery(window).height()*(c/100)));return c},getHalf:function(b){var c=
parseInt(b);return"string"==typeof b&&"%"==b.charAt(b.length-1)?Math.floor(c/2)+"%":Math.floor(c/2)+"px"},parseSuspend:function(b){b=b.get(0);b._skel_panels_suspend&&b._skel_panels_suspend()},parseResume:function(b){b=b.get(0);b._skel_panels_resume&&b._skel_panels_resume()},parseInit:function(e){var c,d;c=e.get(0);var h=e.attr("data-action"),f=e.attr("data-args"),g,l;h&&f&&(f=f.split(","));switch(h){case "togglePanel":case "panelToggle":e.css("-webkit-tap-highlight-color","rgba(0,0,0,0)").css("cursor",
"pointer");c=function(c){c.preventDefault();c.stopPropagation();if(b.cache.activePanel)return b.cache.activePanel._skel_panels_close(),!1;jQuery(this);c=b.cache.panels[f[0]];c.is(":visible")?c._skel_panels_close():c._skel_panels_open()};"android"==b._.vars.deviceType?e.bind("click",c):e.bind(b.eventType,c);break;case "navList":g=jQuery("#"+f[0]);c=g.find("a");d=[];c.each(function(){var b=jQuery(this),c;c=Math.max(0,b.parents("li").length-1);d.push('<a class="link depth-'+c+'" href="'+b.attr("href")+
'"><span class="indent-'+c+'"></span>'+b.text()+"</a>")});0<d.length&&e.html("<nav>"+d.join("")+"</nav>");e.find(".link").css("cursor","pointer").css("display","block");break;case "copyText":g=jQuery("#"+f[0]);e.html(g.text());break;case "copyHTML":g=jQuery("#"+f[0]);e.html(g.html());break;case "moveElementContents":g=jQuery("#"+f[0]);c._skel_panels_resume=function(){g.children().each(function(){e.append(jQuery(this))})};c._skel_panels_suspend=function(){e.children().each(function(){g.append(jQuery(this))})};
c._skel_panels_resume();break;case "moveElement":g=jQuery("#"+f[0]);c._skel_panels_resume=function(){jQuery('<div id="skel-panels-tmp-'+g.attr("id")+'" />').insertBefore(g);e.append(g)};c._skel_panels_suspend=function(){jQuery("#skel-panels-tmp-"+g.attr("id")).replaceWith(g)};c._skel_panels_resume();break;case "moveCell":g=jQuery("#"+f[0]),l=jQuery("#"+f[1]),c._skel_panels_resume=function(){jQuery('<div id="skel-panels-tmp-'+g.attr("id")+'" />').insertBefore(g);e.append(g);g.css("width","auto");l&&
l._skel_panels_expandCell()},c._skel_panels_suspend=function(){jQuery("#skel-panels-tmp-"+g.attr("id")).replaceWith(g);g.css("width","");l&&l.css("width","")},c._skel_panels_resume()}},lockView:function(e){b.cache.window._skel_panels_scrollPos=b.cache.window.scrollTop();b._.vars.isTouch&&b.cache.body.css("overflow-"+e,"hidden");b.cache.pageWrapper.bind("touchstart.lock",function(c){c.preventDefault();c.stopPropagation();b.cache.activePanel&&b.cache.activePanel._skel_panels_close()});b.cache.pageWrapper.bind("click.lock",
function(c){c.preventDefault();c.stopPropagation();b.cache.activePanel&&b.cache.activePanel._skel_panels_close()});b.cache.pageWrapper.bind("scroll.lock",function(c){c.preventDefault();c.stopPropagation();b.cache.activePanel&&b.cache.activePanel._skel_panels_close()});b.cache.window.bind("orientationchange.lock",function(c){b.cache.activePanel&&b.cache.activePanel._skel_panels_close()});b._.vars.isTouch||(b.cache.window.bind("resize.lock",function(c){b.cache.activePanel&&b.cache.activePanel._skel_panels_close()}),
b.cache.window.bind("scroll.lock",function(c){b.cache.activePanel&&b.cache.activePanel._skel_panels_close()}))},unlockView:function(e){b._.vars.isTouch&&b.cache.body.css("overflow-"+e,"visible");b.cache.pageWrapper.unbind("touchstart.lock");b.cache.pageWrapper.unbind("click.lock");b.cache.pageWrapper.unbind("scroll.lock");b.cache.window.unbind("orientationchange.lock");b._.vars.isTouch||(b.cache.window.unbind("resize.lock"),b.cache.window.unbind("scroll.lock"))},resumeElement:function(e){b.cache[e.type+
"s"][e.id].find("*").each(function(){b.parseResume(jQuery(this))})},suspendElement:function(e){e=b.cache[e.type+"s"][e.id];e._skel_panels_translateOrigin();e.find("*").each(function(){b.parseSuspend(jQuery(this))})},initElement:function(e){var c=e.config,d=jQuery(e.object),h;b.cache[e.type+"s"][e.id]=d;d._skel_panels_init();d.find("*").each(function(){b.parseInit(jQuery(this))});switch(e.type){case "panel":d.addClass("skel-panels-panel").css("z-index",b.config.baseZIndex).css("position","fixed").hide();
d.find("a").css("-webkit-tap-highlight-color","rgba(0,0,0,0)").bind("click.skel-panels",function(c){if(b.cache.activePanel){c.preventDefault();c.stopPropagation();c=jQuery(this);var d=c.attr("href");b.cache.activePanel._skel_panels_close();c.hasClass("skel-panels-ignoreHref")||window.setTimeout(function(){window.location.href=d},b.config.speed+10)}});"ios"==b._.vars.deviceType&&d.find("input,select,textarea").focus(function(c){var d=jQuery(this);c.preventDefault();c.stopPropagation();window.setTimeout(function(){var c=
b.cache.window._skel_panels_scrollPos,g=b.cache.window.scrollTop()-c;b.cache.window.scrollTop(c);b.cache.activePanel.scrollTop(b.cache.activePanel.scrollTop()+g);d.hide();window.setTimeout(function(){d.show()},0)},100)});switch(c.position){case "top":case "bottom":var f="bottom"==c.position?"-":"";d.addClass("skel-panels-panel-"+c.position).data("skel-panels-panel-position",c.position).css("height",b.recalcH(c.size)).scrollTop(0);b._.vars.isTouch?d.css("overflow-y","scroll").css("-webkit-overflow-scrolling",
"touch").bind("touchstart",function(b){d._posY=b.originalEvent.touches[0].pageY;d._posX=b.originalEvent.touches[0].pageX}).bind("touchmove",function(b){b=d._posY-b.originalEvent.touches[0].pageY;var c=d.outerHeight(),e=d.get(0).scrollHeight-d.scrollTop();if(0==d.scrollTop()&&0>b||e>c-2&&e<c+2&&0<b)return!1}):d.css("overflow-y","auto");switch(c.style){default:d._skel_panels_open=function(){d._skel_panels_promote().scrollTop(0).css("left","0px").css(c.position,"-"+b.recalcH(c.size)+"px").css("height",
b.recalcH(c.size)).css("width","100%").show();c.resetScroll&&d.scrollTop(0);c.resetForms&&d._skel_panels_resetForms();b.lockView("y");window.setTimeout(function(){d.add(b.cache.fixedWrapper.children()).add(b.cache.pageWrapper)._skel_panels_translate(0,f+b.recalcH(c.size));b.cache.activePanel=d},100)},d._skel_panels_close=function(){d.find("*").blur();d.add(b.cache.pageWrapper).add(b.cache.fixedWrapper.children())._skel_panels_translateOrigin();window.setTimeout(function(){b.unlockView("y");d._skel_panels_demote().hide();
b.cache.activePanel=null},b.config.speed+50)}}break;case "left":case "right":switch(f="right"==c.position?"-":"",d.addClass("skel-panels-panel-"+c.position).data("skel-panels-panel-position",c.position).css("width",b.recalcW(c.size)).scrollTop(0),b._.vars.isTouch?d.css("overflow-y","scroll").css("-webkit-overflow-scrolling","touch").bind("touchstart",function(b){d._posY=b.originalEvent.touches[0].pageY;d._posX=b.originalEvent.touches[0].pageX}).bind("touchmove",function(b){var e=d._posX-b.originalEvent.touches[0].pageX;
b=d._posY-b.originalEvent.touches[0].pageY;var f=d.outerHeight(),h=d.get(0).scrollHeight-d.scrollTop();if(c.swipeToClose&&20>b&&-20<b&&("left"==c.position&&50<e||"right"==c.position&&-50>e))return d._skel_panels_close(),!1;if(0==d.scrollTop()&&0>b||h>f-2&&h<f+2&&0<b)return!1}):d.css("overflow-y","auto"),c.style){default:d._skel_panels_open=function(){d._skel_panels_promote().scrollTop(0).css("top","0px").css(c.position,"-"+b.recalcW(c.size)+"px").css("width",b.recalcW(c.size)).css("height","100%").show();
c.resetScroll&&d.scrollTop(0);c.resetForms&&d._skel_panels_resetForms();b.lockView("x");window.setTimeout(function(){d.add(b.cache.fixedWrapper.children()).add(b.cache.pageWrapper)._skel_panels_translate(f+b.recalcW(c.size),0);b.cache.activePanel=d},100)};d._skel_panels_close=function(){d.find("*").blur();d.add(b.cache.fixedWrapper.children()).add(b.cache.pageWrapper)._skel_panels_translateOrigin();window.setTimeout(function(){b.unlockView("x");d._skel_panels_demote().hide();b.cache.activePanel=null},
b.config.speed+50)};break;case "reveal":d._skel_panels_open=function(){b.cache.fixedWrapper._skel_panels_promote(2);b.cache.pageWrapper._skel_panels_promote(1);d.scrollTop(0).css("top","0px").css(c.position,"0px").css("width",b.recalcW(c.size)).css("height","100%").show();c.resetScroll&&d.scrollTop(0);c.resetForms&&d._skel_panels_resetForms();b.lockView("x");window.setTimeout(function(){b.cache.pageWrapper.add(b.cache.fixedWrapper.children())._skel_panels_translate(f+b.recalcW(c.size),0);b.cache.activePanel=
d},100)},d._skel_panels_close=function(){d.find("*").blur();b.cache.pageWrapper.add(b.cache.fixedWrapper.children())._skel_panels_translateOrigin();window.setTimeout(function(){b.unlockView("x");d.hide();b.cache.pageWrapper._skel_panels_demote();b.cache.pageWrapper._skel_panels_demote();b.cache.activePanel=null},b.config.speed+50)}}}break;case "overlay":d.css("z-index",b.config.baseZIndex).css("position","fixed").addClass("skel-panels-overlay"),d.css("width",c.width).css("height",c.height),(h=b.positions.overlays[c.position])||
(c.position="top-left",h=b.positions.overlays[c.position]),d.addClass("skel-panels-overlay-"+c.position).data("skel-panels-overlay-position",c.position),b._.iterate(h,function(e){d.css(e,h[e]);"50%"==h[e]&&("top"==e?d.css("margin-top","-"+b.getHalf(c.height)):"left"==e&&d.css("margin-left","-"+b.getHalf(c.width)))})}},initElements:function(e){var c,d,h,f=[];b._.iterate(b.config[e+"s"],function(g){c={};b._.extend(c,b.defaults.config[e]);b._.extend(c,b.config[e+"s"][g]);b.config[e+"s"][g]=c;d=b._.newDiv(c.html);
d.id=g;d.className="skel-panels-"+e;c.html||(f[g]=d);h=c.breakpoints?c.breakpoints.split(","):b._.breakpointList;b._.iterate(h,function(f){f=b._.cacheBreakpointElement(h[f],g,d,"overlay"==e?"skel_panels_fixedWrapper":"skel_panels_defaultWrapper",2);f.config=c;f.initialized=!1;f.type=e;f.onAttach=function(){this.initialized?b.resumeElement(this):(b.initElement(this),this.initialized=!0)};f.onDetach=function(){b.suspendElement(this)}})});b._.DOMReady(function(){var c,d;b._.iterate(f,function(b){c=jQuery("#"+
b);d=jQuery(f[b]);c.children().appendTo(d);c.remove()})})},initJQueryUtilityFuncs:function(){jQuery.fn._skel_panels_promote=function(c){this._zIndex=this.css("z-index");this.css("z-index",b.config.baseZIndex+(c?c:1));return this};jQuery.fn._skel_panels_demote=function(){this._zIndex&&(this.css("z-index",this._zIndex),this._zIndex=null);return this};jQuery.fn._skel_panels_xcssValue=function(b,d){return jQuery(this).css(b,"-moz-"+d).css(b,"-webkit-"+d).css(b,"-o-"+d).css(b,"-ms-"+d).css(b,d)};jQuery.fn._skel_panels_xcssProperty=
function(b,d){return jQuery(this).css("-moz-"+b,d).css("-webkit-"+b,d).css("-o-"+b,d).css("-ms-"+b,d).css(b,d)};jQuery.fn._skel_panels_xcss=function(b,d){return jQuery(this).css("-moz-"+b,"-moz-"+d).css("-webkit-"+b,"-webkit-"+d).css("-o-"+b,"-o-"+d).css("-ms-"+b,"-ms-"+d).css(b,d)};jQuery.fn._skel_panels_resetForms=function(){var b=jQuery(this);jQuery(this).find("form").each(function(){this.reset()});return b};jQuery.fn._skel_panels_initializeCell=function(){var b=jQuery(this);b.attr("class").match(/(\s+|^)([0-9]+)u(\s+|$)/)&&
b.data("cell-size",parseInt(RegExp.$2))};jQuery.fn._skel_panels_expandCell=function(){var b=jQuery(this),d=12;b.parent().children().each(function(){var b=jQuery(this).attr("class");b&&b.match(/(\s+|^)([0-9]+)u(\s+|$)/)&&(d-=parseInt(RegExp.$2))});0<d&&(b._skel_panels_initializeCell(),b.css("width",100*((b.data("cell-size")+d)/12)+"%"))};if(b.config.useTransform&&10<=b._.vars.IEVersion&&(!b.config.transformBreakpoints||b._.hasActive(b.config.transformBreakpoints.split(","))))jQuery.fn._skel_panels_translateOrigin=
function(){return jQuery(this)._skel_panels_translate(0,0)},jQuery.fn._skel_panels_translate=function(b,d){return jQuery(this).css("transform","translate("+b+"px, "+d+"px)")},jQuery.fn._skel_panels_init=function(){return jQuery(this).css("backface-visibility","hidden").css("perspective","500")._skel_panels_xcss("transition","transform "+b.config.speed/1E3+"s ease-in-out")};else{var e=[];b.cache.window.resize(function(){if(0!=b.config.speed){var c=b.config.speed;b.config.speed=0;window.setTimeout(function(){b.config.speed=
c;e=[]},c)}});jQuery.fn._skel_panels_translateOrigin=function(){for(var c=0;c<this.length;c++){var d=this[c],h=jQuery(d);e[d.id]&&h.animate(e[d.id],b.config.speed,"swing",function(){b._.iterate(e[d.id],function(b){h.css(b,e[d.id][b])});b.cache.body.css("overflow-x","visible");b.cache.pageWrapper.css("width","auto").css("padding-bottom",0)})}return jQuery(this)};jQuery.fn._skel_panels_translate=function(c,d){var h,f,g,l;c=parseInt(c);d=parseInt(d);0!=c?(b.cache.body.css("overflow-x","hidden"),b.cache.pageWrapper.css("width",
b.cache.window.width())):g=function(){b.cache.body.css("overflow-x","visible");b.cache.pageWrapper.css("width","auto")};0>d?b.cache.pageWrapper.css("padding-bottom",Math.abs(d)):l=function(){b.cache.pageWrapper.css("padding-bottom",0)};for(h=0;h<this.length;h++){var k=this[h],n=jQuery(k),m;if(!e[k.id])if(m=b.positions.overlays[n.data("skel-panels-overlay-position")])e[k.id]=m;else if(m=b.positions.panels[n.data("skel-panels-panel-position")])for(e[k.id]={},f=0;m[f];f++)e[k.id][m[f]]=parseInt(n.css(m[f]));
else m=n.position(),e[k.id]={top:m.top,left:m.left};a={};b._.iterate(e[k.id],function(f){var g;switch(f){case "top":g=b.recalcH(e[k.id][f])+d;break;case "bottom":g=b.recalcH(e[k.id][f])-d;break;case "left":g=b.recalcW(e[k.id][f])+c;break;case "right":g=b.recalcW(e[k.id][f])-c}a[f]=g});n.animate(a,b.config.speed,"swing",function(){g&&g();l&&l()})}return jQuery(this)};jQuery.fn._skel_panels_init=function(){return jQuery(this).css("position","absolute")}}},initObjects:function(){b.cache.window=jQuery(window);
b.cache.window.load(function(){0==b.cache.window.scrollTop()&&window.scrollTo(0,1)});b._.DOMReady(function(){b.cache.body=jQuery("body");b.cache.body.wrapInner('<div id="skel-panels-pageWrapper" />');b.cache.pageWrapper=jQuery("#skel-panels-pageWrapper");b.cache.pageWrapper.css("position","relative").css("left","0").css("right","0").css("top","0")._skel_panels_init();b.cache.defaultWrapper=jQuery('<div id="skel-panels-defaultWrapper" />').appendTo(b.cache.body);b.cache.defaultWrapper.css("height",
"100%");b.cache.fixedWrapper=jQuery('<div id="skel-panels-fixedWrapper" />').appendTo(b.cache.body);b.cache.fixedWrapper.css("position","relative");jQuery(".skel-panels-fixed").appendTo(b.cache.fixedWrapper);b._.registerLocation("skel_panels_defaultWrapper",b.cache.defaultWrapper[0]);b._.registerLocation("skel_panels_fixedWrapper",b.cache.fixedWrapper[0]);b._.registerLocation("skel_panels_pageWrapper",b.cache.pageWrapper[0])})},initIncludes:function(){b._.DOMReady(function(){jQuery(".skel-panels-include").each(function(){b.parseInit(jQuery(this))})})},
init:function(){b.eventType=b._.vars.isTouch?"touchend":"click";b.initObjects();b.initJQueryUtilityFuncs();b.initElements("overlay");b.initElements("panel");b.initIncludes();b._.updateState()}};return b}());
|
AKSW/Sparqlify-Website
|
www/www/js/skel-panels.min.js
|
JavaScript
|
apache-2.0
| 16,451 |
/**
* Provides live preview facilities for the event date format fields, akin
* to (and using the same ajax mechanism as) the date format preview in WP's
* general settings screen.
*/
jQuery( document ).ready( function( $ ) {
// Whenever the input field for a date format changes, update the matching
// live preview area
$( ".live-date-preview" ).siblings( "input" ).change( function() {
var $format_field = $( this );
var new_format = $format_field.val();
var $preview_field = $format_field.siblings( ".live-date-preview" );
/**
* Update the preview field when we get our response back from WP.
*/
var show_update = function( preview_text ) {
preview_text = $( "<div/>" ).html( preview_text ).text(); // Escaping!
$preview_field.html( preview_text );
}
// Before making the request, show the spinner (this should naturally be "wiped"
// when the response is rendered)
$preview_field.append( "<span class='spinner'></span>" );
$preview_field.find( ".spinner" ).css( "visibility", "visible" );
var request = {
action: "date_format",
date: new_format
}
$.post( ajaxurl, request, show_update, "text" );
} );
} );
|
pdpfsug/wp_raga10
|
wp_raga10/wp-content/plugins/the-events-calendar/vendor/tickets/common/src/resources/js/admin-date-preview.js
|
JavaScript
|
agpl-3.0
| 1,173 |
var which = require('which');
var spawnSync = require('child_process').spawnSync;
module.exports.detect = function(gulp) {
var DART_SDK = false;
try {
which.sync('dart');
if (process.platform === 'win32') {
DART_SDK = {
ANALYZER: 'dartanalyzer.bat',
DARTDOCGEN: 'dartdoc.bat',
DARTFMT: 'dartfmt.bat',
PUB: 'pub.bat',
VM: 'dart.exe'
};
} else {
DART_SDK = {
ANALYZER: 'dartanalyzer',
DARTDOCGEN: 'dartdoc',
DARTFMT: 'dartfmt',
PUB: 'pub',
VM: 'dart'
};
}
console.log('Dart SDK detected:');
} catch (e) {
console.log('Dart SDK is not available, Dart tasks will be skipped.');
var gulpTaskFn = gulp.task.bind(gulp);
gulp.task = function (name, deps, fn) {
if (name.indexOf('.dart') === -1) {
return gulpTaskFn(name, deps, fn);
} else {
return gulpTaskFn(name, function() {
console.log('Dart SDK is not available. Skipping task: ' + name);
});
}
};
}
return DART_SDK;
}
module.exports.logVersion = function(dartSdk) {
console.log('DART SDK:') ;
console.log('- dart: ' + spawnSync(dartSdk.VM, ['--version']).stderr.toString().replace(/\n/g, ''));
console.log('- pub: ' + spawnSync(dartSdk.PUB, ['--version']).stdout.toString().replace(/\n/g, ''));
}
|
resalisbury/angular
|
tools/build/dart.js
|
JavaScript
|
apache-2.0
| 1,355 |
๏ปฟ/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar","et",{euro:"Euromรคrk",lsquo:"Alustav รผhekordne jutumรคrk",rsquo:"Lรตpetav รผhekordne jutumรคrk",ldquo:"Alustav kahekordne jutumรคrk",rdquo:"Lรตpetav kahekordne jutumรคrk",ndash:"Enn-kriips",mdash:"Emm-kriips",iexcl:"Pรถรถratud hรผรผumรคrk",cent:"Sendimรคrk",pound:"Naela mรคrk",curren:"Valuutamรคrk",yen:"Jeeni mรคrk",brvbar:"Katkestatud kriips",sect:"Lรตigu mรคrk",uml:"Tรคpid",copy:"Autoriรตiguse mรคrk",ordf:"Feminine ordinal indicator",laquo:"Left-pointing double angle quotation mark",
not:"Ei-mรคrk",reg:"Registered sign",macr:"Macron",deg:"Kraadimรคrk",sup2:"รlaindeks kaks",sup3:"รlaindeks kolm",acute:"Acute accent",micro:"Mikro-mรคrk",para:"Pilcrow sign",middot:"Keskpunkt",cedil:"Cedilla",sup1:"รlaindeks รผks",ordm:"Masculine ordinal indicator",raquo:"Right-pointing double angle quotation mark",frac14:"Vulgar fraction one quarter",frac12:"Vulgar fraction one half",frac34:"Vulgar fraction three quarters",iquest:"Inverted question mark",Agrave:"Latin capital letter A with grave accent",
Aacute:"Latin capital letter A with acute accent",Acirc:"Latin capital letter A with circumflex",Atilde:"Ladina suur A tildega",Auml:"Latin capital letter A with diaeresis",Aring:"Latin capital letter A with ring above",AElig:"Latin Capital letter ร",Ccedil:"Latin capital letter C with cedilla",Egrave:"Latin capital letter E with grave accent",Eacute:"Latin capital letter E with acute accent",Ecirc:"Latin capital letter E with circumflex",Euml:"Latin capital letter E with diaeresis",Igrave:"Latin capital letter I with grave accent",
Iacute:"Latin capital letter I with acute accent",Icirc:"Latin capital letter I with circumflex",Iuml:"Latin capital letter I with diaeresis",ETH:"Latin capital letter Eth",Ntilde:"Latin capital letter N with tilde",Ograve:"Latin capital letter O with grave accent",Oacute:"Latin capital letter O with acute accent",Ocirc:"Latin capital letter O with circumflex",Otilde:"Latin capital letter O with tilde",Ouml:"Tรคppidega ladina suur O",times:"Multiplication sign",Oslash:"Latin capital letter O with stroke",
Ugrave:"Latin capital letter U with grave accent",Uacute:"Latin capital letter U with acute accent",Ucirc:"Kandilise katusega suur ladina U",Uuml:"Tรคppidega ladina suur U",Yacute:"Latin capital letter Y with acute accent",THORN:"Latin capital letter Thorn",szlig:"Ladina vรคike terav s",agrave:"Latin small letter a with grave accent",aacute:"Latin small letter a with acute accent",acirc:"Kandilise katusega ladina vรคike a",atilde:"Tildega ladina vรคike a",auml:"Tรคppidega ladina vรคike a",aring:"Latin small letter a with ring above",
aelig:"Latin small letter รฆ",ccedil:"Latin small letter c with cedilla",egrave:"Latin small letter e with grave accent",eacute:"Latin small letter e with acute accent",ecirc:"Latin small letter e with circumflex",euml:"Latin small letter e with diaeresis",igrave:"Latin small letter i with grave accent",iacute:"Latin small letter i with acute accent",icirc:"Latin small letter i with circumflex",iuml:"Latin small letter i with diaeresis",eth:"Latin small letter eth",ntilde:"Latin small letter n with tilde",
ograve:"Latin small letter o with grave accent",oacute:"Latin small letter o with acute accent",ocirc:"Latin small letter o with circumflex",otilde:"Latin small letter o with tilde",ouml:"Latin small letter o with diaeresis",divide:"Jagamismรคrk",oslash:"Latin small letter o with stroke",ugrave:"Latin small letter u with grave accent",uacute:"Latin small letter u with acute accent",ucirc:"Latin small letter u with circumflex",uuml:"Latin small letter u with diaeresis",yacute:"Latin small letter y with acute accent",
thorn:"Latin small letter thorn",yuml:"Latin small letter y with diaeresis",OElig:"Latin capital ligature OE",oelig:"Latin small ligature oe",372:"Latin capital letter W with circumflex",374:"Latin capital letter Y with circumflex",373:"Latin small letter w with circumflex",375:"Latin small letter y with circumflex",sbquo:"Single low-9 quotation mark",8219:"Single high-reversed-9 quotation mark",bdquo:"Double low-9 quotation mark",hellip:"Horizontal ellipsis",trade:"Kaubamรคrgi mรคrk",9658:"Black right-pointing pointer",
bull:"Kuul",rarr:"Nool paremale",rArr:"Topeltnool paremale",hArr:"Topeltnool vasakule",diams:"Black diamond suit",asymp:"Ligikaudu vรตrdne"});
|
DeadLockMk1/Yogurt
|
yogurt/protected/extensions/booster/assets/ckeditor/plugins/specialchar/dialogs/lang/et.js
|
JavaScript
|
gpl-2.0
| 4,488 |
๏ปฟCKEDITOR.plugins.setLang("autoembed","en-au",{embeddingInProgress:"Trying to embed pasted URL...",embeddingFailed:"This URL could not be automatically embedded."});
|
maiconpinto/cakephp-adminlte-theme
|
webroot/bower_components/ckeditor/plugins/autoembed/lang/en-au.js
|
JavaScript
|
mit
| 167 |
// ramda.js
// https://github.com/CrossEye/ramda
// (c) 2013-2014 Scott Sauyet and Michael Hurley
// Ramda may be freely distributed under the MIT license.
// Ramda
// -----
// A practical functional library for Javascript programmers. Ramda is a collection of tools to make it easier to
// use Javascript as a functional programming language. (The name is just a silly play on `lambda`.)
// Basic Setup
// -----------
// Uses a technique from the [Universal Module Definition][umd] to wrap this up for use in Node.js or in the browser,
// with or without an AMD-style loader.
//
// [umd]: https://github.com/umdjs/umd/blob/master/returnExports.js
(function(factory) {
if (typeof exports === 'object') {
module.exports = factory(this);
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
this.R = this.ramda = factory(this);
}
}(function() {
'use strict';
// This object is what is actually returned, with all the exposed functions attached as properties.
/**
* A practical functional library for Javascript programmers.
*
* @namespace R
*/
// jscs:disable disallowQuotedKeysInObjects
var R = {'version': '0.5.0'};
// jscs:enable disallowQuotedKeysInObjects
// Internal Functions and Properties
// ---------------------------------
/**
* An optimized, private array `slice` implementation.
*
* @private
* @category Internal
* @param {Arguments|Array} args The array or arguments object to consider.
* @param {number} [from=0] The array index to slice from, inclusive.
* @param {number} [to=args.length] The array index to slice to, exclusive.
* @return {Array} A new, sliced array.
* @example
*
* _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3]
*
* var firstThreeArgs = function(a, b, c, d) {
* return _slice(arguments, 0, 3);
* };
* firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3]
*/
function _slice(args, from, to) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return _slice(args, 0, args.length);
case 2: return _slice(args, from, args.length);
default:
var length = to - from, list = new Array(length), idx = -1;
while (++idx < length) {
list[idx] = args[from + idx];
}
return list;
}
}
/**
* Private `concat` function to merge two array-like objects.
*
* @private
* @category Internal
* @param {Array|Arguments} [set1=[]] An array-like object.
* @param {Array|Arguments} [set2=[]] An array-like object.
* @return {Array} A new, merged array.
* @example
*
* concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
*/
var concat = function _concat(set1, set2) {
set1 = set1 || [];
set2 = set2 || [];
var length1 = set1.length,
length2 = set2.length,
result = new Array(length1 + length2);
for (var idx = 0; idx < length1; idx++) {
result[idx] = set1[idx];
}
for (idx = 0; idx < length2; idx++) {
result[idx + length1] = set2[idx];
}
return result;
};
// Private reference to toString function.
var toString = Object.prototype.toString;
/**
* Tests whether or not an object is an array.
*
* @private
* @category Internal
* @param {*} val The object to test.
* @return {boolean} `true` if `val` is an array, `false` otherwise.
* @example
*
* isArray([]); //=> true
* isArray(true); //=> false
* isArray({}); //=> false
*/
var isArray = Array.isArray || function _isArray(val) {
return val && val.length >= 0 && toString.call(val) === '[object Array]';
};
/**
* Tests whether or not an object is similar to an array.
*
* @func
* @category Type
* @category List
* @param {*} val The object to test.
* @return {boolean} `true` if `val` has a numeric length property; `false` otherwise.
* @example
*
* R.isArrayLike([]); //=> true
* R.isArrayLike(true); //=> false
* R.isArrayLike({}); //=> false
* R.isArrayLike({length: 10}); //=> true
*/
R.isArrayLike = function isArrayLike(x) {
return isArray(x) || (
!!x &&
typeof x === 'object' &&
!(x instanceof String) &&
(
!!(x.nodeType === 1 && x.length) ||
x.length >= 0
)
);
};
var NO_ARGS_EXCEPTION = new TypeError('Function called with no arguments');
/**
* Optimized internal two-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} curried function
* @example
*
* var addTwo = function(a, b) {
* return a + b;
* };
*
* var curriedAddTwo = curry2(addTwo);
*/
function curry2(fn) {
return function(a, b) {
switch (arguments.length) {
case 0:
throw NO_ARGS_EXCEPTION;
case 1:
return function(b) {
return fn(a, b);
};
default:
return fn(a, b);
}
};
}
/**
* Optimized internal three-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} curried function
* @example
*
* var addThree = function(a, b, c) {
* return a + b + c;
* };
*
* var curriedAddThree = curry3(addThree);
*/
function curry3(fn) {
return function(a, b, c) {
switch (arguments.length) {
case 0:
throw NO_ARGS_EXCEPTION;
case 1:
return curry2(function(b, c) {
return fn(a, b, c);
});
case 2:
return function(c) {
return fn(a, b, c);
};
default:
return fn(a, b, c);
}
};
}
if (typeof Object.defineProperty === 'function') {
try {
Object.defineProperty(R, '_', {writable: false, value: void 0});
} catch (e) {}
}
var _ = R._; void _;// This intentionally left `undefined`.
/**
* Converts a function into something like an infix operation, meaning that
* when called with a single argument, that argument is applied to the
* second position, sort of a curry-right. This allows for more natural
* processing of functions which are really binary operators.
*
* @memberOf R
* @category Functions
* @param {function} fn The operation to adjust
* @return {function} A new function that acts somewhat like an infix operator.
* @example
*
* var div = R.op(function (a, b) {
* return a / b;
* });
*
* div(6, 3); //=> 2
* div(6, _)(3); //=> 2 // note: `_` here is just an `undefined` value. You could use `void 0` instead
* div(3)(6); //=> 2
*/
var op = R.op = function op(fn) {
var length = fn.length;
if (length < 2) {throw new Error('Expected binary function.');}
var left = curry(fn), right = curry(R.flip(fn));
return function(a, b) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return right(a);
case 2: return (b === R._) ? left(a) : left.apply(null, arguments);
default: return left.apply(null, arguments);
}
};
};
/**
* Creates a new version of `fn` with given arity that, when invoked,
* will return either:
* - A new function ready to accept one or more of `fn`'s remaining arguments, if all of
* `fn`'s expected arguments have not yet been provided
* - `fn`'s result if all of its expected arguments have been provided
*
* This function is useful in place of `curry`, when the arity of the
* function to curry cannot be determined from its signature, e.g. if it's
* a variadic function.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (* -> a) -> (* -> a)
* @param {number} fnArity The arity for the returned function.
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curry
* @example
*
* var addFourNumbers = function() {
* return R.sum([].slice.call(arguments, 0, 4));
* };
*
* var curriedAddFourNumbers = R.curryN(4, addFourNumbers);
* var f = curriedAddFourNumbers(1, 2);
* var g = f(3);
* g(4);//=> 10
*/
var curryN = R.curryN = function curryN(length, fn) {
return (function recurry(args) {
return arity(Math.max(length - (args && args.length || 0), 0), function() {
if (arguments.length === 0) { throw NO_ARGS_EXCEPTION; }
var newArgs = concat(args, arguments);
if (newArgs.length >= length) {
return fn.apply(this, newArgs);
} else {
return recurry(newArgs);
}
});
}([]));
};
/**
* Creates a new version of `fn` that, when invoked, will return either:
* - A new function ready to accept one or more of `fn`'s remaining arguments, if all of
* `fn`'s expected arguments have not yet been provided
* - `fn`'s result if all of its expected arguments have been provided
*
* @func
* @memberOf R
* @category Function
* @sig (* -> a) -> (* -> a)
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curryN
* @example
*
* var addFourNumbers = function(a, b, c, d) {
* return a + b + c + d;
* };
*
* var curriedAddFourNumbers = R.curry(addFourNumbers);
* var f = curriedAddFourNumbers(1, 2);
* var g = f(3);
* g(4);//=> 10
*/
var curry = R.curry = function curry(fn) {
return curryN(fn.length, fn);
};
/**
* Private function that determines whether or not a provided object has a given method.
* Does not ignore methods stored on the object's prototype chain. Used for dynamically
* dispatching Ramda methods to non-Array objects.
*
* @private
* @category Internal
* @param {string} methodName The name of the method to check for.
* @param {Object} obj The object to test.
* @return {boolean} `true` has a given method, `false` otherwise.
* @example
*
* var person = { name: 'John' };
* person.shout = function() { alert(this.name); };
*
* hasMethod('shout', person); //=> true
* hasMethod('foo', person); //=> false
*/
var hasMethod = function _hasMethod(methodName, obj) {
return obj && !isArray(obj) && typeof obj[methodName] === 'function';
};
/**
* Similar to hasMethod, this checks whether a function has a [methodname]
* function. If it isn't an array it will execute that function otherwise it will
* default to the ramda implementation.
*
* @private
* @category Internal
* @param {Function} fn ramda implemtation
* @param {String} methodname property to check for a custom implementation
* @return {Object} whatever the return value of the method is
*/
function checkForMethod(methodname, fn) {
return function(a, b, c) {
var length = arguments.length;
var obj = arguments[length - 1],
callBound = obj && !isArray(obj) && typeof obj[methodname] === 'function';
switch (arguments.length) {
case 0: return fn();
case 1: return callBound ? obj[methodname]() : fn(a);
case 2: return callBound ? obj[methodname](a) : fn(a, b);
case 3: return callBound ? obj[methodname](a, b) : fn(a, b, c);
}
};
}
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
* parameters. Any extraneous parameters will not be passed to the supplied function.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (* -> a) -> (* -> a)
* @param {number} n The desired arity of the new function.
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity `n`.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.nAry(1, takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only `n` arguments are passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
var nAry = R.nAry = function(n, fn) {
switch (n) {
case 0: return function() {return fn.call(this);};
case 1: return function(a0) {return fn.call(this, a0);};
case 2: return function(a0, a1) {return fn.call(this, a0, a1);};
case 3: return function(a0, a1, a2) {return fn.call(this, a0, a1, a2);};
case 4: return function(a0, a1, a2, a3) {return fn.call(this, a0, a1, a2, a3);};
case 5: return function(a0, a1, a2, a3, a4) {return fn.call(this, a0, a1, a2, a3, a4);};
case 6: return function(a0, a1, a2, a3, a4, a5) {return fn.call(this, a0, a1, a2, a3, a4, a5);};
case 7: return function(a0, a1, a2, a3, a4, a5, a6) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6);};
case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);};
case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8);};
case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);};
default: return fn; // TODO: or throw?
}
};
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly 1
* parameter. Any extraneous parameters will not be passed to the supplied function.
*
* @func
* @memberOf R
* @category Function
* @sig (* -> b) -> (a -> b)
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 1.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.unary(takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only 1 argument is passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
R.unary = function _unary(fn) {
return nAry(1, fn);
};
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly 2
* parameters. Any extraneous parameters will not be passed to the supplied function.
*
* @func
* @memberOf R
* @category Function
* @sig (* -> c) -> (a, b -> c)
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 2.
* @example
*
* var takesThreeArgs = function(a, b, c) {
* return [a, b, c];
* };
* takesThreeArgs.length; //=> 3
* takesThreeArgs(1, 2, 3); //=> [1, 2, 3]
*
* var takesTwoArgs = R.binary(takesThreeArgs);
* takesTwoArgs.length; //=> 2
* // Only 2 arguments are passed to the wrapped function
* takesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
*/
var binary = R.binary = function _binary(fn) {
return nAry(2, fn);
};
/**
* Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
* parameters. Unlike `nAry`, which passes only `n` arguments to the wrapped function,
* functions produced by `arity` will pass all provided arguments to the wrapped function.
*
* @func
* @memberOf R
* @sig (Number, (* -> *)) -> (* -> *)
* @category Function
* @param {number} n The desired arity of the returned function.
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is
* guaranteed to be of arity `n`.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.arity(1, takesTwoArgs);
* takesOneArg.length; //=> 1
* // All arguments are passed through to the wrapped function
* takesOneArg(1, 2); //=> [1, 2]
*/
var arity = R.arity = function(n, fn) {
switch (n) {
case 0: return function() {return fn.apply(this, arguments);};
case 1: return function(a0) {void a0; return fn.apply(this, arguments);};
case 2: return function(a0, a1) {void a1; return fn.apply(this, arguments);};
case 3: return function(a0, a1, a2) {void a2; return fn.apply(this, arguments);};
case 4: return function(a0, a1, a2, a3) {void a3; return fn.apply(this, arguments);};
case 5: return function(a0, a1, a2, a3, a4) {void a4; return fn.apply(this, arguments);};
case 6: return function(a0, a1, a2, a3, a4, a5) {void a5; return fn.apply(this, arguments);};
case 7: return function(a0, a1, a2, a3, a4, a5, a6) {void a6; return fn.apply(this, arguments);};
case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {void a7; return fn.apply(this, arguments);};
case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {void a8; return fn.apply(this, arguments);};
case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {void a9; return fn.apply(this, arguments);};
default: return fn; // TODO: or throw?
}
};
/**
* Turns a named method of an object (or object prototype) into a function that can be
* called directly. Passing the optional `len` parameter restricts the returned function to
* the initial `len` parameters of the method.
*
* The returned function is curried and accepts `len + 1` parameters (or `method.length + 1`
* when `len` is not specified), and the final parameter is the target object.
*
* @func
* @memberOf R
* @category Function
* @sig (String, Object, Number) -> (* -> *)
* @param {string} name The name of the method to wrap.
* @param {Object} obj The object to search for the `name` method.
* @param [len] The desired arity of the wrapped method.
* @return {Function} A new function or `undefined` if the specified method is not found.
* @example
*
* var charAt = R.invoker('charAt', String.prototype);
* charAt(6, 'abcdefghijklm'); //=> 'g'
*
* var join = R.invoker('join', Array.prototype);
* var firstChar = charAt(0);
* join('', R.map(firstChar, ['light', 'ampliifed', 'stimulated', 'emission', 'radiation']));
* //=> 'laser'
*/
var invoker = R.invoker = function _invoker(name, obj, len) {
var method = obj[name];
var length = len === void 0 ? method.length : len;
return method && curryN(length + 1, function() {
if (arguments.length) {
var target = Array.prototype.pop.call(arguments);
var targetMethod = target[name];
if (targetMethod == method) {
return targetMethod.apply(target, arguments);
}
}
});
};
/**
* Accepts a function `fn` and any number of transformer functions and returns a new
* function. When the new function is invoked, it calls the function `fn` with parameters
* consisting of the result of calling each supplied handler on successive arguments to the
* new function. For example:
*
* ```javascript
* var useWithExample = R.useWith(someFn, transformerFn1, transformerFn2);
*
* // This invocation:
* useWithExample('x', 'y');
* // Is functionally equivalent to:
* someFn(transformerFn1('x'), transformerFn2('y'))
* ```
*
* If more arguments are passed to the returned function than transformer functions, those
* arguments are passed directly to `fn` as additional parameters. If you expect additional
* arguments that don't need to be transformed, although you can ignore them, it's best to
* pass an identity function so that the new function reports the correct arity.
*
* @func
* @memberOf R
* @category Function
* @sig ((* -> *), (* -> *)...) -> (* -> *)
* @param {Function} fn The function to wrap.
* @param {...Function} transformers A variable number of transformer functions
* @return {Function} The wrapped function.
* @example
*
* var double = function(y) { return y * 2; };
* var square = function(x) { return x * x; };
* var add = function(a, b) { return a + b; };
* // Adds any number of arguments together
* var addAll = function() {
* return R.reduce(add, 0, arguments);
* };
*
* // Basic example
* var addDoubleAndSquare = R.useWith(addAll, double, square);
*
* //โ
addAll(double(10), square(5));
* addDoubleAndSquare(10, 5); //=> 45
*
* // Example of passing more arguments than transformers
* //โ
addAll(double(10), square(5), 100);
* addDoubleAndSquare(10, 5, 100); //=> 145
*
* // But if you're expecting additional arguments that don't need transformation, it's best
* // to pass transformer functions so the resulting function has the correct arity
* var addDoubleAndSquareWithExtraParams = R.useWith(addAll, double, square, R.identity);
* //โ
addAll(double(10), square(5), R.identity(100));
* addDoubleAndSquare(10, 5, 100); //=> 145
*/
var useWith = R.useWith = function _useWith(fn /*, transformers */) {
var transformers = _slice(arguments, 1);
var tlen = transformers.length;
return curry(arity(tlen, function() {
var args = [], idx = -1;
while (++idx < tlen) {
args.push(transformers[idx](arguments[idx]));
}
return fn.apply(this, args.concat(_slice(arguments, tlen)));
}));
};
/**
* Iterate over an input `list`, calling a provided function `fn` for each element in the
* list.
*
* `fn` receives one argument: *(value)*.
*
* Note: `R.forEach` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.forEach` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
*
* Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original
* array. In some libraries this function is named `each`.
*
* @func
* @memberOf R
* @category List
* @sig (a -> *) -> [a] -> [a]
* @param {Function} fn The function to invoke. Receives one argument, `value`.
* @param {Array} list The list to iterate over.
* @return {Array} The original list.
* @example
*
* var printXPlusFive = function(x) { console.log(x + 5); };
* R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3]
* //-> 6
* //-> 7
* //-> 8
*/
function forEach(fn, list) {
var idx = -1, len = list.length;
while (++idx < len) {
fn(list[idx]);
}
// i can't bear not to return *something*
return list;
}
R.forEach = curry2(forEach);
/**
* Like `forEach`, but but passes additional parameters to the predicate function.
*
* `fn` receives three arguments: *(value, index, list)*.
*
* Note: `R.forEach.idx` does not skip deleted or unassigned indices (sparse arrays),
* unlike the native `Array.prototype.forEach` method. For more details on this behavior,
* see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
*
* Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original
* array. In some libraries this function is named `each`.
*
* @func
* @memberOf R
* @category List
* @sig (a, i, [a] -> ) -> [a] -> [a]
* @param {Function} fn The function to invoke. Receives three arguments:
* (`value`, `index`, `list`).
* @param {Array} list The list to iterate over.
* @return {Array} The original list.
* @alias forEach.idx
* @example
*
* // Note that having access to the original `list` allows for
* // mutation. While you *can* do this, it's very un-functional behavior:
* var plusFive = function(num, idx, list) { list[idx] = num + 5 };
* R.forEach.idx(plusFive, [1, 2, 3]); //=> [6, 7, 8]
*/
R.forEach.idx = curry2(function forEachIdx(fn, list) {
var idx = -1, len = list.length;
while (++idx < len) {
fn(list[idx], idx, list);
}
// i can't bear not to return *something*
return list;
});
/**
* Creates a shallow copy of an array.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> [a]
* @param {Array} list The list to clone.
* @return {Array} A new copy of the original list.
* @example
*
* var numbers = [1, 2, 3];
* var numbersClone = R.clone(numbers); //=> [1, 2, 3]
* numbers === numbersClone; //=> false
*
* // Note that this is a shallow clone--it does not clone complex values:
* var objects = [{}, {}, {}];
* var objectsClone = R.clone(objects);
* objects[0] === objectsClone[0]; //=> true
*/
var clone = R.clone = function _clone(list) {
return _slice(list);
};
// Core Functions
// --------------
//
/**
* Reports whether an array is empty.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> Boolean
* @param {Array} list The array to consider.
* @return {boolean} `true` if the `list` argument has a length of 0 or
* if `list` is a falsy value (e.g. undefined).
* @example
*
* R.isEmpty([1, 2, 3]); //=> false
* R.isEmpty([]); //=> true
* R.isEmpty(); //=> true
* R.isEmpty(null); //=> true
*/
function isEmpty(list) {
return !list || !list.length;
}
R.isEmpty = isEmpty;
/**
* Returns a new list with the given element at the front, followed by the contents of the
* list.
*
* @func
* @memberOf R
* @category Array
* @sig a -> [a] -> [a]
* @param {*} el The item to add to the head of the output list.
* @param {Array} list The array to add to the tail of the output list.
* @return {Array} A new array.
* @example
*
* R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum']
*/
R.prepend = curry2(function prepend(el, list) {
return concat([el], list);
});
/**
* @func
* @memberOf R
* @category Array
* @see R.prepend
*/
R.cons = R.prepend;
/**
* Returns the first element in a list.
* In some libraries this function is named `first`.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> a
* @param {Array} [list=[]] The array to consider.
* @return {*} The first element of the list, or `undefined` if the list is empty.
* @example
*
* R.head(['fi', 'fo', 'fum']); //=> 'fi'
*/
R.head = function head(list) {
list = list || [];
return list[0];
};
/**
* @func
* @memberOf R
* @category Array
* @see R.head
*/
R.car = R.head;
/**
* Returns the last element from a list.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> a
* @param {Array} [list=[]] The array to consider.
* @return {*} The last element of the list, or `undefined` if the list is empty.
* @example
*
* R.last(['fi', 'fo', 'fum']); //=> 'fum'
*/
R.last = function _last(list) {
list = list || [];
return list[list.length - 1];
};
/**
* Returns all but the first element of a list. If the list provided has the `tail` method,
* it will instead return `list.tail()`.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> [a]
* @param {Array} [list=[]] The array to consider.
* @return {Array} A new array containing all but the first element of the input list, or an
* empty list if the input list is a falsy value (e.g. `undefined`).
* @example
*
* R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum']
*/
R.tail = checkForMethod('tail', function(list) {
list = list || [];
return (list.length > 1) ? _slice(list, 1) : [];
});
/**
* @func
* @memberOf R
* @category Array
* @see R.tail
*/
R.cdr = R.tail;
/**
* Returns a new list containing the contents of the given list, followed by the given
* element.
*
* @func
* @memberOf R
* @category Array
* @sig a -> [a] -> [a]
* @param {*} el The element to add to the end of the new list.
* @param {Array} list The list whose contents will be added to the beginning of the output
* list.
* @return {Array} A new list containing the contents of the old list followed by `el`.
* @example
*
* R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']
* R.append('tests', []); //=> ['tests']
* R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]
*/
var append = R.append = curry2(function _append(el, list) {
return concat(list, [el]);
});
/**
* @func
* @memberOf R
* @category Array
* @see R.append
*/
R.push = R.append;
/**
* Returns a new list consisting of the elements of the first list followed by the elements
* of the second.
*
* @func
* @memberOf R
* @category Array
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The first list to merge.
* @param {Array} list2 The second set to merge.
* @return {Array} A new array consisting of the contents of `list1` followed by the
* contents of `list2`. If, instead of an {Array} for `list1`, you pass an
* object with a `concat` method on it, `concat` will call `list1.concat`
* and it the value of `list2`.
* @example
*
* R.concat([], []); //=> []
* R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
* R.concat('ABC', 'DEF'); // 'ABCDEF'
*/
R.concat = curry2(function(set1, set2) {
if (isArray(set2)) {
return concat(set1, set2);
} else if (R.is(String, set1)) {
return set1.concat(set2);
} else if (hasMethod('concat', set2)) {
return set2.concat(set1);
} else {
throw new TypeError("can't concat " + typeof set2);
}
});
/**
* A function that does nothing but return the parameter supplied to it. Good as a default
* or placeholder function.
*
* @func
* @memberOf R
* @category Core
* @sig a -> a
* @param {*} x The value to return.
* @return {*} The input value, `x`.
* @example
*
* R.identity(1); //=> 1
*
* var obj = {};
* R.identity(obj) === obj; //=> true
*/
var identity = R.identity = function _I(x) {
return x;
};
/**
* @func
* @memberOf R
* @category Core
* @see R.identity
*/
R.I = R.identity;
/**
* Calls an input function `n` times, returning an array containing the results of those
* function calls.
*
* `fn` is passed one argument: The current value of `n`, which begins at `0` and is
* gradually incremented to `n - 1`.
*
* @func
* @memberOf R
* @category List
* @sig (i -> a) -> i -> [a]
* @param {Function} fn The function to invoke. Passed one argument, the current value of `n`.
* @param {number} n A value between `0` and `n - 1`. Increments after each function call.
* @return {Array} An array containing the return values of all calls to `fn`.
* @example
*
* R.times(R.identity, 5); //=> [0, 1, 2, 3, 4]
*/
R.times = curry2(function _times(fn, n) {
var list = new Array(n);
var idx = -1;
while (++idx < n) {
list[idx] = fn(idx);
}
return list;
});
/**
* Returns a fixed list of size `n` containing a specified identical value.
*
* @func
* @memberOf R
* @category Array
* @sig a -> n -> [a]
* @param {*} value The value to repeat.
* @param {number} n The desired size of the output list.
* @return {Array} A new array containing `n` `value`s.
* @example
*
* R.repeatN('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi']
*
* var obj = {};
* var repeatedObjs = R.repeatN(obj, 5); //=> [{}, {}, {}, {}, {}]
* repeatedObjs[0] === repeatedObjs[1]; //=> true
*/
R.repeatN = curry2(function _repeatN(value, n) {
return R.times(R.always(value), n);
});
// Function functions :-)
// ----------------------
//
// These functions make new functions out of old ones.
// --------
/**
* Basic, right-associative composition function. Accepts two functions and returns the
* composite function; this composite function represents the operation `var h = f(g(x))`,
* where `f` is the first argument, `g` is the second argument, and `x` is whatever
* argument(s) are passed to `h`.
*
* This function's main use is to build the more general `compose` function, which accepts
* any number of functions.
*
* @private
* @category Function
* @param {Function} f A function.
* @param {Function} g A function.
* @return {Function} A new function that is the equivalent of `f(g(x))`.
* @example
*
* var double = function(x) { return x * 2; };
* var square = function(x) { return x * x; };
* var squareThenDouble = internalCompose(double, square);
*
* squareThenDouble(5); //โ
double(square(5)) => 50
*/
function internalCompose(f, g) {
return function() {
return f.call(this, g.apply(this, arguments));
};
}
/**
* Creates a new function that runs each of the functions supplied as parameters in turn,
* passing the return value of each function invocation to the next function invocation,
* beginning with whatever arguments were passed to the initial invocation.
*
* Note that `compose` is a right-associative function, which means the functions provided
* will be invoked in order from right to left. In the example `var h = compose(f, g)`,
* the function `h` is equivalent to `f( g(x) )`, where `x` represents the arguments
* originally passed to `h`.
*
* @func
* @memberOf R
* @category Function
* @sig ((y -> z), (x -> y), ..., (b -> c), (a... -> b)) -> (a... -> z)
* @param {...Function} functions A variable number of functions.
* @return {Function} A new function which represents the result of calling each of the
* input `functions`, passing the result of each function call to the next, from
* right to left.
* @example
*
* var triple = function(x) { return x * 3; };
* var double = function(x) { return x * 2; };
* var square = function(x) { return x * x; };
* var squareThenDoubleThenTriple = R.compose(triple, double, square);
*
* //โ
triple(double(square(5)))
* squareThenDoubleThenTriple(5); //=> 150
*/
var compose = R.compose = function _compose() {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return arguments[0];
default:
var idx = arguments.length - 1, fn = arguments[idx], length = fn.length;
while (idx--) {
fn = internalCompose(arguments[idx], fn);
}
return arity(length, fn);
}
};
/**
* Creates a new function that runs each of the functions supplied as parameters in turn,
* passing the return value of each function invocation to the next function invocation,
* beginning with whatever arguments were passed to the initial invocation.
*
* `pipe` is the mirror version of `compose`. `pipe` is left-associative, which means that
* each of the functions provided is executed in order from left to right.
*
* In some libraries this function is named `sequence`.
* @func
* @memberOf R
* @category Function
* @sig ((a... -> b), (b -> c), ..., (x -> y), (y -> z)) -> (a... -> z)
* @param {...Function} functions A variable number of functions.
* @return {Function} A new function which represents the result of calling each of the
* input `functions`, passing the result of each function call to the next, from
* right to left.
* @example
*
* var triple = function(x) { return x * 3; };
* var double = function(x) { return x * 2; };
* var square = function(x) { return x * x; };
* var squareThenDoubleThenTriple = R.pipe(square, double, triple);
*
* //โ
triple(double(square(5)))
* squareThenDoubleThenTriple(5); //=> 150
*/
R.pipe = function _pipe() {
return compose.apply(this, _slice(arguments).reverse());
};
/**
* Returns a new function much like the supplied one, except that the first two arguments'
* order is reversed.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> b -> c -> ... -> z) -> (b -> a -> c -> ... -> z)
* @param {Function} fn The function to invoke with its first two parameters reversed.
* @return {*} The result of invoking `fn` with its first two parameters' order reversed.
* @example
*
* var mergeThree = function(a, b, c) {
* return ([]).concat(a, b, c);
* };
*
* mergeThree(1, 2, 3); //=> [1, 2, 3]
*
* R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3]
*/
var flip = R.flip = function _flip(fn) {
return function(a, b) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return function(b) { return fn.apply(this, [b, a].concat(_slice(arguments, 1))); };
default: return fn.apply(this, concat([b, a], _slice(arguments, 2)));
}
};
};
/**
* Accepts as its arguments a function and any number of values and returns a function that,
* when invoked, calls the original function with all of the values prepended to the
* original function's arguments list. In some libraries this function is named `applyLeft`.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> b -> ... -> i -> j -> ... -> m -> n) -> a -> b-> ... -> i -> (j -> ... -> m -> n)
* @param {Function} fn The function to invoke.
* @param {...*} [args] Arguments to prepend to `fn` when the returned function is invoked.
* @return {Function} A new function wrapping `fn`. When invoked, it will call `fn`
* with `args` prepended to `fn`'s arguments list.
* @example
*
* var multiply = function(a, b) { return a * b; };
* var double = R.lPartial(multiply, 2);
* double(2); //=> 4
*
* var greet = function(salutation, title, firstName, lastName) {
* return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
* };
* var sayHello = R.lPartial(greet, 'Hello');
* var sayHelloToMs = R.lPartial(sayHello, 'Ms.');
* sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!'
*/
R.lPartial = function _lPartial(fn /*, args */) {
var args = _slice(arguments, 1);
return arity(Math.max(fn.length - args.length, 0), function() {
return fn.apply(this, concat(args, arguments));
});
};
/**
* Accepts as its arguments a function and any number of values and returns a function that,
* when invoked, calls the original function with all of the values appended to the original
* function's arguments list.
*
* Note that `rPartial` is the opposite of `lPartial`: `rPartial` fills `fn`'s arguments
* from the right to the left. In some libraries this function is named `applyRight`.
*
* @func
* @memberOf R
* @category Function
* @sig (a -> b-> ... -> i -> j -> ... -> m -> n) -> j -> ... -> m -> n -> (a -> b-> ... -> i)
* @param {Function} fn The function to invoke.
* @param {...*} [args] Arguments to append to `fn` when the returned function is invoked.
* @return {Function} A new function wrapping `fn`. When invoked, it will call `fn` with
* `args` appended to `fn`'s arguments list.
* @example
*
* var greet = function(salutation, title, firstName, lastName) {
* return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
* };
* var greetMsJaneJones = R.rPartial(greet, 'Ms.', 'Jane', 'Jones');
*
* greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!'
*/
R.rPartial = function _rPartial(fn) {
var args = _slice(arguments, 1);
return arity(Math.max(fn.length - args.length, 0), function() {
return fn.apply(this, concat(arguments, args));
});
};
/**
* Creates a new function that, when invoked, caches the result of calling `fn` for a given
* argument set and returns the result. Subsequent calls to the memoized `fn` with the same
* argument set will not result in an additional call to `fn`; instead, the cached result
* for that set of arguments will be returned.
*
* Note that this version of `memoize` effectively handles only string and number
* parameters. Also note that it does not work on variadic functions.
*
* @func
* @memberOf R
* @category Function
* @sig (a... -> b) -> (a... -> b)
* @param {Function} fn The function to be wrapped by `memoize`.
* @return {Function} Returns a memoized version of `fn`.
* @example
*
* var numberOfCalls = 0;
* var trackedAdd = function(a, b) {
* numberOfCalls += 1;
* return a + b;
* };
* var memoTrackedAdd = R.memoize(trackedAdd);
*
* memoTrackedAdd(1, 2); //=> 3
* numberOfCalls; //=> 1
* memoTrackedAdd(1, 2); //=> 3
* numberOfCalls; //=> 1
* memoTrackedAdd(2, 3); //=> 5
* numberOfCalls; //=> 2
*
* // Note that argument order matters
* memoTrackedAdd(2, 1); //=> 3
* numberOfCalls; //=> 3
*/
R.memoize = function _memoize(fn) {
if (!fn.length) {
return once(fn);
}
var cache = {};
return function() {
if (!arguments.length) {return;}
var position = foldl(function(cache, arg) {
return cache[arg] || (cache[arg] = {});
}, cache, _slice(arguments, 0, arguments.length - 1));
var arg = arguments[arguments.length - 1];
return (position[arg] || (position[arg] = fn.apply(this, arguments)));
};
};
/**
* Accepts a function `fn` and returns a function that guards invocation of `fn` such that
* `fn` can only ever be called once, no matter how many times the returned function is
* invoked.
*
* @func
* @memberOf R
* @category Function
* @sig (a... -> b) -> (a... -> b)
* @param {Function} fn The function to wrap in a call-only-once wrapper.
* @return {Function} The wrapped function.
* @example
*
* var addOneOnce = R.once(function(x){ return x + 1; });
* addOneOnce(10); //=> 11
* addOneOnce(addOneOnce(50)); //=> 11
*/
var once = R.once = function _once(fn) {
var called = false, result;
return function() {
if (called) {
return result;
}
called = true;
result = fn.apply(this, arguments);
return result;
};
};
/**
* Wrap a function inside another to allow you to make adjustments to the parameters, or do
* other processing either before the internal function is called or with its results.
*
* @func
* @memberOf R
* @category Function
* ((* -> *) -> ((* -> *), a...) -> (*, a... -> *)
* @param {Function} fn The function to wrap.
* @param {Function} wrapper The wrapper function.
* @return {Function} The wrapped function.
* @example
*
* var slashify = R.wrap(R.flip(add)('/'), function(f, x) {
* return R.match(/\/$/, x) ? x : f(x);
* });
*
* slashify('a'); //=> 'a/'
* slashify('a/'); //=> 'a/'
*/
R.wrap = function _wrap(fn, wrapper) {
return function() {
return wrapper.apply(this, concat([fn], arguments));
};
};
/**
* Wraps a constructor function inside a curried function that can be called with the same
* arguments and returns the same type. The arity of the function returned is specified
* to allow using variadic constructor functions.
*
* NOTE: Does not work with some built-in objects such as Date.
*
* @func
* @memberOf R
* @category Function
* @sig Number -> (* -> {*}) -> (* -> {*})
* @param {number} n The arity of the constructor function.
* @param {Function} Fn The constructor function to wrap.
* @return {Function} A wrapped, curried constructor function.
* @example
*
* // Variadic constructor function
* var Widget = function() {
* this.children = Array.prototype.slice.call(arguments);
* // ...
* };
* Widget.prototype = {
* // ...
* };
* var allConfigs = {
* // ...
* };
* R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets
*/
var constructN = R.constructN = curry2(function _constructN(n, Fn) {
var f = function() {
var Temp = function() {}, inst, ret;
Temp.prototype = Fn.prototype;
inst = new Temp();
ret = Fn.apply(inst, arguments);
return Object(ret) === ret ? ret : inst;
};
return n > 1 ? curry(nAry(n, f)) : f;
});
/**
* Wraps a constructor function inside a curried function that can be called with the same
* arguments and returns the same type.
*
* NOTE: Does not work with some built-in objects such as Date.
*
* @func
* @memberOf R
* @category Function
* @sig (* -> {*}) -> (* -> {*})
* @param {Function} Fn The constructor function to wrap.
* @return {Function} A wrapped, curried constructor function.
* @example
*
* // Constructor function
* var Widget = function(config) {
* // ...
* };
* Widget.prototype = {
* // ...
* };
* var allConfigs = {
* // ...
* };
* R.map(R.construct(Widget), allConfigs); // a list of Widgets
*/
R.construct = function _construct(Fn) {
return constructN(Fn.length, Fn);
};
/**
* Accepts three functions and returns a new function. When invoked, this new function will
* invoke the first function, `after`, passing as its arguments the results of invoking the
* second and third functions with whatever arguments are passed to the new function.
*
* For example, a function produced by `converge` is equivalent to:
*
* ```javascript
* var h = R.converge(e, f, g);
* h(1, 2); //โ
e( f(1, 2), g(1, 2) )
* ```
*
* @func
* @memberOf R
* @category Function
* @sig ((a, b -> c) -> (((* -> a), (* -> b), ...) -> c)
* @param {Function} after A function. `after` will be invoked with the return values of
* `fn1` and `fn2` as its arguments.
* @param {Function} fn1 A function. It will be invoked with the arguments passed to the
* returned function. Afterward, its resulting value will be passed to `after` as
* its first argument.
* @param {Function} fn2 A function. It will be invoked with the arguments passed to the
* returned function. Afterward, its resulting value will be passed to `after` as
* its second argument.
* @return {Function} A new function.
* @example
*
* var add = function(a, b) { return a + b; };
* var multiply = function(a, b) { return a * b; };
* var subtract = function(a, b) { return a - b; };
*
* //โ
multiply( add(1, 2), subtract(1, 2) );
* R.converge(multiply, add, subtract)(1, 2); //=> -3
*/
R.converge = function(after) {
var fns = _slice(arguments, 1);
return function() {
var args = arguments;
return after.apply(this, map(function(fn) {
return fn.apply(this, args);
}, fns));
};
};
// List Functions
// --------------
//
// These functions operate on logical lists, here plain arrays. Almost all of these are curried, and the list
// parameter comes last, so you can create a new function by supplying the preceding arguments, leaving the
// list parameter off. For instance:
//
// // skip third parameter
// var checkAllPredicates = reduce(andFn, alwaysTrue);
// // ... given suitable definitions of odd, lt20, gt5
// var test = checkAllPredicates([odd, lt20, gt5]);
// // test(7) => true, test(9) => true, test(10) => false,
// // test(3) => false, test(21) => false,
// --------
/**
* Returns a single item by iterating through the list, successively calling the iterator
* function and passing it an accumulator value and the current value from the array, and
* then passing the result to the next call.
*
* The iterator function receives two values: *(acc, value)*
*
* Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.reduce` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,b -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var numbers = [1, 2, 3];
* var add = function(a, b) {
* return a + b;
* };
*
* R.reduce(add, 10, numbers); //=> 16
*/
R.reduce = curry3(function _reduce(fn, acc, list) {
var idx = -1, len = list.length;
while (++idx < len) {
acc = fn(acc, list[idx]);
}
return acc;
});
/**
* @func
* @memberOf R
* @category List
* @see R.reduce
*/
var foldl = R.foldl = R.reduce;
/**
* Like `reduce`, but passes additional parameters to the predicate function.
*
* The iterator function receives four values: *(acc, value, index, list)*
*
* Note: `R.reduce.idx` does not skip deleted or unassigned indices (sparse arrays),
* unlike the native `Array.prototype.reduce` method. For more details on this behavior,
* see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,b,i,[b] -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives four values: the accumulator, the
* current element from `list`, that element's index, and the entire `list` itself.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @alias reduce.idx
* @example
*
* var letters = ['a', 'b', 'c'];
* var objectify = function(accObject, elem, idx, list) {
* accObject[elem] = idx;
* return accObject;
* };
*
* R.reduce.idx(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 }
*/
R.reduce.idx = curry3(function _reduceIdx(fn, acc, list) {
var idx = -1, len = list.length;
while (++idx < len) {
acc = fn(acc, list[idx], idx, list);
}
return acc;
});
/**
* @func
* @memberOf R
* @category List
* @alias foldl.idx
* @see R.reduce.idx
*/
R.foldl.idx = R.reduce.idx;
/**
* Returns a single item by iterating through the list, successively calling the iterator
* function and passing it an accumulator value and the current value from the array, and
* then passing the result to the next call.
*
* Similar to `reduce`, except moves through the input list from the right to the left.
*
* The iterator function receives two values: *(acc, value)*
*
* Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.reduce` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,b -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var pairs = [ ['a', 1], ['b', 2], ['c', 3] ];
* var flattenPairs = function(acc, pair) {
* return acc.concat(pair);
* };
*
* R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ]
*/
R.reduceRight = curry3(checkForMethod('reduceRight', function _reduceRight(fn, acc, list) {
var idx = list.length;
while (idx--) {
acc = fn(acc, list[idx]);
}
return acc;
}));
/**
* @func
* @memberOf R
* @category List
* @see R.reduceRight
*/
R.foldr = R.reduceRight;
/**
* Like `reduceRight`, but passes additional parameters to the predicate function. Moves through
* the input list from the right to the left.
*
* The iterator function receives four values: *(acc, value, index, list)*.
*
* Note: `R.reduceRight.idx` does not skip deleted or unassigned indices (sparse arrays),
* unlike the native `Array.prototype.reduce` method. For more details on this behavior,
* see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,b,i,[b] -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives four values: the accumulator, the
* current element from `list`, that element's index, and the entire `list` itself.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @alias reduceRight.idx
* @example
*
* var letters = ['a', 'b', 'c'];
* var objectify = function(accObject, elem, idx, list) {
* accObject[elem] = idx;
* return accObject;
* };
*
* R.reduceRight.idx(objectify, {}, letters); //=> { 'c': 2, 'b': 1, 'a': 0 }
*/
R.reduceRight.idx = curry3(function _reduceRightIdx(fn, acc, list) {
var idx = list.length;
while (idx--) {
acc = fn(acc, list[idx], idx, list);
}
return acc;
});
/**
* @func
* @memberOf R
* @category List
* @alias foldr.idx
* @see R.reduceRight.idx
*/
R.foldr.idx = R.reduceRight.idx;
/**
* Builds a list from a seed value. Accepts an iterator function, which returns either false
* to stop iteration or an array of length 2 containing the value to add to the resulting
* list and the seed to be used in the next call to the iterator function.
*
* The iterator function receives one argument: *(seed)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> [b]) -> * -> [b]
* @param {Function} fn The iterator function. receives one argument, `seed`, and returns
* either false to quit iteration or an array of length two to proceed. The element
* at index 0 of this array will be added to the resulting array, and the element
* at index 1 will be passed to the next call to `fn`.
* @param {*} seed The seed value.
* @return {Array} The final list.
* @example
*
* var f = function(n) { return n > 50 ? false : [-n, n + 10] };
* R.unfoldr(f, 10); //=> [-10, -20, -30, -40, -50]
*/
R.unfoldr = curry2(function _unfoldr(fn, seed) {
var pair = fn(seed);
var result = [];
while (pair && pair.length) {
result.push(pair[0]);
pair = fn(pair[1]);
}
return result;
});
/**
* Returns a new list, constructed by applying the supplied function to every element of the
* supplied list.
*
* Note: `R.map` does not skip deleted or unassigned indices (sparse arrays), unlike the
* native `Array.prototype.map` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
*
* @func
* @memberOf R
* @category List
* @sig (a -> b) -> [a] -> [b]
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {Array} list The list to be iterated over.
* @return {Array} The new list.
* @example
*
* var double = function(x) {
* return x * 2;
* };
*
* R.map(double, [1, 2, 3]); //=> [2, 4, 6]
*/
function map(fn, list) {
var idx = -1, len = list.length, result = new Array(len);
while (++idx < len) {
result[idx] = fn(list[idx]);
}
return result;
}
R.map = curry2(checkForMethod('map', map));
/**
* Like `map`, but but passes additional parameters to the mapping function.
* `fn` receives three arguments: *(value, index, list)*.
*
* Note: `R.map.idx` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.map` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
*
* @func
* @memberOf R
* @category List
* @sig (a,i,[b] -> b) -> [a] -> [b]
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {Array} list The list to be iterated over.
* @return {Array} The new list.
* @alias map.idx
* @example
*
* var squareEnds = function(elt, idx, list) {
* if (idx === 0 || idx === list.length - 1) {
* return elt * elt;
* }
* return elt;
* };
*
* R.map.idx(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81]
*/
R.map.idx = curry2(function _mapIdx(fn, list) {
var idx = -1, len = list.length, result = new Array(len);
while (++idx < len) {
result[idx] = fn(list[idx], idx, list);
}
return result;
});
/**
* Map, but for objects. Creates an object with the same keys as `obj` and values
* generated by running each property of `obj` through `fn`. `fn` is passed one argument:
* *(value)*.
*
* @func
* @memberOf R
* @category List
* @sig (v -> v) -> {k: v} -> {k: v}
* @param {Function} fn A function called for each property in `obj`. Its return value will
* become a new property on the return object.
* @param {Object} obj The object to iterate over.
* @return {Object} A new object with the same keys as `obj` and values that are the result
* of running each property through `fn`.
* @example
*
* var values = { x: 1, y: 2, z: 3 };
* var double = function(num) {
* return num * 2;
* };
*
* R.mapObj(double, values); //=> { x: 2, y: 4, z: 6 }
*/
// TODO: consider mapObj.key in parallel with mapObj.idx. Also consider folding together with `map` implementation.
R.mapObj = curry2(function _mapObject(fn, obj) {
return foldl(function(acc, key) {
acc[key] = fn(obj[key]);
return acc;
}, {}, keys(obj));
});
/**
* Like `mapObj`, but but passes additional arguments to the predicate function. The
* predicate function is passed three arguments: *(value, key, obj)*.
*
* @func
* @memberOf R
* @category List
* @sig (v, k, {k: v} -> v) -> {k: v} -> {k: v}
* @param {Function} fn A function called for each property in `obj`. Its return value will
* become a new property on the return object.
* @param {Object} obj The object to iterate over.
* @return {Object} A new object with the same keys as `obj` and values that are the result
* of running each property through `fn`.
* @alias mapObj.idx
* @example
*
* var values = { x: 1, y: 2, z: 3 };
* var prependKeyAndDouble = function(num, key, obj) {
* return key + (num * 2);
* };
*
* R.mapObj.idx(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' }
*/
R.mapObj.idx = curry2(function mapObjectIdx(fn, obj) {
return foldl(function(acc, key) {
acc[key] = fn(obj[key], key, obj);
return acc;
}, {}, keys(obj));
});
/**
* ap applies a list of functions to a list of values.
*
* @func
* @memberOf R
* @category Function
* @sig [f] -> [a] -> [f a]
* @param {Array} fns An array of functions
* @param {Array} vs An array of values
* @return the value of applying each the function `fns` to each value in `vs`
* @example
*
* R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6]
*/
R.ap = curry2(function _ap(fns, vs) {
return hasMethod('ap', fns) ? fns.ap(vs) : foldl(function(acc, fn) {
return concat(acc, map(fn, vs));
}, [], fns);
});
/**
*
* `of` wraps any object in an Array. This implementation is compatible with the
* Fantasy-land Applicative spec, and will work with types that implement that spec.
* Note this `of` is different from the ES6 `of`; See
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of
*
* @func
* @memberOf R
* @category Function
* @sig a -> [a]
* @param {*} x any value
* @return [x]
* @example
*
* R.of(1); //=> [1]
* R.of([2]); //=> [[2]]
* R.of({}); //=> [{}]
*/
R.of = function _of(x, container) {
return (hasMethod('of', container)) ? container.of(x) : [x];
};
/**
* `empty` wraps any object in an array. This implementation is compatible with the
* Fantasy-land Monoid spec, and will work with types that implement that spec.
*
* @func
* @memberOf R
* @category Function
* @sig * -> []
* @return {Array} an empty array
* @example
*
* R.empty([1,2,3,4,5]); //=> []
*/
R.empty = function _empty(x) {
return (hasMethod('empty', x)) ? x.empty() : [];
};
/**
* `chain` maps a function over a list and concatenates the results.
* This implementation is compatible with the
* Fantasy-land Chain spec, and will work with types that implement that spec.
* `chain` is also known as `flatMap` in some libraries
*
* @func
* @memberOf R
* @category List
* @sig (a -> [b]) -> [a] -> [b]
* @param {Function} fn
* @param {Array} list
* @return {Array}
* @example
*
* var duplicate = function(n) {
* return [n, n];
* };
* R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
*
*/
R.chain = curry2(checkForMethod('chain', function _chain(f, list) {
return unnest(map(f, list));
}));
/**
* Returns the number of elements in the array by returning `list.length`.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> Number
* @param {Array} list The array to inspect.
* @return {number} The size of the array.
* @example
*
* R.size([]); //=> 0
* R.size([1, 2, 3]); //=> 3
*/
R.size = function _size(list) {
return list.length;
};
/**
* @func
* @memberOf R
* @category List
* @see R.size
*/
R.length = R.size;
/**
* Returns a new list containing only those items that match a given predicate function.
* The predicate function is passed one argument: *(value)*.
*
* Note that `R.filter` does not skip deleted or unassigned indices, unlike the native
* `Array.prototype.filter` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Description
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @example
*
* var isEven = function(n) {
* return n % 2 === 0;
* };
* R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]
*/
var filter = function _filter(fn, list) {
var idx = -1, len = list.length, result = [];
while (++idx < len) {
if (fn(list[idx])) {
result.push(list[idx]);
}
}
return result;
};
R.filter = curry2(checkForMethod('filter', filter));
/**
* Like `filter`, but passes additional parameters to the predicate function. The predicate
* function is passed three arguments: *(value, index, list)*.
*
* @func
* @memberOf R
* @category List
* @sig (a, i, [a] -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @alias filter.idx
* @example
*
* var lastTwo = function(val, idx, list) {
* return list.length - idx <= 2;
* };
* R.filter.idx(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9]
*/
function filterIdx(fn, list) {
var idx = -1, len = list.length, result = [];
while (++idx < len) {
if (fn(list[idx], idx, list)) {
result.push(list[idx]);
}
}
return result;
}
R.filter.idx = curry2(filterIdx);
/**
* Similar to `filter`, except that it keeps only values for which the given predicate
* function returns falsy. The predicate function is passed one argument: *(value)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @example
*
* var isOdd = function(n) {
* return n % 2 === 1;
* };
* R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]
*/
var reject = function _reject(fn, list) {
return filter(not(fn), list);
};
R.reject = curry2(reject);
/**
* Like `reject`, but passes additional parameters to the predicate function. The predicate
* function is passed three arguments: *(value, index, list)*.
*
* @func
* @memberOf R
* @category List
* @sig (a, i, [a] -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @alias reject.idx
* @example
*
* var lastTwo = function(val, idx, list) {
* return list.length - idx <= 2;
* };
*
* R.reject.idx(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3]
*/
R.reject.idx = curry2(function _rejectIdx(fn, list) {
return filterIdx(not(fn), list);
});
/**
* Returns a new list containing the first `n` elements of a given list, passing each value
* to the supplied predicate function, and terminating when the predicate function returns
* `false`. Excludes the element that caused the predicate function to fail. The predicate
* function is passed one argument: *(value)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @example
*
* var isNotFour = function(x) {
* return !(x === 4);
* };
*
* R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3]
*/
R.takeWhile = curry2(checkForMethod('takeWhile', function(fn, list) {
var idx = -1, len = list.length;
while (++idx < len && fn(list[idx])) {}
return _slice(list, 0, idx);
}));
/**
* Returns a new list containing the first `n` elements of the given list. If
* `n > * list.length`, returns a list of `list.length` elements.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a]
* @param {number} n The number of elements to return.
* @param {Array} list The array to query.
* @return {Array} A new array containing the first elements of `list`.
*/
R.take = curry2(checkForMethod('take', function(n, list) {
return _slice(list, 0, Math.min(n, list.length));
}));
/**
* Returns a new list containing the last `n` elements of a given list, passing each value
* to the supplied predicate function, beginning when the predicate function returns
* `true`. Excludes the element that caused the predicate function to fail. The predicate
* function is passed one argument: *(value)*.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @example
*
* var isTwo = function(x) {
* return x === 2;
* };
*
* R.skipUntil(isTwo, [1, 2, 3, 4]); //=> [2, 3, 4]
*/
R.skipUntil = curry2(function _skipUntil(fn, list) {
var idx = -1, len = list.length;
while (++idx < len && !fn(list[idx])) {}
return _slice(list, idx);
});
/**
* Returns a new list containing all but the first `n` elements of the given `list`.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a]
* @param {number} n The number of elements of `list` to skip.
* @param {Array} list The array to consider.
* @return {Array} The last `n` elements of `list`.
* @example
*
* R.skip(3, [1,2,3,4,5,6,7]); //=> [4,5,6,7]
*/
R.skip = curry2(checkForMethod('skip', function _skip(n, list) {
if (n < list.length) {
return _slice(list, n);
} else {
return [];
}
}));
/**
* Returns the first element of the list which matches the predicate, or `undefined` if no
* element matches.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> a | undefined
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Object} The element found, or `undefined`.
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}];
* R.find(R.propEq('a', 2))(xs); //=> {a: 2}
* R.find(R.propEq('a', 4))(xs); //=> undefined
*/
R.find = curry2(function find(fn, list) {
var idx = -1;
var len = list.length;
while (++idx < len) {
if (fn(list[idx])) {
return list[idx];
}
}
});
/**
* Returns the index of the first element of the list which matches the predicate, or `-1`
* if no element matches.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Number
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {number} The index of the element found, or `-1`.
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}];
* R.findIndex(R.propEq('a', 2))(xs); //=> 1
* R.findIndex(R.propEq('a', 4))(xs); //=> -1
*/
R.findIndex = curry2(function _findIndex(fn, list) {
var idx = -1;
var len = list.length;
while (++idx < len) {
if (fn(list[idx])) {
return idx;
}
}
return -1;
});
/**
* Returns the last element of the list which matches the predicate, or `undefined` if no
* element matches.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> a | undefined
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Object} The element found, or `undefined`.
* @example
*
* var xs = [{a: 1, b: 0}, {a:1, b: 1}];
* R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1}
* R.findLast(R.propEq('a', 4))(xs); //=> undefined
*/
R.findLast = curry2(function _findLast(fn, list) {
var idx = list.length;
while (idx--) {
if (fn(list[idx])) {
return list[idx];
}
}
});
/**
* Returns the index of the last element of the list which matches the predicate, or
* `-1` if no element matches.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Number
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {number} The index of the element found, or `-1`.
* @example
*
* var xs = [{a: 1, b: 0}, {a:1, b: 1}];
* R.findLastIndex(R.propEq('a', 1))(xs); //=> 1
* R.findLastIndex(R.propEq('a', 4))(xs); //=> -1
*/
R.findLastIndex = curry2(function _findLastIndex(fn, list) {
var idx = list.length;
while (idx--) {
if (fn(list[idx])) {
return idx;
}
}
return -1;
});
/**
* Returns `true` if all elements of the list match the predicate, `false` if there are any
* that don't.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {boolean} `true` if the predicate is satisfied by every element, `false`
* otherwise
* @example
*
* var lessThan2 = R.flip(R.lt)(2);
* var lessThan3 = R.flip(R.lt)(3);
* var xs = R.range(1, 3);
* xs; //=> [1, 2]
* R.every(lessThan2)(xs); //=> false
* R.every(lessThan3)(xs); //=> true
*/
function every(fn, list) {
var idx = -1;
while (++idx < list.length) {
if (!fn(list[idx])) {
return false;
}
}
return true;
}
R.every = curry2(every);
/**
* Returns `true` if at least one of elements of the list match the predicate, `false`
* otherwise.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {boolean} `true` if the predicate is satisfied by at least one element, `false`
* otherwise
* @example
*
* var lessThan0 = R.flip(R.lt)(0);
* var lessThan2 = R.flip(R.lt)(2);
* var xs = R.range(1, 3);
* xs; //=> [1, 2]
* R.some(lessThan0)(xs); //=> false
* R.some(lessThan2)(xs); //=> true
*/
function some(fn, list) {
var idx = -1;
while (++idx < list.length) {
if (fn(list[idx])) {
return true;
}
}
return false;
}
R.some = curry2(some);
/**
* Internal implementation of `indexOf`.
* Returns the position of the first occurrence of an item in an array
* (by strict equality),
* or -1 if the item is not included in the array.
*
* @private
* @category Internal
* @param {Array} The array to search
* @param {*} item the item to find in the Array
* @param {Number} from (optional) the index to start searching the Array
* @return {Number} the index of the found item, or -1
*
*/
var indexOf = function _indexOf(list, item, from) {
var idx = 0, length = list.length;
if (typeof from == 'number') {
idx = from < 0 ? Math.max(0, length + from) : from;
}
for (; idx < length; idx++) {
if (list[idx] === item) {
return idx;
}
}
return -1;
};
/**
* Internal implementation of `lastIndexOf`.
* Returns the position of the last occurrence of an item in an array
* (by strict equality),
* or -1 if the item is not included in the array.
*
* @private
* @category Internal
* @param {Array} The array to search
* @param {*} item the item to find in the Array
* @param {Number} from (optional) the index to start searching the Array
* @return {Number} the index of the found item, or -1
*
*/
var lastIndexOf = function _lastIndexOf(list, item, from) {
var idx = list.length;
if (typeof from == 'number') {
idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
}
while (--idx >= 0) {
if (list[idx] === item) {
return idx;
}
}
return -1;
};
/**
* Returns the position of the first occurrence of an item in an array
* (by strict equality),
* or -1 if the item is not included in the array.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} list The array to search in.
* @return {Number} the index of the target, or -1 if the target is not found.
*
* @example
*
* R.indexOf(3, [1,2,3,4]); //=> 2
* R.indexOf(10, [1,2,3,4]); //=> -1
*/
R.indexOf = curry2(function _indexOf(target, list) {
return indexOf(list, target);
});
/**
* Returns the position of the first occurrence of an item (by strict equality) in
* an array, or -1 if the item is not included in the array. However,
* `indexOf.from` will only search the tail of the array, starting from the
* `fromIdx` parameter.
*
* @func
* @memberOf R
* @category List
* @sig a -> Number -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} list The array to search in.
* @param {Number} fromIdx the index to start searching from
* @return {Number} the index of the target, or -1 if the target is not found.
*
* @example
*
* R.indexOf.from(3, 2, [-1,0,1,2,3,4]); //=> 4
* R.indexOf.from(10, 2, [1,2,3,4]); //=> -1
*/
R.indexOf.from = curry3(function indexOfFrom(target, fromIdx, list) {
return indexOf(list, target, fromIdx);
});
/**
* Returns the position of the last occurrence of an item (by strict equality) in
* an array, or -1 if the item is not included in the array.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} list The array to search in.
* @return {Number} the index of the target, or -1 if the target is not found.
*
* @example
*
* R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6
* R.lastIndexOf(10, [1,2,3,4]); //=> -1
*/
R.lastIndexOf = curry2(function _lastIndexOf(target, list) {
return lastIndexOf(list, target);
});
/**
* Returns the position of the last occurrence of an item (by strict equality) in
* an array, or -1 if the item is not included in the array. However,
* `lastIndexOf.from` will only search the tail of the array, starting from the
* `fromIdx` parameter.
*
* @func
* @memberOf R
* @category List
* @sig a -> Number -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} list The array to search in.
* @param {Number} fromIdx the index to start searching from
* @return {Number} the index of the target, or -1 if the target is not found.
*
* @example
*
* R.lastIndexOf.from(3, 2, [-1,3,3,0,1,2,3,4]); //=> 2
* R.lastIndexOf.from(10, 2, [1,2,3,4]); //=> -1
*/
R.lastIndexOf.from = curry3(function lastIndexOfFrom(target, fromIdx, list) {
return lastIndexOf(list, target, fromIdx);
});
/**
* Returns `true` if the specified item is somewhere in the list, `false` otherwise.
* Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking.
*
* @func
* @memberOf R
* @category List
* @sig a -> [a] -> Boolean
* @param {Object} a The item to compare against.
* @param {Array} list The array to consider.
* @return {boolean} `true` if the item is in the list, `false` otherwise.
* @example
*
* R.contains(3)([1, 2, 3]); //=> true
* R.contains(4)([1, 2, 3]); //=> false
* R.contains({})([{}, {}]); //=> false
* var obj = {};
* R.contains(obj)([{}, obj, {}]); //=> true
*/
function contains(a, list) {
return indexOf(list, a) > -1;
}
R.contains = curry2(contains);
/**
* Returns `true` if the `x` is found in the `list`, using `pred` as an
* equality predicate for `x`.
*
* @func
* @memberOf R
* @category List
* @sig (x, a -> Boolean) -> x -> [a] -> Boolean
* @param {Function} pred :: x -> x -> Bool
* @param {*} x the item to find
* @param {Array} list the list to iterate over
* @return {Boolean} `true` if `x` is in `list`, else `false`
* @example
*
* var xs = [{x: 12}, {x: 11}, {x: 10}];
* R.containsWith(function(a, b) { return a.x === b.x; }, {x: 10}, xs); //=> true
* R.containsWith(function(a, b) { return a.x === b.x; }, {x: 1}, xs); //=> false
*/
function containsWith(pred, x, list) {
var idx = -1, len = list.length;
while (++idx < len) {
if (pred(x, list[idx])) {
return true;
}
}
return false;
}
R.containsWith = curry3(containsWith);
/**
* Returns a new list containing only one copy of each element in the original list.
* Equality is strict here, meaning reference equality for objects and non-coercing equality
* for primitives.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [a]
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* R.uniq([1, 1, 2, 1]); //=> [1, 2]
* R.uniq([{}, {}]); //=> [{}, {}]
* R.uniq([1, '1']); //=> [1, '1']
*/
var uniq = R.uniq = function uniq(list) {
var idx = -1, len = list.length;
var result = [], item;
while (++idx < len) {
item = list[idx];
if (!contains(item, result)) {
result.push(item);
}
}
return result;
};
/**
* Returns `true` if all elements are unique, otherwise `false`.
* Uniqueness is determined using strict equality (`===`).
*
* @func
* @memberOf R
* @category List
* @sig [a] -> Boolean
* @param {Array} list The array to consider.
* @return {boolean} `true` if all elements are unique, else `false`.
* @example
*
* R.isSet(['1', 1]); //=> true
* R.isSet([1, 1]); //=> false
* R.isSet([{}, {}]); //=> true
*/
R.isSet = function _isSet(list) {
var len = list.length;
var idx = -1;
while (++idx < len) {
if (indexOf(list, list[idx], idx + 1) >= 0) {
return false;
}
}
return true;
};
/**
* Returns a new list containing only one copy of each element in the original list, based
* upon the value returned by applying the supplied predicate to two list elements. Prefers
* the first item if two items compare equal based on the predicate.
*
* @func
* @memberOf R
* @category List
* @sig (x, a -> Boolean) -> [a] -> [a]
* @param {Function} pred :: x -> x -> Bool
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* var strEq = function(a, b) { return ('' + a) === ('' + b) };
* R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2]
* R.uniqWith(strEq)([{}, {}]); //=> [{}]
* R.uniqWith(strEq)([1, '1', 1]); //=> [1]
* R.uniqWith(strEq)(['1', 1, 1]); //=> ['1']
*/
var uniqWith = R.uniqWith = curry2(function _uniqWith(pred, list) {
var idx = -1, len = list.length;
var result = [], item;
while (++idx < len) {
item = list[idx];
if (!containsWith(pred, item, result)) {
result.push(item);
}
}
return result;
});
/**
* Returns a new list by plucking the same named property off all objects in the list supplied.
*
* @func
* @memberOf R
* @category List
* @sig String -> {*} -> [*]
* @param {string|number} key The key name to pluck off of each object.
* @param {Array} list The array to consider.
* @return {Array} The list of values for the given key.
* @example
*
* R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2]
* R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3]
*/
var pluck = R.pluck = curry2(function _pluck(p, list) {
return map(prop(p), list);
});
/**
* `makeFlat` is a helper function that returns a one-level or fully recursive function
* based on the flag passed in.
*
* @private
*/
// TODO: document, even for internals...
var makeFlat = function _makeFlat(recursive) {
return function __flatt(list) {
var value, result = [], idx = -1, j, ilen = list.length, jlen;
while (++idx < ilen) {
if (R.isArrayLike(list[idx])) {
value = (recursive) ? __flatt(list[idx]) : list[idx];
j = -1;
jlen = value.length;
while (++j < jlen) {
result.push(value[j]);
}
} else {
result.push(list[idx]);
}
}
return result;
};
};
/**
* Returns a new list by pulling every item out of it (and all its sub-arrays) and putting
* them in a new array, depth-first.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [b]
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
* @example
*
* R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
* //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
*/
R.flatten = makeFlat(true);
/**
* Returns a new list by pulling every item at the first level of nesting out, and putting
* them in a new array.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [b]
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
* @example
*
* R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]]
* R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6]
*/
var unnest = R.unnest = makeFlat(false);
/**
* Creates a new list out of the two supplied by applying the function to
* each equally-positioned pair in the lists. The returned list is
* truncated to the length of the shorter of the two input lists.
*
* @function
* @memberOf R
* @category List
* @sig (a,b -> c) -> a -> b -> [c]
* @param {Function} fn The function used to combine the two elements into one value.
* @param {Array} list1 The first array to consider.
* @param {Array} list2 The second array to consider.
* @return {Array} The list made by combining same-indexed elements of `list1` and `list2`
* using `fn`.
* @example
*
* var f = function(x, y) {
* // ...
* };
* R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']);
* //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')]
*/
R.zipWith = curry3(function _zipWith(fn, a, b) {
var rv = [], idx = -1, len = Math.min(a.length, b.length);
while (++idx < len) {
rv[idx] = fn(a[idx], b[idx]);
}
return rv;
});
/**
* Creates a new list out of the two supplied by pairing up
* equally-positioned items from both lists. The returned list is
* truncated to the length of the shorter of the two input lists.
* Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`.
*
* @func
* @memberOf R
* @category List
* @sig a -> b -> [[a,b]]
* @param {Array} list1 The first array to consider.
* @param {Array} list2 The second array to consider.
* @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`.
* @example
*
* R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']]
*/
R.zip = curry2(function _zip(a, b) {
var rv = [];
var idx = -1;
var len = Math.min(a.length, b.length);
while (++idx < len) {
rv[idx] = [a[idx], b[idx]];
}
return rv;
});
/**
* Creates a new object out of a list of keys and a list of values.
*
* @func
* @memberOf R
* @category List
* @sig k -> v -> {k: v}
* @param {Array} keys The array that will be properties on the output object.
* @param {Array} values The list of values on the output object.
* @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`.
* @example
*
* R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3}
*/
R.zipObj = curry2(function _zipObj(keys, values) {
var idx = -1, len = keys.length, out = {};
while (++idx < len) {
out[keys[idx]] = values[idx];
}
return out;
});
/**
* Creates a new object out of a list key-value pairs.
*
* @func
* @memberOf R
* @category List
* @sig [[k,v]] -> {k: v}
* @param {Array} An array of two-element arrays that will be the keys and values of the ouput object.
* @return {Object} The object made by pairing up `keys` and `values`.
* @example
*
* R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3}
*/
R.fromPairs = function _fromPairs(pairs) {
var idx = -1, len = pairs.length, out = {};
while (++idx < len) {
if (isArray(pairs[idx]) && pairs[idx].length) {
out[pairs[idx][0]] = pairs[idx][1];
}
}
return out;
};
/**
* Creates a new list out of the two supplied by applying the function
* to each possible pair in the lists.
*
* @see R.xprod
* @func
* @memberOf R
* @category List
* @sig (a,b -> c) -> a -> b -> [c]
* @param {Function} fn The function to join pairs with.
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The list made by combining each possible pair from
* `as` and `bs` using `fn`.
* @example
*
* var f = function(x, y) {
* // ...
* };
* R.xprodWith(f, [1, 2], ['a', 'b']);
* // [f(1, 'a'), f(1, 'b'), f(2, 'a'), f(2, 'b')];
*/
R.xprodWith = curry3(function _xprodWith(fn, a, b) {
if (isEmpty(a) || isEmpty(b)) {
return [];
}
// Better to push them all or to do `new Array(ilen * jlen)` and
// calculate indices?
var idx = -1, ilen = a.length, j, jlen = b.length, result = [];
while (++idx < ilen) {
j = -1;
while (++j < jlen) {
result.push(fn(a[idx], b[j]));
}
}
return result;
});
/**
* Creates a new list out of the two supplied by creating each possible
* pair from the lists.
*
* @func
* @memberOf R
* @category List
* @sig a -> b -> [[a,b]]
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The list made by combining each possible pair from
* `as` and `bs` into pairs (`[a, b]`).
* @example
*
* R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
*/
R.xprod = curry2(function _xprod(a, b) { // = xprodWith(prepend); (takes about 3 times as long...)
if (isEmpty(a) || isEmpty(b)) {
return [];
}
var idx = -1;
var ilen = a.length;
var j;
var jlen = b.length;
// Better to push them all or to do `new Array(ilen * jlen)` and calculate indices?
var result = [];
while (++idx < ilen) {
j = -1;
while (++j < jlen) {
result.push([a[idx], b[j]]);
}
}
return result;
});
/**
* Returns a new list with the same elements as the original list, just
* in the reverse order.
*
* @func
* @memberOf R
* @category List
* @sig [a] -> [a]
* @param {Array} list The list to reverse.
* @return {Array} A copy of the list in reverse order.
* @example
*
* R.reverse([1, 2, 3]); //=> [3, 2, 1]
* R.reverse([1, 2]); //=> [2, 1]
* R.reverse([1]); //=> [1]
* R.reverse([]); //=> []
*/
R.reverse = function _reverse(list) {
return clone(list || []).reverse();
};
/**
* Returns a list of numbers from `from` (inclusive) to `to`
* (exclusive).
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [Number]
* @param {number} from The first number in the list.
* @param {number} to One more than the last number in the list.
* @return {Array} The list of numbers in tthe set `[a, b)`.
* @example
*
* R.range(1, 5); //=> [1, 2, 3, 4]
* R.range(50, 53); //=> [50, 51, 52]
*/
R.range = curry2(function _range(from, to) {
if (from >= to) {
return [];
}
var idx = 0, result = new Array(Math.floor(to) - Math.ceil(from));
for (; from < to; idx++, from++) {
result[idx] = from;
}
return result;
});
/**
* Returns a string made by inserting the `separator` between each
* element and concatenating all the elements into a single string.
*
* @func
* @memberOf R
* @category List
* @sig String -> [a] -> String
* @param {string|number} separator The string used to separate the elements.
* @param {Array} xs The elements to join into a string.
* @return {string} The string made by concatenating `xs` with `separator`.
* @example
*
* var spacer = R.join(' ');
* spacer(['a', 2, 3.4]); //=> 'a 2 3.4'
* R.join('|', [1, 2, 3]); //=> '1|2|3'
*/
R.join = invoker('join', Array.prototype);
/**
* Returns the elements from `xs` starting at `a` and ending at `b - 1`.
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [a] -> [a]
* @param {number} a The starting index.
* @param {number} b One more than the ending index.
* @param {Array} xs The list to take elements from.
* @return {Array} The items from `a` to `b - 1` from `xs`.
* @example
*
* var xs = R.range(0, 10);
* R.slice(2, 5)(xs); //=> [2, 3, 4]
*/
R.slice = invoker('slice', Array.prototype);
/**
* Returns the elements from `xs` starting at `a` going to the end of `xs`.
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a]
* @param {number} a The starting index.
* @param {Array} xs The list to take elements from.
* @return {Array} The items from `a` to the end of `xs`.
* @example
*
* var xs = R.range(0, 10);
* R.slice.from(2)(xs); //=> [2, 3, 4, 5, 6, 7, 8, 9]
*
* var ys = R.range(4, 8);
* var tail = R.slice.from(1);
* tail(ys); //=> [5, 6, 7]
*/
R.slice.from = curry2(function(a, xs) {
return xs.slice(a, xs.length);
});
/**
* Removes the sub-list of `list` starting at index `start` and containing
* `count` elements. _Note that this is not destructive_: it returns a
* copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @category List
* @sig Number -> Number -> [a] -> [a]
* @param {Number} start The position to start removing elements
* @param {Number} count The number of elements to remove
* @param {Array} list The list to remove from
* @return {Array} a new Array with `count` elements from `start` removed
* @example
*
* R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]
*/
R.remove = curry3(function _remove(start, count, list) {
return concat(_slice(list, 0, Math.min(start, list.length)), _slice(list, Math.min(list.length, start + count)));
});
/**
* Inserts the supplied element into the list, at index `index`. _Note
* that this is not destructive_: it returns a copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @category List
* @sig Number -> a -> [a] -> [a]
* @param {Number} index The position to insert the element
* @param {*} elt The element to insert into the Array
* @param {Array} list The list to insert into
* @return {Array} a new Array with `elt` inserted at `index`
* @example
*
* R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4]
*/
R.insert = curry3(function _insert(idx, elt, list) {
idx = idx < list.length && idx >= 0 ? idx : list.length;
return concat(append(elt, _slice(list, 0, idx)), _slice(list, idx));
});
/**
* Inserts the sub-list into the list, at index `index`. _Note that this
* is not destructive_: it returns a copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @category List
* @sig Number -> [a] -> [a] -> [a]
* @param {Number} index The position to insert the sublist
* @param {Array} elts The sub-list to insert into the Array
* @param {Array} list The list to insert the sub-list into
* @return {Array} a new Array with `elts` inserted starting at `index`
* @example
*
* R.insert.all(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4]
*/
R.insert.all = curry3(function _insertAll(idx, elts, list) {
idx = idx < list.length && idx >= 0 ? idx : list.length;
return concat(concat(_slice(list, 0, idx), elts), _slice(list, idx));
});
/**
* Makes a comparator function out of a function that reports whether the first element is less than the second.
*
* @func
* @memberOf R
* @category Function
* @sig (a, b -> Boolean) -> (a, b -> Number)
* @param {Function} pred A predicate function of arity two.
* @return {Function} a Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`
* @example
*
* var cmp = R.comparator(function(a, b) {
* return a.age < b.age;
* });
* var people = [
* // ...
* ];
* R.sort(cmp, people);
*/
var comparator = R.comparator = function _comparator(pred) {
return function(a, b) {
return pred(a, b) ? -1 : pred(b, a) ? 1 : 0;
};
};
/**
* Returns a copy of the list, sorted according to the comparator function, which should accept two values at a
* time and return a negative number if the first value is smaller, a positive number if it's larger, and zero
* if they are equal. Please note that this is a **copy** of the list. It does not modify the original.
*
* @func
* @memberOf R
* @category List
* @sig (a,a -> Number) -> [a] -> [a]
* @param {Function} comparator A sorting function :: a -> b -> Int
* @param {Array} list The list to sort
* @return {Array} a new array with its elements sorted by the comparator function.
* @example
*
* var diff = function(a, b) { return a - b; };
* R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7]
*/
R.sort = curry2(function sort(comparator, list) {
return clone(list).sort(comparator);
});
/**
* Splits a list into sublists stored in an object, based on the result of calling a String-returning function
* on each element, and grouping the results according to values returned.
*
* @func
* @memberOf R
* @category List
* @sig (a -> s) -> [a] -> {s: a}
* @param {Function} fn Function :: a -> String
* @param {Array} list The array to group
* @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements
* that produced that key when passed to `fn`.
* @example
*
* var byGrade = R.groupBy(function(student) {
* var score = student.score;
* return (score < 65) ? 'F' : (score < 70) ? 'D' :
* (score < 80) ? 'C' : (score < 90) ? 'B' : 'A';
* });
* var students = [{name: 'Abby', score: 84},
* {name: 'Eddy', score: 58},
* // ...
* {name: 'Jack', score: 69}];
* byGrade(students);
* // {
* // 'A': [{name: 'Dianne', score: 99}],
* // 'B': [{name: 'Abby', score: 84}]
* // // ...,
* // 'F': [{name: 'Eddy', score: 58}]
* // }
*/
R.groupBy = curry2(function _groupBy(fn, list) {
return foldl(function(acc, elt) {
var key = fn(elt);
acc[key] = append(elt, acc[key] || (acc[key] = []));
return acc;
}, {}, list);
});
/**
* Takes a predicate and a list and returns the pair of lists of
* elements which do and do not satisfy the predicate, respectively.
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [[a],[a]]
* @param {Function} pred Function :: a -> Boolean
* @param {Array} list The array to partition
* @return {Array} A nested array, containing first an array of elements that satisfied the predicate,
* and second an array of elements that did not satisfy.
* @example
*
* R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']);
* //=> [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ]
*/
R.partition = curry2(function _partition(pred, list) {
return foldl(function(acc, elt) {
acc[pred(elt) ? 0 : 1].push(elt);
return acc;
}, [[], []], list);
});
// Object Functions
// ----------------
//
// These functions operate on plain Javascript object, adding simple functions to test properties on these
// objects. Many of these are of most use in conjunction with the list functions, operating on lists of
// objects.
// --------
/**
* Runs the given function with the supplied object, then returns the object.
*
* @func
* @memberOf R
* @category Function
* @sig a -> (a -> *) -> a
* @param {*} x
* @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away.
* @return {*} x
* @example
*
* var sayX = function(x) { console.log('x is ' + x); };
* R.tap(100, sayX); //=> 100
* //-> 'x is 100')
*/
R.tap = curry2(function _tap(x, fn) {
if (typeof fn === 'function') { fn(x); }
return x;
});
/**
* Tests if two items are equal. Equality is strict here, meaning reference equality for objects and
* non-coercing equality for primitives.
*
* @func
* @memberOf R
* @category Relation
* @sig a -> b -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @example
*
* var o = {};
* R.eq(o, o); //=> true
* R.eq(o, {}); //=> false
* R.eq(1, 1); //=> true
* R.eq(1, '1'); //=> false
*/
R.eq = curry2(function _eq(a, b) { return a === b; });
/**
* Returns a function that when supplied an object returns the indicated property of that object, if it exists.
*
* @func
* @memberOf R
* @category Object
* @sig s -> {s: a} -> a
* @param {String} p The property name
* @param {Object} obj The object to query
* @return {*} The value at obj.p
* @example
*
* R.prop('x', {x: 100}); //=> 100
* R.prop('x', {}); //=> undefined
*
* var fifth = R.prop(4); // indexed from 0, remember
* fifth(['Bashful', 'Doc', 'Dopey', 'Grumpy', 'Happy', 'Sleepy', 'Sneezy']);
* //=> 'Happy'
*/
var prop = R.prop = function prop(p, obj) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return function _prop(obj) { return obj[p]; };
}
return obj[p];
};
/**
* @func
* @memberOf R
* @category Object
* @see R.prop
*/
R.get = R.prop;
/**
* Returns the value at the specified property.
* The only difference from `prop` is the parameter order.
*
* @func
* @memberOf R
* @see R.prop
* @category Object
* @sig {s: a} -> s -> a
* @param {Object} obj The object to query
* @param {String} prop The property name
* @return {*} The value at obj.p
* @example
*
* R.props({x: 100}, 'x'); //=> 100
*/
R.props = flip(R.prop);
/**
* An internal reference to `Object.prototype.hasOwnProperty`
* @private
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* If the given object has an own property with the specified name,
* returns the value of that property.
* Otherwise returns the provided default value.
*
* @func
* @memberOf R
* @category Object
* @sig s -> v -> {s: x} -> x | v
* @param {String} p The name of the property to return.
* @param {*} val The default value.
* @returns {*} The value of given property or default value.
* @example
*
* var alice = {
* name: 'ALICE',
* age: 101
* };
* var favorite = R.prop('favoriteLibrary');
* var favoriteWithDefault = R.propOrDefault('favoriteLibrary', 'Ramda');
*
* favorite(alice); //=> undefined
* favoriteWithDefault(alice); //=> 'Ramda'
*/
R.propOrDefault = curry3(function _propOrDefault(p, val, obj) {
return hasOwnProperty.call(obj, p) ? obj[p] : val;
});
/**
* Calls the specified function on the supplied object. Any additional arguments
* after `fn` and `obj` are passed in to `fn`. If no additional arguments are passed to `func`,
* `fn` is invoked with no arguments.
*
* @func
* @memberOf R
* @category Object
* @sig k -> {k : v} -> v(*)
* @param {String} fn The name of the property mapped to the function to invoke
* @param {Object} obj The object
* @return {*} The value of invoking `obj.fn`
* @example
*
* R.func('add', R, 1, 2); //=> 3
*
* var obj = { f: function() { return 'f called'; } };
* R.func('f', obj); //=> 'f called'
*/
R.func = function _func(funcName, obj) {
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1: return function(obj) { return obj[funcName].apply(obj, _slice(arguments, 1)); };
default: return obj[funcName].apply(obj, _slice(arguments, 2));
}
};
/**
* Returns a function that always returns the given value.
*
* @func
* @memberOf R
* @category Function
* @sig a -> (* -> a)
* @param {*} val The value to wrap in a function
* @return {Function} A Function :: * -> val
* @example
*
* var t = R.always('Tee');
* t(); //=> 'Tee'
*/
var always = R.always = function _always(val) {
return function() {
return val;
};
};
/**
* Internal reference to Object.keys
*
* @private
* @param {Object}
* @return {Array}
*/
var nativeKeys = Object.keys;
/**
* Returns a list containing the names of all the enumerable own
* properties of the supplied object.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [k]
* @param {Object} obj The object to extract properties from
* @return {Array} An array of the object's own properties
* @example
*
* R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
*/
var keys = R.keys = (function() {
// cover IE < 9 keys issues
var hasEnumBug = !({toString: null}).propertyIsEnumerable('toString');
var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
return function _keys(obj) {
if (!R.is(Object, obj)) {
return [];
}
if (nativeKeys) {
return nativeKeys(Object(obj));
}
var prop, ks = [], nIdx;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
ks.push(prop);
}
}
if (hasEnumBug) {
nIdx = nonEnumerableProps.length;
while (nIdx--) {
prop = nonEnumerableProps[nIdx];
if (hasOwnProperty.call(obj, prop) && !R.contains(prop, ks)) {
ks.push(prop);
}
}
}
return ks;
};
}());
/**
* Returns a list containing the names of all the
* properties of the supplied object, including prototype properties.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [k]
* @param {Object} obj The object to extract properties from
* @return {Array} An array of the object's own and prototype properties
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.keysIn(f); //=> ['x', 'y']
*/
R.keysIn = function _keysIn(obj) {
var prop, ks = [];
for (prop in obj) {
ks.push(prop);
}
return ks;
};
/**
* @private
* @param {Function} fn The strategy for extracting keys from an object
* @return {Function} A function that takes an object and returns an array of
* key-value arrays.
*/
var pairWith = function(fn) {
return function(obj) {
return R.map(function(key) { return [key, obj[key]]; }, fn(obj));
};
};
/**
* Converts an object into an array of key, value arrays.
* Only the object's own properties are used.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [[k,v]]
* @param {Object} obj The object to extract from
* @return {Array} An array of key, value arrays from the object's own properties
* @example
*
* R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]]
*/
R.toPairs = pairWith(R.keys);
/**
* Converts an object into an array of key, value arrays.
* The object's own properties and prototype properties are used.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [[k,v]]
* @param {Object} obj The object to extract from
* @return {Array} An array of key, value arrays from the object's own
* and prototype properties
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.toPairsIn(f); //=> [['x','X'], ['y','Y']]
*/
R.toPairsIn = pairWith(R.keysIn);
/**
* Returns a list of all the enumerable own properties of the supplied object.
* Note that the order of the output array is not guaranteed across
* different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [v]
* @param {Object} obj The object to extract values from
* @return {Array} An array of the values of the object's own properties
* @example
*
* R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3]
*/
R.values = function _values(obj) {
var props = keys(obj),
length = props.length,
vals = new Array(length);
for (var idx = 0; idx < length; idx++) {
vals[idx] = obj[props[idx]];
}
return vals;
};
/**
* Returns a list of all the properties, including prototype properties,
* of the supplied object.
* Note that the order of the output array is not guaranteed to be
* consistent across different JS platforms.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> [v]
* @param {Object} obj The object to extract values from
* @return {Array} An array of the values of the object's own and prototype properties
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.valuesIn(f); //=> ['X', 'Y']
*/
R.valuesIn = function _valuesIn(obj) {
var prop, vs = [];
for (prop in obj) {
vs.push(obj[prop]);
}
return vs;
};
/**
* Internal helper function for making a partial copy of an object
*
* @private
*
*/
// TODO: document, even for internals...
function pickWith(test, obj) {
var copy = {},
props = keys(obj), prop, val;
for (var idx = 0, len = props.length; idx < len; idx++) {
prop = props[idx];
val = obj[prop];
if (test(val, prop, obj)) {
copy[prop] = val;
}
}
return copy;
}
/**
* Returns a partial copy of an object containing only the keys specified. If the key does not exist, the
* property is ignored.
*
* @func
* @memberOf R
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String propery names to copy onto a new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties from `names` on it.
* @example
*
* R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
* R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1}
*/
R.pick = curry2(function pick(names, obj) {
return pickWith(function(val, key) {
return contains(key, names);
}, obj);
});
/**
* Returns a partial copy of an object omitting the keys specified.
*
* @func
* @memberOf R
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String propery names to omit from the new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with properties from `names` not on it.
* @example
*
* R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}
*/
R.omit = curry2(function omit(names, obj) {
return pickWith(function(val, key) {
return !contains(key, names);
}, obj);
});
/**
* Returns a partial copy of an object containing only the keys that
* satisfy the supplied predicate.
*
* @func
* @memberOf R
* @category Object
* @sig (v, k -> Boolean) -> {k: v} -> {k: v}
* @param {Function} pred A predicate to determine whether or not a key
* should be included on the output object.
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties that satisfy `pred`
* on it.
* @see R.pick
* @example
*
* var isUpperCase = function(val, key) { return key.toUpperCase() === key; }
* R.pickWith(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
*/
R.pickWith = curry2(pickWith);
/**
* Internal implementation of `pickAll`
*
* @private
* @see R.pickAll
*/
// TODO: document, even for internals...
var pickAll = function _pickAll(names, obj) {
var copy = {};
forEach(function(name) {
copy[name] = obj[name];
}, names);
return copy;
};
/**
* Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist.
*
* @func
* @memberOf R
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String propery names to copy onto a new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties from `names` on it.
* @see R.pick
* @example
*
* R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
* R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined}
*/
R.pickAll = curry2(pickAll);
/**
* Assigns own enumerable properties of the other object to the destination
* object prefering items in other.
*
* @private
* @memberOf R
* @category Object
* @param {Object} object The destination object.
* @param {Object} other The other object to merge with destination.
* @returns {Object} Returns the destination object.
* @example
*
* extend({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
* //=> { 'name': 'fred', 'age': 40 }
*/
function extend(destination, other) {
var props = keys(other),
idx = -1, length = props.length;
while (++idx < length) {
destination[props[idx]] = other[props[idx]];
}
return destination;
}
/**
* Create a new object with the own properties of a
* merged with the own properties of object b.
* This function will *not* mutate passed-in objects.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> {k: v} -> {k: v}
* @param {Object} a source object
* @param {Object} b object with higher precendence in output
* @returns {Object} Returns the destination object.
* @example
*
* R.mixin({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
* //=> { 'name': 'fred', 'age': 40 }
*/
R.mixin = curry2(function _mixin(a, b) {
return extend(extend({}, a), b);
});
/**
* Creates a shallow copy of an object's own properties.
*
* @func
* @memberOf R
* @category Object
* @sig {*} -> {*}
* @param {Object} obj The object to clone
* @returns {Object} A new object
* @example
*
* R.cloneObj({a: 1, b: 2, c: [1, 2, 3]}); // {a: 1, b: 2, c: [1, 2, 3]}
*/
R.cloneObj = function(obj) {
return extend({}, obj);
};
/**
* Reports whether two functions have the same value for the specified property. Useful as a curried predicate.
*
* @func
* @memberOf R
* @category Object
* @sig k -> {k: v} -> {k: v} -> Boolean
* @param {String} prop The name of the property to compare
* @param {Object} obj1
* @param {Object} obj2
* @return {Boolean}
*
* @example
*
* var o1 = { a: 1, b: 2, c: 3, d: 4 };
* var o2 = { a: 10, b: 20, c: 3, d: 40 };
* R.eqProps('a', o1, o2); //=> false
* R.eqProps('c', o1, o2); //=> true
*/
R.eqProps = curry3(function eqProps(prop, obj1, obj2) {
return obj1[prop] === obj2[prop];
});
/**
* internal helper for `where`
*
* @private
* @see R.where
*/
function satisfiesSpec(spec, parsedSpec, testObj) {
if (spec === testObj) { return true; }
if (testObj == null) { return false; }
parsedSpec.fn = parsedSpec.fn || [];
parsedSpec.obj = parsedSpec.obj || [];
var key, val, idx = -1, fnLen = parsedSpec.fn.length, j = -1, objLen = parsedSpec.obj.length;
while (++idx < fnLen) {
key = parsedSpec.fn[idx];
val = spec[key];
// if (!hasOwnProperty.call(testObj, key)) {
// return false;
// }
if (!(key in testObj)) {
return false;
}
if (!val(testObj[key], testObj)) {
return false;
}
}
while (++j < objLen) {
key = parsedSpec.obj[j];
if (spec[key] !== testObj[key]) {
return false;
}
}
return true;
}
/**
* Takes a spec object and a test object and returns true if the test satisfies the spec.
* Any property on the spec that is not a function is interpreted as an equality
* relation.
*
* If the spec has a property mapped to a function, then `where` evaluates the function, passing in
* the test object's value for the property in question, as well as the whole test object.
*
* `where` is well suited to declarativley expressing constraints for other functions, e.g.,
* `filter`, `find`, `pickWith`, etc.
*
* @func
* @memberOf R
* @category Object
* @sig {k: v} -> {k: v} -> Boolean
* @param {Object} spec
* @param {Object} testObj
* @return {Boolean}
* @example
*
* var spec = {x: 2};
* R.where(spec, {w: 10, x: 2, y: 300}); //=> true
* R.where(spec, {x: 1, y: 'moo', z: true}); //=> false
*
* var spec2 = {x: function(val, obj) { return val + obj.y > 10; }};
* R.where(spec2, {x: 2, y: 7}); //=> false
* R.where(spec2, {x: 3, y: 8}); //=> true
*
* var xs = [{x: 2, y: 1}, {x: 10, y: 2}, {x: 8, y: 3}, {x: 10, y: 4}];
* R.filter(R.where({x: 10}), xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}]
*/
R.where = function where(spec, testObj) {
var parsedSpec = R.groupBy(function(key) {
return typeof spec[key] === 'function' ? 'fn' : 'obj';
}, keys(spec));
switch (arguments.length) {
case 0: throw NO_ARGS_EXCEPTION;
case 1:
return function(testObj) {
return satisfiesSpec(spec, parsedSpec, testObj);
};
}
return satisfiesSpec(spec, parsedSpec, testObj);
};
// Miscellaneous Functions
// -----------------------
//
// A few functions in need of a good home.
// --------
/**
* Expose the functions from ramda as properties of another object.
* If the provided object is the global object then the ramda
* functions become global functions.
* Warning: This function *will* mutate the object provided.
*
* @func
* @memberOf R
* @category Object
* @sig -> {*} -> {*}
* @param {Object} obj The object to attach ramda functions
* @return {Object} a reference to the mutated object
* @example
*
* var x = {}
* R.installTo(x); // x now contains ramda functions
* R.installTo(this); // add ramda functions to `this` object
*/
R.installTo = function(obj) {
return extend(obj, R);
};
/**
* See if an object (`val`) is an instance of the supplied constructor.
* This function will check up the inheritance chain, if any.
*
* @func
* @memberOf R
* @category type
* @sig (* -> {*}) -> a -> Boolean
* @param {Object} ctor A constructor
* @param {*} val The value to test
* @return {Boolean}
* @example
*
* R.is(Object, {}); //=> true
* R.is(Number, 1); //=> true
* R.is(Object, 1); //=> false
* R.is(String, 's'); //=> true
* R.is(String, new String('')); //=> true
* R.is(Object, new String('')); //=> true
* R.is(Object, 's'); //=> false
* R.is(Number, {}); //=> false
*/
R.is = curry2(function is(ctor, val) {
return val != null && val.constructor === ctor || val instanceof ctor;
});
/**
* A function that always returns `0`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @category function
* @sig * -> 0
* @see R.always
* @return {Number} 0. Always zero.
* @example
*
* R.alwaysZero(); //=> 0
*/
R.alwaysZero = always(0);
/**
* A function that always returns `false`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @category function
* @sig * -> false
* @see R.always
* @return {Boolean} false
* @example
*
* R.alwaysFalse(); //=> false
*/
R.alwaysFalse = always(false);
/**
* A function that always returns `true`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @category function
* @sig * -> true
* @see R.always
* @return {Boolean} true
* @example
*
* R.alwaysTrue(); //=> true
*/
R.alwaysTrue = always(true);
// Logic Functions
// ---------------
//
// These functions are very simple wrappers around the built-in logical operators, useful in building up
// more complex functional forms.
// --------
/**
*
* A function wrapping calls to the two functions in an `&&` operation, returning `true` or `false`. Note that
* this is short-circuited, meaning that the second function will not be invoked if the first returns a false-y
* value.
*
* @func
* @memberOf R
* @category logic
* @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @param {Function} g another predicate
* @return {Function} a function that applies its arguments to `f` and `g` and ANDs their outputs together.
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0 };
* var f = R.and(gt10, even);
* f(100); //=> true
* f(101); //=> false
*/
R.and = curry2(function and(f, g) {
return function _and() {
return !!(f.apply(this, arguments) && g.apply(this, arguments));
};
});
/**
* A function wrapping calls to the two functions in an `||` operation, returning `true` or `false`. Note that
* this is short-circuited, meaning that the second function will not be invoked if the first returns a truth-y
* value.
*
* @func
* @memberOf R
* @category logic
* @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @param {Function} g another predicate
* @return {Function} a function that applies its arguments to `f` and `g` and ORs their outputs together.
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0 };
* var f = R.or(gt10, even);
* f(101); //=> true
* f(8); //=> true
*/
R.or = curry2(function or(f, g) {
return function _or() {
return !!(f.apply(this, arguments) || g.apply(this, arguments));
};
});
/**
* A function wrapping a call to the given function in a `!` operation. It will return `true` when the
* underlying function would return a false-y value, and `false` when it would return a truth-y one.
*
* @func
* @memberOf R
* @category logic
* @sig (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @return {Function} a function that applies its arguments to `f` and logically inverts its output.
* @example
*
* var gt10 = function(x) { return x > 10; };
* var f = R.not(gt10);
* f(11); //=> false
* f(9); //=> true
*/
var not = R.not = function _not(f) {
return function() {return !f.apply(this, arguments);};
};
/**
* Create a predicate wrapper which will call a pick function (all/any) for each predicate
*
* @private
* @see R.every
* @see R.some
*/
// TODO: document, even for internals...
var predicateWrap = function _predicateWrap(predPicker) {
return function(preds /* , args */) {
var predIterator = function() {
var args = arguments;
return predPicker(function(predicate) {
return predicate.apply(null, args);
}, preds);
};
return arguments.length > 1 ?
// Call function imediately if given arguments
predIterator.apply(null, _slice(arguments, 1)) :
// Return a function which will call the predicates with the provided arguments
arity(max(pluck('length', preds)), predIterator);
};
};
/**
* Given a list of predicates, returns a new predicate that will be true exactly when all of them are.
*
* @func
* @memberOf R
* @category logic
* @sig [(*... -> Boolean)] -> (*... -> Boolean)
* @param {Array} list An array of predicate functions
* @param {*} optional Any arguments to pass into the predicates
* @return {Function} a function that applies its arguments to each of
* the predicates, returning `true` if all are satisfied.
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0};
* var f = R.allPredicates([gt10, even]);
* f(11); //=> false
* f(12); //=> true
*/
R.allPredicates = predicateWrap(every);
/**
* Given a list of predicates returns a new predicate that will be true exactly when any one of them is.
*
* @func
* @memberOf R
* @category logic
* @sig [(*... -> Boolean)] -> (*... -> Boolean)
* @param {Array} list An array of predicate functions
* @param {*} optional Any arguments to pass into the predicates
* @return {Function} a function that applies its arguments to each of the predicates, returning
* `true` if all are satisfied..
* @example
*
* var gt10 = function(x) { return x > 10; };
* var even = function(x) { return x % 2 === 0};
* var f = R.anyPredicates([gt10, even]);
* f(11); //=> true
* f(8); //=> true
* f(9); //=> false
*/
R.anyPredicates = predicateWrap(some);
// Arithmetic Functions
// --------------------
//
// These functions wrap up the certain core arithmetic operators
// --------
/**
* Adds two numbers (or strings). Equivalent to `a + b` but curried.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @sig String -> String -> String
* @param {number|string} a The first value.
* @param {number|string} b The second value.
* @return {number|string} The result of `a + b`.
* @example
*
* var increment = R.add(1);
* increment(10); //=> 11
* R.add(2, 3); //=> 5
* R.add(7)(10); //=> 17
*/
var add = R.add = curry2(function _add(a, b) { return a + b; });
/**
* Multiplies two numbers. Equivalent to `a * b` but curried.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} a The first value.
* @param {number} b The second value.
* @return {number} The result of `a * b`.
* @example
*
* var double = R.multiply(2);
* var triple = R.multiply(3);
* double(3); //=> 6
* triple(4); //=> 12
* R.multiply(2, 5); //=> 10
*/
var multiply = R.multiply = curry2(function _multiply(a, b) { return a * b; });
/**
* Subtracts two numbers. Equivalent to `a - b` but curried.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} a The first value.
* @param {number} b The second value.
* @return {number} The result of `a - b`.
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.subtract(10, 8); //=> 2
*
* var minus5 = R.subtract(5);
* minus5(17); //=> 12
*
* // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead
* var complementaryAngle = R.subtract(90, _);
* complementaryAngle(30); //=> 60
* complementaryAngle(72); //=> 18
*/
R.subtract = op(function _subtract(a, b) { return a - b; });
/**
* Divides two numbers. Equivalent to `a / b`.
* While at times the curried version of `divide` might be useful,
* probably the curried version of `divideBy` will be more useful.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} a The first value.
* @param {number} b The second value.
* @return {number} The result of `a / b`.
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.divide(71, 100); //=> 0.71
*
* // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead
* var half = R.divide(2);
* half(42); //=> 21
*
* var reciprocal = R.divide(1, _);
* reciprocal(4); //=> 0.25
*/
R.divide = op(function _divide(a, b) { return a / b; });
/**
* Divides the second parameter by the first and returns the remainder.
* Note that this functions preserves the JavaScript-style behavior for
* modulo. For mathematical modulo see `mathMod`
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} a The value to the divide.
* @param {number} b The pseudo-modulus
* @return {number} The result of `b % a`.
* @note Operator: this is right-curried by default, but can be called via sections
* @see R.mathMod
* @example
*
* R.modulo(17, 3); //=> 2
* // JS behavior:
* R.modulo(-17, 3); //=> -2
* R.modulo(17, -3); //=> 2
*
* var isOdd = R.modulo(2);
* isOdd(42); //=> 0
* isOdd(21); //=> 1
*/
R.modulo = op(function _modulo(a, b) { return a % b; });
/**
* Determine if the passed argument is an integer.
*
* @private
* @param {*} n
* @category type
* @return {Boolean}
*/
// TODO: document, even for internals...
var isInteger = Number.isInteger || function isInteger(n) {
return (n << 0) === n;
};
/**
* mathMod behaves like the modulo operator should mathematically, unlike the `%`
* operator (and by extension, R.modulo). So while "-17 % 5" is -2,
* mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN
* when the modulus is zero or negative.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Number
* @param {number} m The dividend.
* @param {number} p the modulus.
* @return {number} The result of `b mod a`.
* @see R.moduloBy
* @example
*
* R.mathMod(-17, 5); //=> 3
* R.mathMod(17, 5); //=> 2
* R.mathMod(17, -5); //=> NaN
* R.mathMod(17, 0); //=> NaN
* R.mathMod(17.2, 5); //=> NaN
* R.mathMod(17, 5.3); //=> NaN
*
* var clock = R.mathMod(12);
* clock(15); //=> 3
* clock(24); //=> 0
*
* // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead
* var seventeenMod = R.mathMod(17, _);
* seventeenMod(3); //=> 2
* seventeenMod(4); //=> 1
* seventeenMod(10); //=> 7
*/
R.mathMod = op(function _mathMod(m, p) {
if (!isInteger(m)) { return NaN; }
if (!isInteger(p) || p < 1) { return NaN; }
return ((m % p) + p) % p;
});
/**
* Adds together all the elements of a list.
*
* @func
* @memberOf R
* @category math
* @sig [Number] -> Number
* @param {Array} list An array of numbers
* @return {number} The sum of all the numbers in the list.
* @see reduce
* @example
*
* R.sum([2,4,6,8,100,1]); //=> 121
*/
R.sum = foldl(add, 0);
/**
* Multiplies together all the elements of a list.
*
* @func
* @memberOf R
* @category math
* @sig [Number] -> Number
* @param {Array} list An array of numbers
* @return {number} The product of all the numbers in the list.
* @see reduce
* @example
*
* R.product([2,4,6,8,100,1]); //=> 38400
*/
R.product = foldl(multiply, 1);
/**
* Returns true if the first parameter is less than the second.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean} a < b
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.lt(2, 6); //=> true
* R.lt(2, 0); //=> false
* R.lt(2, 2); //=> false
* R.lt(5)(10); //=> false // default currying is right-sectioned
* R.lt(5, _)(10); //=> true // left-sectioned currying
*/
R.lt = op(function _lt(a, b) { return a < b; });
/**
* Returns true if the first parameter is less than or equal to the second.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean} a <= b
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.lte(2, 6); //=> true
* R.lte(2, 0); //=> false
* R.lte(2, 2); //=> true
*/
R.lte = op(function _lte(a, b) { return a <= b; });
/**
* Returns true if the first parameter is greater than the second.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean} a > b
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.gt(2, 6); //=> false
* R.gt(2, 0); //=> true
* R.gt(2, 2); //=> false
*/
R.gt = op(function _gt(a, b) { return a > b; });
/**
* Returns true if the first parameter is greater than or equal to the second.
*
* @func
* @memberOf R
* @category math
* @sig Number -> Number -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean} a >= b
* @note Operator: this is right-curried by default, but can be called via sections
* @example
*
* R.gte(2, 6); //=> false
* R.gte(2, 0); //=> true
* R.gte(2, 2); //=> true
*/
R.gte = op(function _gte(a, b) { return a >= b; });
/**
* Determines the largest of a list of numbers (or elements that can be cast to numbers)
*
* @func
* @memberOf R
* @category math
* @sig [Number] -> Number
* @see R.maxWith
* @param {Array} list A list of numbers
* @return {Number} The greatest number in the list
* @example
*
* R.max([7, 3, 9, 2, 4, 9, 3]); //=> 9
*/
var max = R.max = function _max(list) {
return foldl(binary(Math.max), -Infinity, list);
};
/**
* Determines the largest of a list of items as determined by pairwise comparisons from the supplied comparator
*
* @func
* @memberOf R
* @category math
* @sig (a -> Number) -> [a] -> a
* @param {Function} keyFn A comparator function for elements in the list
* @param {Array} list A list of comparable elements
* @return {*} The greatest element in the list. `undefined` if the list is empty.
* @see R.max
* @example
*
* function cmp(obj) { return obj.x; }
* var a = {x: 1}, b = {x: 2}, c = {x: 3};
* R.maxWith(cmp, [a, b, c]); //=> {x: 3}
*/
R.maxWith = curry2(function _maxWith(keyFn, list) {
if (!(list && list.length > 0)) {
return;
}
var idx = 0, winner = list[idx], max = keyFn(winner), testKey;
while (++idx < list.length) {
testKey = keyFn(list[idx]);
if (testKey > max) {
max = testKey;
winner = list[idx];
}
}
return winner;
});
/**
* Determines the smallest of a list of numbers (or elements that can be cast to numbers)
*
* @func
* @memberOf R
* @category math
* @sig [Number] -> Number
* @param {Array} list A list of numbers
* @return {Number} The greatest number in the list
* @see R.minWith
* @example
*
* R.min([7, 3, 9, 2, 4, 9, 3]); //=> 2
*/
R.min = function _min(list) {
return foldl(binary(Math.min), Infinity, list);
};
/**
* Determines the smallest of a list of items as determined by pairwise comparisons from the supplied comparator
*
* @func
* @memberOf R
* @category math
* @sig (a -> Number) -> [a] -> a
* @param {Function} keyFn A comparator function for elements in the list
* @param {Array} list A list of comparable elements
* @see R.min
* @return {*} The greatest element in the list. `undefined` if the list is empty.
* @example
*
* function cmp(obj) { return obj.x; }
* var a = {x: 1}, b = {x: 2}, c = {x: 3};
* R.minWith(cmp, [a, b, c]); //=> {x: 1}
*/
// TODO: combine this with maxWith?
R.minWith = curry2(function _minWith(keyFn, list) {
if (!(list && list.length > 0)) {
return;
}
var idx = 0, winner = list[idx], min = keyFn(list[idx]), testKey;
while (++idx < list.length) {
testKey = keyFn(list[idx]);
if (testKey < min) {
min = testKey;
winner = list[idx];
}
}
return winner;
});
// String Functions
// ----------------
//
// Much of the String.prototype API exposed as simple functions.
// --------
/**
* returns a subset of a string between one index and another.
*
* @func
* @memberOf R
* @category string
* @sig Number -> Number -> String -> String
* @param {Number} indexA An integer between 0 and the length of the string.
* @param {Number} indexB An integer between 0 and the length of the string.
* @param {String} The string to extract from
* @return {String} the extracted substring
* @see R.invoker
* @example
*
* R.substring(2, 5, 'abcdefghijklm'); //=> 'cde'
*/
var substring = R.substring = invoker('substring', String.prototype);
/**
* The trailing substring of a String starting with the nth character:
*
* @func
* @memberOf R
* @category string
* @sig Number -> String -> String
* @param {Number} indexA An integer between 0 and the length of the string.
* @param {String} The string to extract from
* @return {String} the extracted substring
* @see R.invoker
* @example
*
* R.substringFrom(8, 'abcdefghijklm'); //=> 'ijklm'
*/
R.substringFrom = flip(substring)(void 0);
/**
* The leading substring of a String ending before the nth character:
*
* @func
* @memberOf R
* @category string
* @sig Number -> String -> String
* @param {Number} indexA An integer between 0 and the length of the string.
* @param {String} The string to extract from
* @return {String} the extracted substring
* @see R.invoker
* @example
*
* R.substringTo(8, 'abcdefghijklm'); //=> 'abcdefgh'
*/
R.substringTo = substring(0);
/**
* The character at the nth position in a String:
*
* @func
* @memberOf R
* @category string
* @sig Number -> String -> String
* @param {Number} index An integer between 0 and the length of the string.
* @param {String} str The string to extract a char from
* @return {String} the character at `index` of `str`
* @see R.invoker
* @example
*
* R.charAt(8, 'abcdefghijklm'); //=> 'i'
*/
R.charAt = invoker('charAt', String.prototype);
/**
* The ascii code of the character at the nth position in a String:
*
* @func
* @memberOf R
* @category string
* @sig Number -> String -> Number
* @param {Number} index An integer between 0 and the length of the string.
* @param {String} str The string to extract a charCode from
* @return {Number} the code of the character at `index` of `str`
* @see R.invoker
* @example
*
* R.charCodeAt(8, 'abcdefghijklm'); //=> 105
* // (... 'a' ~ 97, 'b' ~ 98, ... 'i' ~ 105)
*/
R.charCodeAt = invoker('charCodeAt', String.prototype);
/**
* Tests a regular expression agains a String
*
* @func
* @memberOf R
* @category string
* @sig RegExp -> String -> [String] | null
* @param {RegExp} rx A regular expression.
* @param {String} str The string to match against
* @return {Array} The list of matches, or null if no matches found
* @see R.invoker
* @example
*
* R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na']
*/
R.match = invoker('match', String.prototype);
/**
* Finds the first index of a substring in a string, returning -1 if it's not present
*
* @func
* @memberOf R
* @category string
* @sig String -> String -> Number
* @param {String} c A string to find.
* @param {String} str The string to search in
* @return {Number} The first index of `c` or -1 if not found
* @see R.invoker
* @example
*
* R.strIndexOf('c', 'abcdefg'); //=> 2
*/
R.strIndexOf = curry2(function _strIndexOf(c, str) {
return str.indexOf(c);
});
/**
*
* Finds the last index of a substring in a string, returning -1 if it's not present
*
* @func
* @memberOf R
* @category string
* @sig String -> String -> Number
* @param {String} c A string to find.
* @param {String} str The string to search in
* @return {Number} The last index of `c` or -1 if not found
* @see R.invoker
* @example
*
* R.strLastIndexOf('a', 'banana split'); //=> 5
*/
R.strLastIndexOf = curry2(function(c, str) {
return str.lastIndexOf(c);
});
/**
* The upper case version of a string.
*
* @func
* @memberOf R
* @category string
* @sig String -> String
* @param {string} str The string to upper case.
* @return {string} The upper case version of `str`.
* @example
*
* R.toUpperCase('abc'); //=> 'ABC'
*/
R.toUpperCase = invoker('toUpperCase', String.prototype);
/**
* The lower case version of a string.
*
* @func
* @memberOf R
* @category string
* @sig String -> String
* @param {string} str The string to lower case.
* @return {string} The lower case version of `str`.
* @example
*
* R.toLowerCase('XYZ'); //=> 'xyz'
*/
R.toLowerCase = invoker('toLowerCase', String.prototype);
/**
* Splits a string into an array of strings based on the given
* separator.
*
* @func
* @memberOf R
* @category string
* @sig String -> String -> [String]
* @param {string} sep The separator string.
* @param {string} str The string to separate into an array.
* @return {Array} The array of strings from `str` separated by `str`.
* @example
*
* var pathComponents = R.split('/');
* R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node']
*
* R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd']
*/
R.split = invoker('split', String.prototype, 1);
/**
* internal path function
* Takes an array, paths, indicating the deep set of keys
* to find.
*
* @private
* @memberOf R
* @category string
* @param {Array} paths An array of strings to map to object properties
* @param {Object} obj The object to find the path in
* @return {Array} The value at the end of the path or `undefined`.
* @example
*
* path(['a', 'b'], {a: {b: 2}}); //=> 2
*/
function path(paths, obj) {
var idx = -1, length = paths.length, val;
if (obj == null) { return; }
val = obj;
while (val != null && ++idx < length) {
val = val[paths[idx]];
}
return val;
}
/**
* Retrieve a nested path on an object seperated by the specified
* separator value.
*
* @func
* @memberOf R
* @category string
* @sig String -> String -> {*} -> *
* @param {string} sep The separator to use in `path`.
* @param {string} path The path to use.
* @return {*} The data at `path`.
* @example
*
* R.pathOn('/', 'a/b/c', {a: {b: {c: 3}}}); //=> 3
*/
R.pathOn = curry3(function pathOn(sep, str, obj) {
return path(str.split(sep), obj);
});
/**
* Retrieve a nested path on an object seperated by periods
*
* @func
* @memberOf R
* @category string
* @sig String -> {*} -> *
* @param {string} path The dot path to use.
* @return {*} The data at `path`.
* @example
*
* R.path('a.b', {a: {b: 2}}); //=> 2
*/
R.path = R.pathOn('.');
// Data Analysis and Grouping Functions
// ------------------------------------
//
// Functions performing SQL-like actions on lists of objects. These do
// not have any SQL-like optimizations performed on them, however.
// --------
/**
* Reasonable analog to SQL `select` statement.
*
* @func
* @memberOf R
* @category object
* @category relation
* @string [k] -> [{k: v}] -> [{k: v}]
* @param {Array} props The property names to project
* @param {Array} objs The objects to query
* @return {Array} An array of objects with just the `props` properties.
* @example
*
* var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2};
* var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7};
* var kids = [abby, fred];
* R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]
*/
R.project = useWith(map, R.pickAll, identity); // passing `identity` gives correct arity
/**
* Determines whether the given property of an object has a specific
* value according to strict equality (`===`). Most likely used to
* filter a list:
*
* @func
* @memberOf R
* @category relation
* @sig k -> v -> {k: v} -> Boolean
* @param {string|number} name The property name (or index) to use.
* @param {*} val The value to compare the property with.
* @return {boolean} `true` if the properties are equal, `false` otherwise.
* @example
*
* var abby = {name: 'Abby', age: 7, hair: 'blond'};
* var fred = {name: 'Fred', age: 12, hair: 'brown'};
* var rusty = {name: 'Rusty', age: 10, hair: 'brown'};
* var alois = {name: 'Alois', age: 15, disposition: 'surly'};
* var kids = [abby, fred, rusty, alois];
* var hasBrownHair = R.propEq('hair', 'brown');
* R.filter(hasBrownHair, kids); //=> [fred, rusty]
*/
R.propEq = curry3(function propEq(name, val, obj) {
return obj[name] === val;
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of the
* elements of each list.
*
* @func
* @memberOf R
* @category relation
* @sig [a] -> [a] -> [a]
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The first and second lists concatenated, with
* duplicates removed.
* @example
*
* R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4]
*/
R.union = compose(uniq, R.concat);
/**
* Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is
* determined according to the value returned by applying the supplied predicate to two list elements.
*
* @func
* @memberOf R
* @category relation
* @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The first and second lists concatenated, with
* duplicates removed.
* @see R.union
* @example
*
* function cmp(x, y) { return x.a === y.a; }
* var l1 = [{a: 1}, {a: 2}];
* var l2 = [{a: 1}, {a: 4}];
* R.unionWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}]
*/
R.unionWith = curry3(function _unionWith(pred, list1, list2) {
return uniqWith(pred, concat(list1, list2));
});
/**
* Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
*
* @func
* @memberOf R
* @category relation
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The elements in `list1` that are not in `list2`
* @see R.differenceWith
* @example
*
* R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2]
* R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5]
*/
R.difference = curry2(function _difference(first, second) {
return uniq(reject(flip(contains)(second), first));
});
/**
* Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
* Duplication is determined according to the value returned by applying the supplied predicate to two list
* elements.
*
* @func
* @memberOf R
* @category relation
* @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @see R.difference
* @return {Array} The elements in `list1` that are not in `list2`
* @example
*
* function cmp(x, y) { return x.a === y.a; }
* var l1 = [{a: 1}, {a: 2}, {a: 3}];
* var l2 = [{a: 3}, {a: 4}];
* R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}]
*
*/
R.differenceWith = curry3(function differenceWith(pred, first, second) {
return uniqWith(pred)(reject(flip(R.containsWith(pred))(second), first));
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists.
*
* @func
* @memberOf R
* @category relation
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @see R.intersectionWith
* @return {Array} The list of elements found in both `list1` and `list2`
* @example
*
* R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3]
*/
R.intersection = curry2(function intersection(list1, list2) {
return uniq(filter(flip(contains)(list1), list2));
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of those
* elements common to both lists. Duplication is determined according
* to the value returned by applying the supplied predicate to two list
* elements.
*
* @func
* @memberOf R
* @category relation
* @sig (a,a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred A predicate function that determines whether
* the two supplied elements are equal.
* Signatrue: a -> a -> Boolean
* @param {Array} list1 One list of items to compare
* @param {Array} list2 A second list of items to compare
* @see R.intersection
* @return {Array} A new list containing those elements common to both lists.
* @example
*
* var buffaloSpringfield = [
* {id: 824, name: 'Richie Furay'},
* {id: 956, name: 'Dewey Martin'},
* {id: 313, name: 'Bruce Palmer'},
* {id: 456, name: 'Stephen Stills'},
* {id: 177, name: 'Neil Young'}
* ];
* var csny = [
* {id: 204, name: 'David Crosby'},
* {id: 456, name: 'Stephen Stills'},
* {id: 539, name: 'Graham Nash'},
* {id: 177, name: 'Neil Young'}
* ];
*
* var sameId = function(o1, o2) {return o1.id === o2.id;};
*
* R.intersectionWith(sameId, buffaloSpringfield, csny);
* //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}]
*/
R.intersectionWith = curry3(function intersectionWith(pred, list1, list2) {
var results = [], idx = -1;
while (++idx < list1.length) {
if (containsWith(pred, list1[idx], list2)) {
results[results.length] = list1[idx];
}
}
return uniqWith(pred, results);
});
/**
* Creates a new list whose elements each have two properties: `val` is
* the value of the corresponding item in the list supplied, and `key`
* is the result of applying the supplied function to that item.
*
* @private
* @func
* @memberOf R
* @category relation
* @param {Function} fn An arbitrary unary function returning a potential
* object key. Signature: Any -> String
* @param {Array} list The list of items to process
* @return {Array} A new list with the described structure.
* @example
*
* var people = [
* {first: 'Fred', last: 'Flintstone', age: 23},
* {first: 'Betty', last: 'Rubble', age: 21},
* {first: 'George', last: 'Jetson', age: 29}
* ];
*
* var fullName = function(p) {return p.first + ' ' + p.last;};
*
* keyValue(fullName, people); //=>
* // [
* // {
* // key: 'Fred Flintstone',
* // val: {first: 'Fred', last: 'Flintstone', age: 23}
* // }, {
* // key: 'Betty Rubble',
* // val: {first: 'Betty', last: 'Rubble', age: 21}
* // }, {
* // key: 'George Jetson',
* // val: {first: 'George', last: 'Jetson', age: 29}
* // }
* // ];
*/
function keyValue(fn, list) { // TODO: Should this be made public?
return map(function(item) {return {key: fn(item), val: item};}, list);
}
/**
* Sorts the list according to a key generated by the supplied function.
*
* @func
* @memberOf R
* @category relation
* @sig (a -> String) -> [a] -> [a]
* @param {Function} fn The function mapping `list` items to keys.
* @param {Array} list The list to sort.
* @return {Array} A new list sorted by the keys generated by `fn`.
* @example
*
* var sortByFirstItem = R.sortBy(prop(0));
* var sortByNameCaseInsensitive = R.sortBy(compose(R.toLowerCase, prop('name')));
* var pairs = [[-1, 1], [-2, 2], [-3, 3]];
* sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]]
* var alice = {
* name: 'ALICE',
* age: 101
* };
* var bob = {
* name: 'Bob',
* age: -10
* };
* var clara = {
* name: 'clara',
* age: 314.159
* };
* var people = [clara, bob, alice];
* sortByNameCaseInsensitive(people); //=> [alice, bob, clara]
*/
R.sortBy = curry2(function sortBy(fn, list) {
return pluck('val', keyValue(fn, list).sort(comparator(function(a, b) {return a.key < b.key;})));
});
/**
* Counts the elements of a list according to how many match each value
* of a key generated by the supplied function. Returns an object
* mapping the keys produced by `fn` to the number of occurrences in
* the list. Note that all keys are coerced to strings because of how
* JavaScript objects work.
*
* @func
* @memberOf R
* @category relation
* @sig (a -> String) -> [a] -> {*}
* @param {Function} fn The function used to map values to keys.
* @param {Array} list The list to count elements from.
* @return {Object} An object mapping keys to number of occurrences in the list.
* @example
*
* var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];
* var letters = R.split('', 'abcABCaaaBBc');
* R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}
* R.countBy(R.toLowerCase)(letters); //=> {'a': 5, 'b': 4, 'c': 3}
*/
R.countBy = curry2(function countBy(fn, list) {
return foldl(function(counts, obj) {
counts[obj.key] = (counts[obj.key] || 0) + 1;
return counts;
}, {}, keyValue(fn, list));
});
/**
* @private
* @param {Function} fn The strategy for extracting function names from an object
* @return {Function} A function that takes an object and returns an array of function names
*
*/
var functionsWith = function(fn) {
return function(obj) {
return R.filter(function(key) { return typeof obj[key] === 'function'; }, fn(obj));
};
};
/**
* Returns a list of function names of object's own functions
*
* @func
* @memberOf R
* @category Object
* @sig {*} -> [String]
* @param {Object} obj The objects with functions in it
* @return {Array} returns a list of the object's own properites that map to functions
* @example
*
* R.functions(R); // returns list of ramda's own function names
*
* var F = function() { this.x = function(){}; this.y = 1; }
* F.prototype.z = function() {};
* F.prototype.a = 100;
* R.functions(new F()); //=> ["x"]
*/
R.functions = functionsWith(R.keys);
/**
* Returns a list of function names of object's own and prototype functions
*
* @func
* @memberOf R
* @category Object
* @sig {*} -> [String]
* @param {Object} obj The objects with functions in it
* @return {Array} returns a list of the object's own properites and prototype
* properties that map to functions
* @example
*
* R.functionsIn(R); // returns list of ramda's own and prototype function names
*
* var F = function() { this.x = function(){}; this.y = 1; }
* F.prototype.z = function() {};
* F.prototype.a = 100;
* R.functionsIn(new F()); //=> ["x", "z"]
*/
R.functionsIn = functionsWith(R.keysIn);
// All the functional goodness, wrapped in a nice little package, just for you!
return R;
}));
|
neveldo/cdnjs
|
ajax/libs/ramda/0.5.0/ramda.js
|
JavaScript
|
mit
| 171,861 |
/*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 3.3.0
build: 3167
*/
YUI.add('dataschema-json', function(Y) {
/**
* Provides a DataSchema implementation which can be used to work with JSON data.
*
* @module dataschema
* @submodule dataschema-json
*/
/**
* JSON subclass for the DataSchema Utility.
* @class DataSchema.JSON
* @extends DataSchema.Base
* @static
*/
var LANG = Y.Lang,
SchemaJSON = {
/////////////////////////////////////////////////////////////////////////////
//
// DataSchema.JSON static methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Utility function converts JSON locator strings into walkable paths
*
* @method DataSchema.JSON.getPath
* @param locator {String} JSON value locator.
* @return {String[]} Walkable path to data value.
* @static
*/
getPath: function(locator) {
var path = null,
keys = [],
i = 0;
if (locator) {
// Strip the ["string keys"] and [1] array indexes
locator = locator.
replace(/\[(['"])(.*?)\1\]/g,
function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}).
replace(/\[(\d+)\]/g,
function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}).
replace(/^\./,''); // remove leading dot
// Validate against problematic characters.
if (!/[^\w\.\$@]/.test(locator)) {
path = locator.split('.');
for (i=path.length-1; i >= 0; --i) {
if (path[i].charAt(0) === '@') {
path[i] = keys[parseInt(path[i].substr(1),10)];
}
}
}
else {
}
}
return path;
},
/**
* Utility function to walk a path and return the value located there.
*
* @method DataSchema.JSON.getLocationValue
* @param path {String[]} Locator path.
* @param data {String} Data to traverse.
* @return {Object} Data value at location.
* @static
*/
getLocationValue: function (path, data) {
var i = 0,
len = path.length;
for (;i<len;i++) {
if(
LANG.isObject(data) &&
(path[i] in data)
) {
data = data[path[i]];
}
else {
data = undefined;
break;
}
}
return data;
},
/**
* Applies a given schema to given JSON data.
*
* @method apply
* @param schema {Object} Schema to apply.
* @param data {Object} JSON data.
* @return {Object} Schema-parsed data.
* @static
*/
apply: function(schema, data) {
var data_in = data,
data_out = {results:[],meta:{}};
// Convert incoming JSON strings
if(!LANG.isObject(data)) {
try {
data_in = Y.JSON.parse(data);
}
catch(e) {
data_out.error = e;
return data_out;
}
}
if(LANG.isObject(data_in) && schema) {
// Parse results data
if(!LANG.isUndefined(schema.resultListLocator)) {
data_out = SchemaJSON._parseResults.call(this, schema, data_in, data_out);
}
// Parse meta data
if(!LANG.isUndefined(schema.metaFields)) {
data_out = SchemaJSON._parseMeta(schema.metaFields, data_in, data_out);
}
}
else {
data_out.error = new Error("JSON schema parse failure");
}
return data_out;
},
/**
* Schema-parsed list of results from full data
*
* @method _parseResults
* @param schema {Object} Schema to parse against.
* @param json_in {Object} JSON to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Parsed data object.
* @static
* @protected
*/
_parseResults: function(schema, json_in, data_out) {
var results = [],
path,
error;
if(schema.resultListLocator) {
path = SchemaJSON.getPath(schema.resultListLocator);
if(path) {
results = SchemaJSON.getLocationValue(path, json_in);
if (results === undefined) {
data_out.results = [];
error = new Error("JSON results retrieval failure");
}
else {
if(LANG.isArray(results)) {
// if no result fields are passed in, then just take the results array whole-hog
// Sometimes you're getting an array of strings, or want the whole object,
// so resultFields don't make sense.
if (LANG.isArray(schema.resultFields)) {
data_out = SchemaJSON._getFieldValues.call(this, schema.resultFields, results, data_out);
}
else {
data_out.results = results;
}
}
else {
data_out.results = [];
error = new Error("JSON Schema fields retrieval failure");
}
}
}
else {
error = new Error("JSON Schema results locator failure");
}
if (error) {
data_out.error = error;
}
}
return data_out;
},
/**
* Get field data values out of list of full results
*
* @method _getFieldValues
* @param fields {Array} Fields to find.
* @param array_in {Array} Results to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Parsed data object.
* @static
* @protected
*/
_getFieldValues: function(fields, array_in, data_out) {
var results = [],
len = fields.length,
i, j,
field, key, locator, path, parser,
simplePaths = [], complexPaths = [], fieldParsers = [],
result, record;
// First collect hashes of simple paths, complex paths, and parsers
for (i=0; i<len; i++) {
field = fields[i]; // A field can be a simple string or a hash
key = field.key || field; // Find the key
locator = field.locator || key; // Find the locator
// Validate and store locators for later
path = SchemaJSON.getPath(locator);
if (path) {
if (path.length === 1) {
simplePaths[simplePaths.length] = {key:key, path:path[0]};
} else {
complexPaths[complexPaths.length] = {key:key, path:path};
}
} else {
}
// Validate and store parsers for later
//TODO: use Y.DataSchema.parse?
parser = (LANG.isFunction(field.parser)) ? field.parser : Y.Parsers[field.parser+''];
if (parser) {
fieldParsers[fieldParsers.length] = {key:key, parser:parser};
}
}
// Traverse list of array_in, creating records of simple fields,
// complex fields, and applying parsers as necessary
for (i=array_in.length-1; i>=0; --i) {
record = {};
result = array_in[i];
if(result) {
// Cycle through simpleLocators
for (j=simplePaths.length-1; j>=0; --j) {
// Bug 1777850: The result might be an array instead of object
record[simplePaths[j].key] = Y.DataSchema.Base.parse.call(this,
(LANG.isUndefined(result[simplePaths[j].path]) ?
result[j] : result[simplePaths[j].path]), simplePaths[j]);
}
// Cycle through complexLocators
for (j=complexPaths.length - 1; j>=0; --j) {
record[complexPaths[j].key] = Y.DataSchema.Base.parse.call(this,
(SchemaJSON.getLocationValue(complexPaths[j].path, result)), complexPaths[j] );
}
// Cycle through fieldParsers
for (j=fieldParsers.length-1; j>=0; --j) {
key = fieldParsers[j].key;
record[key] = fieldParsers[j].parser.call(this, record[key]);
// Safety net
if (LANG.isUndefined(record[key])) {
record[key] = null;
}
}
results[i] = record;
}
}
data_out.results = results;
return data_out;
},
/**
* Parses results data according to schema
*
* @method _parseMeta
* @param metaFields {Object} Metafields definitions.
* @param json_in {Object} JSON to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Schema-parsed meta data.
* @static
* @protected
*/
_parseMeta: function(metaFields, json_in, data_out) {
if(LANG.isObject(metaFields)) {
var key, path;
for(key in metaFields) {
if (metaFields.hasOwnProperty(key)) {
path = SchemaJSON.getPath(metaFields[key]);
if (path && json_in) {
data_out.meta[key] = SchemaJSON.getLocationValue(path, json_in);
}
}
}
}
else {
data_out.error = new Error("JSON meta data retrieval failure");
}
return data_out;
}
};
Y.DataSchema.JSON = Y.mix(SchemaJSON, Y.DataSchema.Base);
}, '3.3.0' ,{requires:['dataschema-base','json']});
|
blackstark/site
|
www/sugar/jssource/src_files/include/javascript/yui3/build/dataschema/dataschema-json.js
|
JavaScript
|
gpl-2.0
| 11,142 |
/**
* @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not.
* @author Glen Mailer
* @copyright 2015 Glen Mailer
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function(context) {
var FUNCTION_MESSAGE = "Unexpected newline between function and ( of function call.";
var PROPERTY_MESSAGE = "Unexpected newline between object and [ of property access.";
/**
* Check to see if the bracket prior to the node is continuing the previous
* line's expression
* @param {ASTNode} node The node to check.
* @param {string} msg The error message to use.
* @returns {void}
* @private
*/
function checkForBreakBefore(node, msg) {
var tokens = context.getTokensBefore(node, 2);
var paren = tokens[1];
var before = tokens[0];
if (paren.loc.start.line !== before.loc.end.line) {
context.report(node, paren.loc.start, msg, { char: paren.value });
}
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
"MemberExpression": function(node) {
if (!node.computed) {
return;
}
checkForBreakBefore(node.property, PROPERTY_MESSAGE);
},
"CallExpression": function(node) {
if (node.arguments.length === 0) {
return;
}
checkForBreakBefore(node.arguments[0], FUNCTION_MESSAGE);
}
};
};
module.exports.schema = [];
|
Phalanstere/WritersStudio
|
writers_studio-win32-ia32/resources/app/node_modules/eslint/lib/rules/no-unexpected-multiline.js
|
JavaScript
|
mit
| 1,803 |
YUI.add('color-base', function (Y, NAME) {
/**
Color provides static methods for color conversion.
Y.Color.toRGB('f00'); // rgb(255, 0, 0)
Y.Color.toHex('rgb(255, 255, 0)'); // #ffff00
@module color
@submodule color-base
@class Color
@since 3.8.0
**/
var REGEX_HEX = /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})/,
REGEX_HEX3 = /^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})/,
REGEX_RGB = /rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/,
TYPES = { 'HEX': 'hex', 'RGB': 'rgb', 'RGBA': 'rgba' },
CONVERTS = { 'hex': 'toHex', 'rgb': 'toRGB', 'rgba': 'toRGBA' };
Y.Color = {
/**
@static
@property KEYWORDS
@type Object
@since 3.8.0
**/
KEYWORDS: {
'black': '000', 'silver': 'c0c0c0', 'gray': '808080', 'white': 'fff',
'maroon': '800000', 'red': 'f00', 'purple': '800080', 'fuchsia': 'f0f',
'green': '008000', 'lime': '0f0', 'olive': '808000', 'yellow': 'ff0',
'navy': '000080', 'blue': '00f', 'teal': '008080', 'aqua': '0ff'
},
/**
@static
@property REGEX_HEX
@type RegExp
@default /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/
@since 3.8.0
**/
REGEX_HEX: REGEX_HEX,
/**
@static
@property REGEX_HEX3
@type RegExp
@default /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})/
@since 3.8.0
**/
REGEX_HEX3: REGEX_HEX3,
/**
@static
@property REGEX_RGB
@type RegExp
@default /rgba?\(([0-9]{1,3}), ?([0-9]{1,3}), ?([0-9]{1,3}),? ?([.0-9]{1,3})?\)/
@since 3.8.0
**/
REGEX_RGB: REGEX_RGB,
re_RGB: REGEX_RGB,
re_hex: REGEX_HEX,
re_hex3: REGEX_HEX3,
/**
@static
@property STR_HEX
@type String
@default #{*}{*}{*}
@since 3.8.0
**/
STR_HEX: '#{*}{*}{*}',
/**
@static
@property STR_RGB
@type String
@default rgb({*}, {*}, {*})
@since 3.8.0
**/
STR_RGB: 'rgb({*}, {*}, {*})',
/**
@static
@property STR_RGBA
@type String
@default rgba({*}, {*}, {*}, {*})
@since 3.8.0
**/
STR_RGBA: 'rgba({*}, {*}, {*}, {*})',
/**
@static
@property TYPES
@type Object
@default {'rgb':'rgb', 'rgba':'rgba'}
@since 3.8.0
**/
TYPES: TYPES,
/**
@static
@property CONVERTS
@type Object
@default {}
@since 3.8.0
**/
CONVERTS: CONVERTS,
/**
@public
@method convert
@param {String} str
@param {String} to
@return {String}
@since 3.8.0
**/
convert: function (str, to) {
// check for a toXXX conversion method first
// if it doesn't exist, use the toXxx conversion method
var convert = Y.Color.CONVERTS[to],
clr = Y.Color[convert](str);
return clr.toLowerCase();
},
/**
Converts provided color value to a hex value string
@public
@method toHex
@param {String} str Hex or RGB value string
@return {String} returns array of values or CSS string if options.css is true
@since 3.8.0
**/
toHex: function (str) {
var clr = Y.Color._convertTo(str, 'hex');
return clr.toLowerCase();
},
/**
Converts provided color value to an RGB value string
@public
@method toRGB
@param {String} str Hex or RGB value string
@return {String}
@since 3.8.0
**/
toRGB: function (str) {
var clr = Y.Color._convertTo(str, 'rgb');
return clr.toLowerCase();
},
/**
Converts provided color value to an RGB value string
@public
@method toRGBA
@param {String} str Hex or RGB value string
@return {String}
@since 3.8.0
**/
toRGBA: function (str) {
var clr = Y.Color._convertTo(str, 'rgba' );
return clr.toLowerCase();
},
/**
Converts the provided color string to an array of values. Will
return an empty array if the provided string is not able
to be parsed.
@public
@method toArray
@param {String} str
@return {Array}
@since 3.8.0
**/
toArray: function(str) {
// parse with regex and return "matches" array
var type = Y.Color.findType(str).toUpperCase(),
regex,
arr,
length,
lastItem;
if (type === 'HEX' && str.length < 5) {
type = 'HEX3';
}
if (type.charAt(type.length - 1) === 'A') {
type = type.slice(0, -1);
}
regex = Y.Color['REGEX_' + type];
if (regex) {
arr = regex.exec(str) || [];
length = arr.length;
if (length) {
arr.shift();
length--;
lastItem = arr[length - 1];
if (!lastItem) {
arr[length - 1] = 1;
}
}
}
return arr;
},
/**
Converts the array of values to a string based on the provided template.
@public
@method fromArray
@param {Array} arr
@param {String} template
@return {String}
@since 3.8.0
**/
fromArray: function(arr, template) {
arr = arr.concat();
if (typeof template === 'undefined') {
return arr.join(', ');
}
var replace = '{*}';
template = Y.Color['STR_' + template.toUpperCase()];
if (arr.length === 3 && template.match(/\{\*\}/g).length === 4) {
arr.push(1);
}
while ( template.indexOf(replace) >= 0 && arr.length > 0) {
template = template.replace(replace, arr.shift());
}
return template;
},
/**
Finds the value type based on the str value provided.
@public
@method findType
@param {String} str
@return {String}
@since 3.8.0
**/
findType: function (str) {
if (Y.Color.KEYWORDS[str]) {
return 'keyword';
}
var index = str.indexOf('('),
key;
if (index > 0) {
key = str.substr(0, index);
}
if (key && Y.Color.TYPES[key.toUpperCase()]) {
return Y.Color.TYPES[key.toUpperCase()];
}
return 'hex';
}, // return 'keyword', 'hex', 'rgb'
/**
Retrives the alpha channel from the provided string. If no alpha
channel is present, `1` will be returned.
@protected
@method _getAlpha
@param {String} clr
@return {Number}
@since 3.8.0
**/
_getAlpha: function (clr) {
var alpha,
arr = Y.Color.toArray(clr);
if (arr.length > 3) {
alpha = arr.pop();
}
return +alpha || 1;
},
/**
Returns the hex value string if found in the KEYWORDS object
@protected
@method _keywordToHex
@param {String} clr
@return {String}
@since 3.8.0
**/
_keywordToHex: function (clr) {
var keyword = Y.Color.KEYWORDS[clr];
if (keyword) {
return keyword;
}
},
/**
Converts the provided color string to the value type provided as `to`
@protected
@method _convertTo
@param {String} clr
@param {String} to
@return {String}
@since 3.8.0
**/
_convertTo: function(clr, to) {
var from = Y.Color.findType(clr),
originalTo = to,
needsAlpha,
alpha,
method,
ucTo;
if (from === 'keyword') {
clr = Y.Color._keywordToHex(clr);
from = 'hex';
}
if (from === 'hex' && clr.length < 5) {
if (clr.charAt(0) === '#') {
clr = clr.substr(1);
}
clr = '#' + clr.charAt(0) + clr.charAt(0) +
clr.charAt(1) + clr.charAt(1) +
clr.charAt(2) + clr.charAt(2);
}
if (from === to) {
return clr;
}
if (from.charAt(from.length - 1) === 'a') {
from = from.slice(0, -1);
}
needsAlpha = (to.charAt(to.length - 1) === 'a');
if (needsAlpha) {
to = to.slice(0, -1);
alpha = Y.Color._getAlpha(clr);
}
ucTo = to.charAt(0).toUpperCase() + to.substr(1).toLowerCase();
method = Y.Color['_' + from + 'To' + ucTo ];
// check to see if need conversion to rgb first
// check to see if there is a direct conversion method
// convertions are: hex <-> rgb <-> hsl
if (!method) {
if (from !== 'rgb' && to !== 'rgb') {
clr = Y.Color['_' + from + 'ToRgb'](clr);
from = 'rgb';
method = Y.Color['_' + from + 'To' + ucTo ];
}
}
if (method) {
clr = ((method)(clr, needsAlpha));
}
// process clr from arrays to strings after conversions if alpha is needed
if (needsAlpha) {
if (!Y.Lang.isArray(clr)) {
clr = Y.Color.toArray(clr);
}
clr.push(alpha);
clr = Y.Color.fromArray(clr, originalTo.toUpperCase());
}
return clr;
},
/**
Processes the hex string into r, g, b values. Will return values as
an array, or as an rgb string.
@protected
@method _hexToRgb
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_hexToRgb: function (str, toArray) {
var r, g, b;
/*jshint bitwise:false*/
if (str.charAt(0) === '#') {
str = str.substr(1);
}
str = parseInt(str, 16);
r = str >> 16;
g = str >> 8 & 0xFF;
b = str & 0xFF;
if (toArray) {
return [r, g, b];
}
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
},
/**
Processes the rgb string into r, g, b values. Will return values as
an array, or as a hex string.
@protected
@method _rgbToHex
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_rgbToHex: function (str) {
/*jshint bitwise:false*/
var rgb = Y.Color.toArray(str),
hex = rgb[2] | (rgb[1] << 8) | (rgb[0] << 16);
hex = (+hex).toString(16);
while (hex.length < 6) {
hex = '0' + hex;
}
return '#' + hex;
}
};
}, '@VERSION@', {"requires": ["yui-base"]});
|
sajochiu/cdnjs
|
ajax/libs/yui/3.9.1/color-base/color-base.js
|
JavaScript
|
mit
| 10,438 |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _postcss = require('postcss');
var _clone = require('../clone');
var _clone2 = _interopRequireDefault(_clone);
var _hasAllProps = require('../hasAllProps');
var _hasAllProps2 = _interopRequireDefault(_hasAllProps);
var _getLastNode = require('../getLastNode');
var _getLastNode2 = _interopRequireDefault(_getLastNode);
var _canMerge = require('../canMerge');
var _canMerge2 = _interopRequireDefault(_canMerge);
exports['default'] = function (direction) {
var wsc = ['width', 'style', 'color'].map(function (d) {
return 'border-' + direction + '-' + d;
});
var defaults = ['medium', 'none', 'currentColor'];
var declaration = 'border-' + direction;
var processor = {
explode: function explode(rule) {
rule.walkDecls(declaration, function (decl) {
var values = _postcss.list.space(decl.value);
wsc.forEach(function (prop, index) {
var node = (0, _clone2['default'])(decl);
node.prop = prop;
node.value = values[index];
if (node.value === undefined) {
node.value = defaults[index];
}
rule.insertAfter(decl, node);
});
decl.remove();
});
},
merge: function merge(rule) {
var decls = rule.nodes.filter(function (node) {
return node.prop && ~wsc.indexOf(node.prop);
});
var _loop = function () {
var lastNode = decls[decls.length - 1];
var props = decls.filter(function (node) {
return node.important === lastNode.important;
});
if (_hasAllProps2['default'].apply(undefined, [props].concat(wsc)) && _canMerge2['default'].apply(undefined, props)) {
var values = wsc.map(function (prop) {
return (0, _getLastNode2['default'])(props, prop).value;
});
var value = values.concat(['']).reduceRight(function (prev, cur, i) {
if (prev === '' && cur === defaults[i]) {
return prev;
}
return cur + " " + prev;
}).trim();
if (value === '') {
value = defaults[0];
}
var shorthand = (0, _clone2['default'])(lastNode);
shorthand.prop = declaration;
shorthand.value = value;
rule.insertAfter(lastNode, shorthand);
props.forEach(function (prop) {
return prop.remove();
});
}
decls = decls.filter(function (node) {
return ! ~props.indexOf(node);
});
};
while (decls.length) {
_loop();
}
}
};
return processor;
};
module.exports = exports['default'];
|
synchronit/synchronit_website
|
zensum/node_modules/postcss-merge-longhand/dist/lib/decl/border-base.js
|
JavaScript
|
apache-2.0
| 3,293 |
/**
* @license AngularJS v1.3.10
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
var $sanitizeMinErr = angular.$$minErr('$sanitize');
/**
* @ngdoc module
* @name ngSanitize
* @description
*
* # ngSanitize
*
* The `ngSanitize` module provides functionality to sanitize HTML.
*
*
* <div doc-module-components="ngSanitize"></div>
*
* See {@link ngSanitize.$sanitize `$sanitize`} for usage.
*/
/*
* HTML Parser By Misko Hevery (misko@hevery.com)
* based on: HTML Parser By John Resig (ejohn.org)
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*
* // Use like so:
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
*/
/**
* @ngdoc service
* @name $sanitize
* @kind function
*
* @description
* The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
* then serialized back to properly escaped html string. This means that no unsafe input can make
* it into the returned string, however, since our parser is more strict than a typical browser
* parser, it's possible that some obscure input, which would be recognized as valid HTML by a
* browser, won't make it through the sanitizer. The input may also contain SVG markup.
* The whitelist is configured using the functions `aHrefSanitizationWhitelist` and
* `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.
*
* @param {string} html HTML input.
* @returns {string} Sanitized HTML.
*
* @example
<example module="sanitizeExample" deps="angular-sanitize.js">
<file name="index.html">
<script>
angular.module('sanitizeExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
$scope.snippet =
'<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>';
$scope.deliberatelyTrustDangerousSnippet = function() {
return $sce.trustAsHtml($scope.snippet);
};
}]);
</script>
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Directive</td>
<td>How</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="bind-html-with-sanitize">
<td>ng-bind-html</td>
<td>Automatically uses $sanitize</td>
<td><pre><div ng-bind-html="snippet"><br/></div></pre></td>
<td><div ng-bind-html="snippet"></div></td>
</tr>
<tr id="bind-html-with-trust">
<td>ng-bind-html</td>
<td>Bypass $sanitize by explicitly trusting the dangerous value</td>
<td>
<pre><div ng-bind-html="deliberatelyTrustDangerousSnippet()">
</div></pre>
</td>
<td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
</tr>
<tr id="bind-default">
<td>ng-bind</td>
<td>Automatically escapes</td>
<td><pre><div ng-bind="snippet"><br/></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should sanitize the html snippet by default', function() {
expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
});
it('should inline raw snippet if bound to a trusted value', function() {
expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should escape snippet without any filter', function() {
expect(element(by.css('#bind-default div')).getInnerHtml()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
toBe('new <b>text</b>');
expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
'new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
"new <b onclick=\"alert(1)\">text</b>");
});
</file>
</example>
*/
function $SanitizeProvider() {
this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
return function(html) {
var buf = [];
htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
return !/^unsafe/.test($$sanitizeUri(uri, isImage));
}));
return buf.join('');
};
}];
}
function sanitizeText(chars) {
var buf = [];
var writer = htmlSanitizeWriter(buf, angular.noop);
writer.chars(chars);
return buf.join('');
}
// Regular Expressions for parsing tags and attributes
var START_TAG_REGEXP =
/^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,
END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/,
ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
BEGIN_TAG_REGEXP = /^</,
BEGING_END_TAGE_REGEXP = /^<\//,
COMMENT_REGEXP = /<!--(.*?)-->/g,
DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,
CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
// Match everything outside of normal chars and " (quote character)
NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
var voidElements = makeMap("area,br,col,hr,img,wbr");
// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
optionalEndTagInlineElements = makeMap("rp,rt"),
optionalEndTagElements = angular.extend({},
optionalEndTagInlineElements,
optionalEndTagBlockElements);
// Safe Block Elements - HTML5
var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," +
"aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
"h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
// Inline Elements - HTML5
var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," +
"bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
"samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
// SVG Elements
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
var svgElements = makeMap("animate,animateColor,animateMotion,animateTransform,circle,defs," +
"desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient," +
"line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set," +
"stop,svg,switch,text,title,tspan,use");
// Special Elements (can contain anything)
var specialElements = makeMap("script,style");
var validElements = angular.extend({},
voidElements,
blockElements,
inlineElements,
optionalEndTagElements,
svgElements);
//Attributes that have href and hence need to be sanitized
var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href");
var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+
'id,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+
'scope,scrolling,shape,size,span,start,summary,target,title,type,'+
'valign,value,vspace,width');
// SVG attributes (without "id" and "name" attributes)
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' +
'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' +
'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' +
'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' +
'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' +
'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' +
'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' +
'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' +
'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' +
'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' +
'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' +
'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' +
'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' +
'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' +
'zoomAndPan');
var validAttrs = angular.extend({},
uriAttrs,
svgAttrs,
htmlAttrs);
function makeMap(str) {
var obj = {}, items = str.split(','), i;
for (i = 0; i < items.length; i++) obj[items[i]] = true;
return obj;
}
/**
* @example
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* @param {string} html string
* @param {object} handler
*/
function htmlParser(html, handler) {
if (typeof html !== 'string') {
if (html === null || typeof html === 'undefined') {
html = '';
} else {
html = '' + html;
}
}
var index, chars, match, stack = [], last = html, text;
stack.last = function() { return stack[ stack.length - 1 ]; };
while (html) {
text = '';
chars = true;
// Make sure we're not in a script or style element
if (!stack.last() || !specialElements[ stack.last() ]) {
// Comment
if (html.indexOf("<!--") === 0) {
// comments containing -- are not allowed unless they terminate the comment
index = html.indexOf("--", 4);
if (index >= 0 && html.lastIndexOf("-->", index) === index) {
if (handler.comment) handler.comment(html.substring(4, index));
html = html.substring(index + 3);
chars = false;
}
// DOCTYPE
} else if (DOCTYPE_REGEXP.test(html)) {
match = html.match(DOCTYPE_REGEXP);
if (match) {
html = html.replace(match[0], '');
chars = false;
}
// end tag
} else if (BEGING_END_TAGE_REGEXP.test(html)) {
match = html.match(END_TAG_REGEXP);
if (match) {
html = html.substring(match[0].length);
match[0].replace(END_TAG_REGEXP, parseEndTag);
chars = false;
}
// start tag
} else if (BEGIN_TAG_REGEXP.test(html)) {
match = html.match(START_TAG_REGEXP);
if (match) {
// We only have a valid start-tag if there is a '>'.
if (match[4]) {
html = html.substring(match[0].length);
match[0].replace(START_TAG_REGEXP, parseStartTag);
}
chars = false;
} else {
// no ending tag found --- this piece should be encoded as an entity.
text += '<';
html = html.substring(1);
}
}
if (chars) {
index = html.indexOf("<");
text += index < 0 ? html : html.substring(0, index);
html = index < 0 ? "" : html.substring(index);
if (handler.chars) handler.chars(decodeEntities(text));
}
} else {
html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
function(all, text) {
text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");
if (handler.chars) handler.chars(decodeEntities(text));
return "";
});
parseEndTag("", stack.last());
}
if (html == last) {
throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
"of html: {0}", html);
}
last = html;
}
// Clean up any remaining tags
parseEndTag();
function parseStartTag(tag, tagName, rest, unary) {
tagName = angular.lowercase(tagName);
if (blockElements[ tagName ]) {
while (stack.last() && inlineElements[ stack.last() ]) {
parseEndTag("", stack.last());
}
}
if (optionalEndTagElements[ tagName ] && stack.last() == tagName) {
parseEndTag("", tagName);
}
unary = voidElements[ tagName ] || !!unary;
if (!unary)
stack.push(tagName);
var attrs = {};
rest.replace(ATTR_REGEXP,
function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
var value = doubleQuotedValue
|| singleQuotedValue
|| unquotedValue
|| '';
attrs[name] = decodeEntities(value);
});
if (handler.start) handler.start(tagName, attrs, unary);
}
function parseEndTag(tag, tagName) {
var pos = 0, i;
tagName = angular.lowercase(tagName);
if (tagName)
// Find the closest opened tag of the same type
for (pos = stack.length - 1; pos >= 0; pos--)
if (stack[ pos ] == tagName)
break;
if (pos >= 0) {
// Close all the open elements, up the stack
for (i = stack.length - 1; i >= pos; i--)
if (handler.end) handler.end(stack[ i ]);
// Remove the open elements from the stack
stack.length = pos;
}
}
}
var hiddenPre=document.createElement("pre");
var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/;
/**
* decodes all entities into regular string
* @param value
* @returns {string} A string with decoded entities.
*/
function decodeEntities(value) {
if (!value) { return ''; }
// Note: IE8 does not preserve spaces at the start/end of innerHTML
// so we must capture them and reattach them afterward
var parts = spaceRe.exec(value);
var spaceBefore = parts[1];
var spaceAfter = parts[3];
var content = parts[2];
if (content) {
hiddenPre.innerHTML=content.replace(/</g,"<");
// innerText depends on styling as it doesn't display hidden elements.
// Therefore, it's better to use textContent not to cause unnecessary
// reflows. However, IE<9 don't support textContent so the innerText
// fallback is necessary.
content = 'textContent' in hiddenPre ?
hiddenPre.textContent : hiddenPre.innerText;
}
return spaceBefore + content + spaceAfter;
}
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns {string} escaped text
*/
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(SURROGATE_PAIR_REGEXP, function(value) {
var hi = value.charCodeAt(0);
var low = value.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}).
replace(NON_ALPHANUMERIC_REGEXP, function(value) {
// unsafe chars are: \u0000-\u001f \u007f-\u009f \u00ad \u0600-\u0604 \u070f \u17b4 \u17b5 \u200c-\u200f \u2028-\u202f \u2060-\u206f \ufeff \ufff0-\uffff from jslint.com/lint.html
// decimal values are: 0-31, 127-159, 173, 1536-1540, 1807, 6068, 6069, 8204-8207, 8232-8239, 8288-8303, 65279, 65520-65535
var c = value.charCodeAt(0);
// if unsafe character encode
if(c <= 159 ||
c == 173 ||
(c >= 1536 && c <= 1540) ||
c == 1807 ||
c == 6068 ||
c == 6069 ||
(c >= 8204 && c <= 8207) ||
(c >= 8232 && c <= 8239) ||
(c >= 8288 && c <= 8303) ||
c == 65279 ||
(c >= 65520 && c <= 65535)) return '&#' + c + ';';
return value; // avoids multilingual issues
}).
replace(/</g, '<').
replace(/>/g, '>');
}
var trim = (function() {
// native trim is way faster: http://jsperf.com/angular-trim-test
// but IE doesn't have it... :-(
// TODO: we should move this into IE/ES5 polyfill
if (!String.prototype.trim) {
return function(value) {
return angular.isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
};
}
return function(value) {
return angular.isString(value) ? value.trim() : value;
};
})();
// Custom logic for accepting certain style options only - textAngular
// Currently allows only the color, background-color, text-align, float, width and height attributes
// all other attributes should be easily done through classes.
function validStyles(styleAttr){
var result = '';
var styleArray = styleAttr.split(';');
angular.forEach(styleArray, function(value){
var v = value.split(':');
if(v.length == 2){
var key = trim(angular.lowercase(v[0]));
var value = trim(angular.lowercase(v[1]));
if(
(key === 'color' || key === 'background-color') && (
value.match(/^rgb\([0-9%,\. ]*\)$/i)
|| value.match(/^rgba\([0-9%,\. ]*\)$/i)
|| value.match(/^hsl\([0-9%,\. ]*\)$/i)
|| value.match(/^hsla\([0-9%,\. ]*\)$/i)
|| value.match(/^#[0-9a-f]{3,6}$/i)
|| value.match(/^[a-z]*$/i)
)
||
key === 'text-align' && (
value === 'left'
|| value === 'right'
|| value === 'center'
|| value === 'justify'
)
||
key === 'float' && (
value === 'left'
|| value === 'right'
|| value === 'none'
)
||
(key === 'width' || key === 'height') && (
value.match(/[0-9\.]*(px|em|rem|%)/)
)
) result += key + ': ' + value + ';';
}
});
return result;
}
// this function is used to manually allow specific attributes on specific tags with certain prerequisites
function validCustomTag(tag, attrs, lkey, value){
// catch the div placeholder for the iframe replacement
if (tag === 'img' && attrs['ta-insert-video']){
if(lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditble' && value === 'false')) return true;
}
return false;
}
/**
* create an HTML/XML writer which writes to buffer
* @param {Array} buf use buf.jain('') to get out sanitized html string
* @returns {object} in the form of {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* }
*/
function htmlSanitizeWriter(buf, uriValidator) {
var ignore = false;
var out = angular.bind(buf, buf.push);
return {
start: function(tag, attrs, unary) {
tag = angular.lowercase(tag);
if (!ignore && specialElements[tag]) {
ignore = tag;
}
if (!ignore && validElements[tag] === true) {
out('<');
out(tag);
angular.forEach(attrs, function(value, key) {
var lkey=angular.lowercase(key);
var isImage=(tag === 'img' && lkey === 'src') || (lkey === 'background');
if ((lkey === 'style' && (value = validStyles(value)) !== '') || validCustomTag(tag, attrs, lkey, value) || validAttrs[lkey] === true &&
(uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
out(' ');
out(key);
out('="');
out(encodeEntities(value));
out('"');
}
});
out(unary ? '/>' : '>');
}
},
end: function(tag) {
tag = angular.lowercase(tag);
if (!ignore && validElements[tag] === true) {
out('</');
out(tag);
out('>');
}
if (tag == ignore) {
ignore = false;
}
},
chars: function(chars) {
if (!ignore) {
out(encodeEntities(chars));
}
}
};
}
// define ngSanitize module and register $sanitize service
angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
/* global sanitizeText: false */
/**
* @ngdoc filter
* @name linky
* @kind function
*
* @description
* Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
* plain email address links.
*
* Requires the {@link ngSanitize `ngSanitize`} module to be installed.
*
* @param {string} text Input text.
* @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
* @returns {string} Html-linkified text.
*
* @usage
<span ng-bind-html="linky_expression | linky"></span>
*
* @example
<example module="linkyExample" deps="angular-sanitize.js">
<file name="index.html">
<script>
angular.module('linkyExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.snippet =
'Pretty text with some links:\n'+
'http://angularjs.org/,\n'+
'mailto:us@somewhere.org,\n'+
'another@somewhere.org,\n'+
'and one more: ftp://127.0.0.1/.';
$scope.snippetWithTarget = 'http://angularjs.org/';
}]);
</script>
<div ng-controller="ExampleController">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Filter</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="linky-filter">
<td>linky filter</td>
<td>
<pre><div ng-bind-html="snippet | linky"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippet | linky"></div>
</td>
</tr>
<tr id="linky-target">
<td>linky target</td>
<td>
<pre><div ng-bind-html="snippetWithTarget | linky:'_blank'"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippetWithTarget | linky:'_blank'"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</file>
<file name="protractor.js" type="protractor">
it('should linkify the snippet with urls', function() {
expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
'another@somewhere.org, and one more: ftp://127.0.0.1/.');
expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
});
it('should not linkify snippet without the linky filter', function() {
expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
'another@somewhere.org, and one more: ftp://127.0.0.1/.');
expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new http://link.');
expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
toBe('new http://link.');
expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
.toBe('new http://link.');
});
it('should work with the target property', function() {
expect(element(by.id('linky-target')).
element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
toBe('http://angularjs.org/');
expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
});
</file>
</example>
*/
angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
var LINKY_URL_REGEXP =
/((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"โโ]/,
MAILTO_REGEXP = /^mailto:/;
return function(text, target) {
if (!text) return text;
var match;
var raw = text;
var html = [];
var url;
var i;
while ((match = raw.match(LINKY_URL_REGEXP))) {
// We can not end in these as they are sometimes found at the end of the sentence
url = match[0];
// if we did not match ftp/http/www/mailto then assume mailto
if (!match[2] && !match[4]) {
url = (match[3] ? 'http://' : 'mailto:') + url;
}
i = match.index;
addText(raw.substr(0, i));
addLink(url, match[0].replace(MAILTO_REGEXP, ''));
raw = raw.substring(i + match[0].length);
}
addText(raw);
return $sanitize(html.join(''));
function addText(text) {
if (!text) {
return;
}
html.push(sanitizeText(text));
}
function addLink(url, text) {
html.push('<a ');
if (angular.isDefined(target)) {
html.push('target="',
target,
'" ');
}
html.push('href="',
url.replace(/"/g, '"'),
'">');
addText(text);
html.push('</a>');
}
};
}]);
})(window, window.angular);
|
walgheraibi/StemCells
|
ui/js/bower_components/textAngular/src/textAngular-sanitize.js
|
JavaScript
|
mit
| 26,988 |
module.exports = collect
function collect (stream) {
if (stream._collected) return
stream._collected = true
stream.pause()
stream.on("data", save)
stream.on("end", save)
var buf = []
function save (b) {
if (typeof b === "string") b = new Buffer(b)
if (Buffer.isBuffer(b) && !b.length) return
buf.push(b)
}
stream.on("entry", saveEntry)
var entryBuffer = []
function saveEntry (e) {
collect(e)
entryBuffer.push(e)
}
stream.on("proxy", proxyPause)
function proxyPause (p) {
p.pause()
}
// replace the pipe method with a new version that will
// unlock the buffered stuff. if you just call .pipe()
// without a destination, then it'll re-play the events.
stream.pipe = (function (orig) { return function (dest) {
// console.error(" === open the pipes", dest && dest.path)
// let the entries flow through one at a time.
// Once they're all done, then we can resume completely.
var e = 0
;(function unblockEntry () {
var entry = entryBuffer[e++]
// console.error(" ==== unblock entry", entry && entry.path)
if (!entry) return resume()
entry.on("end", unblockEntry)
if (dest) dest.add(entry)
else stream.emit("entry", entry)
})()
function resume () {
stream.removeListener("entry", saveEntry)
stream.removeListener("data", save)
stream.removeListener("end", save)
stream.pipe = orig
if (dest) stream.pipe(dest)
buf.forEach(function (b) {
if (b) stream.emit("data", b)
else stream.emit("end")
})
stream.resume()
}
return dest
}})(stream.pipe)
}
|
nikste/visualizationDemo
|
zeppelin-web/node/npm/node_modules/fstream/lib/collect.js
|
JavaScript
|
apache-2.0
| 1,652 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require turbolinks
//= require_tree .
|
thegillis/from_rails_to_phoenix
|
widget_market_rails/app/assets/javascripts/application.js
|
JavaScript
|
mit
| 695 |
YUI.add('escape', function(Y) {
/**
Provides utility methods for escaping strings.
@module escape
@class Escape
@static
@since 3.3.0
**/
var HTML_CHARS = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`'
},
Escape = {
// -- Public Static Methods ------------------------------------------------
/**
Returns a copy of the specified string with special HTML characters
escaped. The following characters will be converted to their
corresponding character entities:
& < > " ' / `
This implementation is based on the [OWASP HTML escaping
recommendations][1]. In addition to the characters in the OWASP
recommendations, we also escape the <code>`</code> character, since IE
interprets it as an attribute delimiter.
If _string_ is not already a string, it will be coerced to a string.
[1]: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
@method html
@param {String} string String to escape.
@return {String} Escaped string.
@static
**/
html: function (string) {
return (string + '').replace(/[&<>"'\/`]/g, Escape._htmlReplacer);
},
/**
Returns a copy of the specified string with special regular expression
characters escaped, allowing the string to be used safely inside a regex.
The following characters, and all whitespace characters, are escaped:
- # $ ^ * ( ) + [ ] { } | \ , . ?
If _string_ is not already a string, it will be coerced to a string.
@method regex
@param {String} string String to escape.
@return {String} Escaped string.
@static
**/
regex: function (string) {
return (string + '').replace(/[\-#$\^*()+\[\]{}|\\,.?\s]/g, '\\$&');
},
// -- Protected Static Methods ---------------------------------------------
/**
* Regex replacer for HTML escaping.
*
* @method _htmlReplacer
* @param {String} match Matched character (must exist in HTML_CHARS).
* @returns {String} HTML entity.
* @static
* @protected
*/
_htmlReplacer: function (match) {
return HTML_CHARS[match];
}
};
Escape.regexp = Escape.regex;
Y.Escape = Escape;
}, '@VERSION@' ,{requires:['yui-base']});
|
drewfreyling/cdnjs
|
ajax/libs/yui/3.4.1pr1/escape/escape.js
|
JavaScript
|
mit
| 2,360 |
import React, {useState} from 'react';
import {
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
Platform,
Linking,
} from 'react-native';
import AutoHeightWebView from 'react-native-autoheight-webview';
import {
autoHeightHtml0,
autoHeightHtml1,
autoHeightScript,
autoWidthHtml0,
autoWidthHtml1,
autoWidthScript,
autoDetectLinkScript,
style0,
inlineBodyStyle,
} from './config';
const onShouldStartLoadWithRequest = result => {
console.log(result);
return true;
};
const onError = ({nativeEvent}) =>
console.error('WebView error: ', nativeEvent);
const onMessage = event => {
const {data} = event.nativeEvent;
let messageData;
// maybe parse stringified JSON
try {
messageData = JSON.parse(data);
} catch (e) {
console.log(e.message);
}
if (typeof messageData === 'object') {
const {url} = messageData;
// check if this message concerns us
if (url && url.startsWith('http')) {
Linking.openURL(url).catch(error =>
console.error('An error occurred', error),
);
}
}
};
const onHeightLoadStart = () => console.log('height on load start');
const onHeightLoad = () => console.log('height on load');
const onHeightLoadEnd = () => console.log('height on load end');
const onWidthLoadStart = () => console.log('width on load start');
const onWidthLoad = () => console.log('width on load');
const onWidthLoadEnd = () => console.log('width on load end');
const Explorer = () => {
const [{widthHtml, heightHtml}, setHtml] = useState({
widthHtml: autoWidthHtml0,
heightHtml: autoHeightHtml0,
});
const changeSource = () =>
setHtml({
widthHtml: widthHtml === autoWidthHtml0 ? autoWidthHtml1 : autoWidthHtml0,
heightHtml:
heightHtml === autoHeightHtml0 ? autoHeightHtml1 : autoHeightHtml0,
});
const [{widthStyle, heightStyle}, setStyle] = useState({
heightStyle: null,
widthStyle: inlineBodyStyle,
});
const changeStyle = () =>
setStyle({
widthStyle:
widthStyle === inlineBodyStyle
? style0 + inlineBodyStyle
: inlineBodyStyle,
heightStyle: heightStyle === null ? style0 : null,
});
const [{widthScript, heightScript}, setScript] = useState({
heightScript: autoDetectLinkScript,
widthScript: null,
});
const changeScript = () =>
setScript({
widthScript: widthScript == autoWidthScript ? autoWidthScript : null,
heightScript:
heightScript !== autoDetectLinkScript
? autoDetectLinkScript
: autoHeightScript + autoDetectLinkScript,
});
const [heightSize, setHeightSize] = useState({height: 0, width: 0});
const [widthSize, setWidthSize] = useState({height: 0, width: 0});
return (
<ScrollView
style={{
paddingTop: 45,
backgroundColor: 'lightyellow',
}}
contentContainerStyle={{
justifyContent: 'center',
alignItems: 'center',
}}>
<AutoHeightWebView
customStyle={heightStyle}
onError={onError}
onLoad={onHeightLoad}
onLoadStart={onHeightLoadStart}
onLoadEnd={onHeightLoadEnd}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
onSizeUpdated={setHeightSize}
source={{html: heightHtml}}
customScript={heightScript}
onMessage={onMessage}
/>
<Text style={{padding: 5}}>
height: {heightSize.height}, width: {heightSize.width}
</Text>
<AutoHeightWebView
style={{
marginTop: 15,
}}
customStyle={widthStyle}
onError={onError}
onLoad={onWidthLoad}
onLoadStart={onWidthLoadStart}
onLoadEnd={onWidthLoadEnd}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
onSizeUpdated={setWidthSize}
allowFileAccessFromFileURLs={true}
allowUniversalAccessFromFileURLs={true}
source={{
html: widthHtml,
baseUrl:
Platform.OS === 'android' ? 'file:///android_asset/' : 'web/',
}}
customScript={widthScript}
/>
<Text style={{padding: 5}}>
height: {widthSize.height}, width: {widthSize.width}
</Text>
<TouchableOpacity onPress={changeSource} style={styles.button}>
<Text>change source</Text>
</TouchableOpacity>
<TouchableOpacity onPress={changeStyle} style={styles.button}>
<Text>change style</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={changeScript}
style={[styles.button, {marginBottom: 100}]}>
<Text>change script</Text>
</TouchableOpacity>
</ScrollView>
);
};
const styles = StyleSheet.create({
button: {
marginTop: 15,
backgroundColor: 'aliceblue',
borderRadius: 5,
padding: 5,
},
});
export default Explorer;
|
iou90/react-native-autoheight-webview
|
demo/App.js
|
JavaScript
|
isc
| 4,845 |
"use strict";
import clear from "rollup-plugin-clear";
import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import typescript from "rollup-plugin-typescript2";
import screeps from "rollup-plugin-screeps";
let cfg;
const dest = process.env.DEST;
if (!dest) {
console.log("No destination specified - code will be compiled but not uploaded");
} else if ((cfg = require("./screeps.json")[dest]) == null) {
throw new Error("Invalid upload destination");
}
export default {
input: "src/main.ts",
output: {
file: "dist/main.js",
format: "cjs",
sourcemap: true
},
plugins: [
clear({ targets: ["dist"] }),
resolve(),
commonjs(),
typescript({tsconfig: "./tsconfig.json"}),
screeps({config: cfg, dryRun: cfg == null})
]
}
|
thaelina/Screeps-ThaeOS
|
rollup.config.js
|
JavaScript
|
isc
| 850 |
import { timeout as d3_timeout } from 'd3-timer';
export function uiFlash(context) {
var _flashTimer;
var _duration = 2000;
var _iconName = '#iD-icon-no';
var _iconClass = 'disabled';
var _text = '';
var _textClass;
function flash() {
if (_flashTimer) {
_flashTimer.stop();
}
context.container().select('.main-footer-wrap')
.classed('footer-hide', true)
.classed('footer-show', false);
context.container().select('.flash-wrap')
.classed('footer-hide', false)
.classed('footer-show', true);
var content = context.container().select('.flash-wrap').selectAll('.flash-content')
.data([0]);
// Enter
var contentEnter = content.enter()
.append('div')
.attr('class', 'flash-content');
var iconEnter = contentEnter
.append('svg')
.attr('class', 'flash-icon')
.append('g')
.attr('transform', 'translate(10,10)');
iconEnter
.append('circle')
.attr('r', 9);
iconEnter
.append('use')
.attr('transform', 'translate(-7,-7)')
.attr('width', '14')
.attr('height', '14');
contentEnter
.append('div')
.attr('class', 'flash-text');
// Update
content = content
.merge(contentEnter);
content
.selectAll('.flash-icon')
.attr('class', 'flash-icon ' + (_iconClass || ''));
content
.selectAll('.flash-icon use')
.attr('xlink:href', _iconName);
content
.selectAll('.flash-text')
.attr('class', 'flash-text ' + (_textClass || ''))
.text(_text);
_flashTimer = d3_timeout(function() {
_flashTimer = null;
context.container().select('.main-footer-wrap')
.classed('footer-hide', false)
.classed('footer-show', true);
context.container().select('.flash-wrap')
.classed('footer-hide', true)
.classed('footer-show', false);
}, _duration);
return content;
}
flash.duration = function(_) {
if (!arguments.length) return _duration;
_duration = _;
return flash;
};
flash.text = function(_) {
if (!arguments.length) return _text;
_text = _;
return flash;
};
flash.textClass = function(_) {
if (!arguments.length) return _textClass;
_textClass = _;
return flash;
};
flash.iconName = function(_) {
if (!arguments.length) return _iconName;
_iconName = _;
return flash;
};
flash.iconClass = function(_) {
if (!arguments.length) return _iconClass;
_iconClass = _;
return flash;
};
return flash;
}
|
morray/iD
|
modules/ui/flash.js
|
JavaScript
|
isc
| 2,966 |
"use strict";
const http_1 = require("http");
const WebSocketServer = require("ws");
const express = require("express");
const dgram = require("dgram");
const readUInt64BE = require("readuint64be");
const buffer_1 = require("buffer");
const _ = require("lodash");
// Health Insurrance:
process.on("uncaughtException", function (err) {
console.log(err);
});
const debug = require("debug")("PeerTracker:Server"), redis = require("redis"), GeoIpNativeLite = require("geoip-native-lite"), bencode = require("bencode");
// Load in GeoData
GeoIpNativeLite.loadDataSync();
// Keep statistics going, update every 30 min
let stats = {
seedCount: 0,
leechCount: 0,
torrentCount: 0,
activeTcount: 0,
scrapeCount: 0,
successfulDown: 0,
countries: {}
};
const ACTION_CONNECT = 0, ACTION_ANNOUNCE = 1, ACTION_SCRAPE = 2, ACTION_ERROR = 3, INTERVAL = 1801, startConnectionIdHigh = 0x417, startConnectionIdLow = 0x27101980;
// Without using streams, this can handle ~320 IPv4 addresses. More doesn't necessarily mean better.
const MAX_PEER_SIZE = 1500;
const FOUR_AND_FIFTEEN_DAYS = 415 * 24 * 60 * 60; // assuming start time is seconds for redis;
// Redis
let client;
class Server {
constructor(opts) {
this._debug = (...args) => {
args[0] = "[" + this._debugId + "] " + args[0];
debug.apply(null, args);
};
const self = this;
if (!opts)
opts = { port: 80, udpPort: 1337, docker: false };
self._debugId = ~~((Math.random() * 100000) + 1);
self._debug("peer-tracker Server instance created");
self.PORT = opts.port;
self.udpPORT = opts.udpPort;
self.server = http_1.createServer();
self.wss = new WebSocketServer.Server({ server: self.server });
self.udp4 = dgram.createSocket({ type: "udp4", reuseAddr: true });
self.app = express();
// PREP VISUAL AID:
console.log(`
.
|
|
|
|||
/___\\
|_ _|
| | | |
| | | |
|__| |__|
| | | |
| | | |
| | | | Peer Tracker 1.1.0
| | | |
| | | | Running in standalone mode
| | | | UDP PORT: ${self.udpPORT}
| | | | HTTP & WS PORT: ${self.PORT}
| | | |
| |_| |
|__| |__|
| | | | LET'S BUILD AN EMPIRE!
| | | | https://github.com/CraigglesO/peer-tracker
| | | |
| | | |
|____|_|____|
`);
// Redis
if (opts.docker)
client = redis.createClient("6379", "redis");
else
client = redis.createClient();
// If an error occurs, print it to the console
client.on("error", function (err) {
console.log("Redis error: " + err);
});
client.on("ready", function () {
console.log(new Date() + ": Redis is up and running.");
});
self.app.set("trust proxy", function (ip) {
return true;
});
// Express
self.app.get("/", function (req, res) {
let ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
if (ip.indexOf("::ffff:") !== -1)
ip = ip.slice(7);
res.status(202).send("Welcome to the Empire. Your address: " + ip);
});
self.app.get("/stat.json", function (req, res) {
res.status(202).send(stats);
});
self.app.get("/stat", function (req, res) {
// { seedCount, leechCount, torrentCount, activeTcount, scrapeCount, successfulDown, countries };
let parsedResponce = `<h1><span style="color:blue;">V1.0.3</span> - ${stats.torrentCount} Torrents {${stats.activeTcount} active}</h1>\n
<h2>Successful Downloads: ${stats.successfulDown}</h2>\n
<h2>Number of Scrapes to this tracker: ${stats.scrapeCount}</h2>\n
<h3>Connected Peers: ${stats.seedCount + stats.leechCount}</h3>\n
<h3><ul>Seeders: ${stats.seedCount}</ul></h3>\n
<h3><ul>Leechers: ${stats.leechCount}</ul></h3>\n
<h3>Countries that have connected: <h3>\n
<ul>`;
let countries;
for (countries in stats.countries)
parsedResponce += `<li>${stats.countries[countries]}</li>\n`;
parsedResponce += "</ul>";
res.status(202).send(parsedResponce);
});
self.app.get("*", function (req, res) {
res.status(404).send("<h1>404 Not Found</h1>");
});
self.server.on("request", self.app.bind(self));
self.server.listen(self.PORT, function () { console.log(new Date() + ": HTTP Server Ready" + "\n" + new Date() + ": Websockets Ready."); });
// WebSocket:
self.wss.on("connection", function connection(ws) {
// let location = url.parse(ws.upgradeReq.url, true);
let ip;
let peerAddress;
let port;
if (opts.docker) {
ip = ws.upgradeReq.headers["x-forwarded-for"];
peerAddress = ip.split(":")[0];
port = ip.split(":")[1];
}
else {
peerAddress = ws._socket.remoteAddress;
port = ws._socket.remotePort;
}
if (peerAddress.indexOf("::ffff:") !== -1)
peerAddress = peerAddress.slice(7);
console.log("peerAddress", peerAddress);
ws.on("message", function incoming(msg) {
handleMessage(msg, peerAddress, port, "ws", (reply) => {
ws.send(reply);
});
});
});
// UDP:
self.udp4.bind(self.udpPORT);
self.udp4.on("message", function (msg, rinfo) {
handleMessage(msg, rinfo.address, rinfo.port, "udp", (reply) => {
self.udp4.send(reply, 0, reply.length, rinfo.port, rinfo.address, (err) => {
if (err) {
console.log("udp4 error: ", err);
}
;
});
});
});
self.udp4.on("error", function (err) { console.log("error", err); });
self.udp4.on("listening", () => { console.log(new Date() + ": UDP-4 Bound and ready."); });
self.updateStatus((info) => {
stats = info;
});
setInterval(() => {
console.log("STAT UPDATE, " + Date.now());
self.updateStatus((info) => {
stats = info;
});
}, 30 * 60 * 1000);
}
updateStatus(cb) {
const self = this;
// Get hashes -> iterate through hashes and get all peers and leechers
// Also get number of scrapes 'scrape'
// Number of active hashes hash+':time'
let NOW = Date.now(), seedCount = 0, // check
leechCount = 0, // check
torrentCount = 0, // check
activeTcount = 0, // check
scrapeCount = 0, // check
successfulDown = 0, // check
countries = {};
client.get("hashes", (err, reply) => {
if (!reply)
return;
let hashList = reply.split(",");
torrentCount = hashList.length;
client.get("scrape", (err, rply) => {
if (err) {
return;
}
if (!rply)
return;
scrapeCount = rply;
});
hashList.forEach((hash, i) => {
client.mget([hash + ":seeders", hash + ":leechers", hash + ":time", hash + ":completed"], (err, rply) => {
if (err) {
return;
}
// iterate through:
// seeders
if (rply[0]) {
rply[0] = rply[0].split(",");
seedCount += rply[0].length;
rply[0].forEach((addr) => {
let ip = addr.split(":")[0];
let country = GeoIpNativeLite.lookup(ip);
if (country)
countries[country] = country.toUpperCase();
});
}
if (rply[1]) {
rply[1] = rply[1].split(",");
seedCount += rply[1].length;
rply[1].forEach((addr) => {
let ip = addr.split(":")[0];
let country = GeoIpNativeLite.lookup(ip);
if (country)
countries[country] = country.toUpperCase();
});
}
if (rply[2]) {
if (((NOW - rply[2]) / 1000) < 432000)
activeTcount++;
}
if (rply[3]) {
successfulDown += Number(rply[3]);
}
if (i === (torrentCount - 1)) {
cb({ seedCount, leechCount, torrentCount, activeTcount, scrapeCount, successfulDown, countries });
}
});
});
});
}
}
// MESSAGE FUNCTIONS:
function handleMessage(msg, peerAddress, port, type, cb) {
// PACKET SIZES:
// CONNECT: 16 - ANNOUNCE: 98 - SCRAPE: 16 OR (16 + 20 * n)
let buf = new buffer_1.Buffer(msg), bufLength = buf.length, transaction_id = 0, action = null, connectionIdHigh = null, connectionIdLow = null, hash = null, responce = null, PEER_ID = null, PEER_ADDRESS = null, PEER_KEY = null, NUM_WANT = null, peerPort = port, peers = null;
// Ensure packet fullfills the minimal 16 byte requirement.
if (bufLength < 16) {
ERROR();
}
else {
// Get generic data:
connectionIdHigh = buf.readUInt32BE(0),
connectionIdLow = buf.readUInt32BE(4),
action = buf.readUInt32BE(8),
transaction_id = buf.readUInt32BE(12); // 12 32-bit integer transaction_id
}
switch (action) {
case ACTION_CONNECT:
// Check whether the transaction ID is equal to the one you chose.
if (startConnectionIdLow !== connectionIdLow || startConnectionIdHigh !== connectionIdHigh) {
ERROR();
break;
}
// Create a new Connection ID and Transaction ID for this user... kill after 30 seconds:
let newConnectionIDHigh = ~~((Math.random() * 100000) + 1);
let newConnectionIDLow = ~~((Math.random() * 100000) + 1);
client.setex(peerAddress + ":" + newConnectionIDHigh, 60, 1);
client.setex(peerAddress + ":" + newConnectionIDLow, 60, 1);
client.setex(peerAddress + ":" + startConnectionIdLow, 60, 1);
client.setex(peerAddress + ":" + startConnectionIdHigh, 60, 1);
// client.setex(peerAddress + ':' + transaction_id , 30 * 1000, 1); // THIS MIGHT BE WRONG
// Create a responce buffer:
responce = new buffer_1.Buffer(16);
responce.fill(0);
responce.writeUInt32BE(ACTION_CONNECT, 0); // 0 32-bit integer action 0 // connect
responce.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id
responce.writeUInt32BE(newConnectionIDHigh, 8); // 8 64-bit integer connection_id
responce.writeUInt32BE(newConnectionIDLow, 12); // 8 64-bit integer connection_id
cb(responce);
break;
case ACTION_ANNOUNCE:
// Checks to make sure the packet is worth analyzing:
// 1. packet is atleast 84 bytes
if (bufLength < 84) {
ERROR();
break;
}
// Minimal requirements:
hash = buf.slice(16, 36);
hash = hash.toString("hex");
PEER_ID = buf.slice(36, 56); // -WD0017-I0mH4sMSAPOJ && -LT1000-9BjtQhMtTtTc
PEER_ID = PEER_ID.toString();
let DOWNLOADED = readUInt64BE(buf, 56), LEFT = readUInt64BE(buf, 64), UPLOADED = readUInt64BE(buf, 72), EVENT = buf.readUInt32BE(80);
if (bufLength > 96) {
PEER_ADDRESS = buf.readUInt16BE(84);
PEER_KEY = buf.readUInt16BE(88);
NUM_WANT = buf.readUInt16BE(92);
peerPort = buf.readUInt16BE(96);
}
// 2. check that Transaction ID and Connection ID match
client.mget([peerAddress + ":" + connectionIdHigh, peerAddress + ":" + connectionIdLow], (err, reply) => {
if (!reply[0] || !reply[1] || err) {
ERROR();
return;
}
addHash(hash);
// Check EVENT // 0: none; 1: completed; 2: started; 3: stopped
// If 1, 2, or 3 do sets first.
if (EVENT === 1) {
// Change the array this peer is housed in.
removePeer(peerAddress + ":" + peerPort, hash + type + ":leechers");
addPeer(peerAddress + ":" + peerPort, hash + type + ":seeders");
// Increment total users who completed file
client.incr(hash + ":completed");
}
else if (EVENT === 2) {
// Add to array (leecher array if LEFT is > 0)
if (LEFT > 0)
addPeer(peerAddress + ":" + peerPort, hash + type + ":leechers");
else
addPeer(peerAddress + ":" + peerPort, hash + type + ":seeders");
}
else if (EVENT === 3) {
// Remove peer from array (leecher array if LEFT is > 0)
removePeer(peerAddress + ":" + peerPort, hash + type + ":leechers");
removePeer(peerAddress + ":" + peerPort, hash + type + ":seeders");
return;
}
client.mget([hash + type + ":seeders", hash + type + ":leechers"], (err, rply) => {
if (err) {
ERROR();
return;
}
// Convert all addresses to a proper hex buffer:
// Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize
let addresses = addrToBuffer(rply[0], rply[1], LEFT);
// Create a responce buffer:
responce = new buffer_1.Buffer(20);
responce.fill(0);
responce.writeUInt32BE(ACTION_ANNOUNCE, 0); // 0 32-bit integer action 1 -> announce
responce.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id
responce.writeUInt32BE(INTERVAL, 8); // 8 32-bit integer interval
responce.writeUInt32BE(addresses[0], 12); // 12 32-bit integer leechers
responce.writeUInt32BE(addresses[1], 16); // 16 32-bit integer seeders
responce = buffer_1.Buffer.concat([responce, addresses[2]]); // 20 + 6 * n 32-bit integer IP address
// 24 + 6 * n 16-bit integer TCP port
cb(responce);
});
});
break;
case ACTION_SCRAPE:
// Check whether the transaction ID is equal to the one you chose.
// 2. check that Transaction ID and Connection ID match
// addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize
// Create a responce buffer:
client.incr("scrape");
let responces = new buffer_1.Buffer(8);
responces.fill(0);
responces.writeUInt32BE(ACTION_SCRAPE, 0); // 0 32-bit integer action 2 -> scrape
responces.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id
let bufferSum = [];
// LOOP THROUGH REQUESTS
for (let i = 16; i < (buf.length - 16); i += 20) {
hash = buf.slice(i, i + 20);
hash = hash.toString("hex");
client.mget([hash + type + ":seeders", hash + type + ":leechers", hash + type + ":completed"], (err, rply) => {
if (err) {
ERROR();
return;
}
// convert all addresses to a proper hex buffer:
let addresses = addrToBuffer(rply[0], rply[1], 1);
let responce = new buffer_1.Buffer(20);
responce.fill(0);
responce.writeUInt32BE(addresses[1], 8); // 8 + 12 * n 32-bit integer seeders
responce.writeUInt32BE(rply[2], 12); // 12 + 12 * n 32-bit integer completed
responce.writeUInt32BE(addresses[0], 16); // 16 + 12 * n 32-bit integer leechers
bufferSum.push(responce);
if ((i + 16) >= (buf.length - 16)) {
let scrapes = buffer_1.Buffer.concat(bufferSum);
responces = buffer_1.Buffer.concat([responces, scrapes]);
cb(responces);
}
});
}
break;
default:
ERROR();
}
function ERROR() {
responce = new buffer_1.Buffer(11);
responce.fill(0);
responce.writeUInt32BE(ACTION_ERROR, 0);
responce.writeUInt32BE(transaction_id, 4);
responce.write("900", 8);
cb(responce);
}
function addPeer(peer, where) {
client.get(where, (err, reply) => {
if (err) {
ERROR();
return;
}
else {
if (!reply)
reply = peer;
else
reply = peer + "," + reply;
reply = reply.split(",");
reply = _.uniq(reply);
// Keep the list under MAX_PEER_SIZE;
if (reply.length > MAX_PEER_SIZE) {
reply = reply.slice(0, MAX_PEER_SIZE);
}
reply = reply.join(",");
client.set(where, reply);
}
});
}
function removePeer(peer, where) {
client.get(where, (err, reply) => {
if (err) {
ERROR();
return;
}
else {
if (!reply)
return;
else {
reply = reply.split(",");
let index = reply.indexOf(peer);
if (index > -1) {
reply.splice(index, 1);
}
reply = reply.join(",");
client.set(where, reply);
}
}
});
}
function addrToBuffer(seeders, leechers, LEFT) {
// Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize
// Also we don't need to send the users own address
// If peer is a leecher, send more seeders; if peer is a seeder, send only leechers
let leecherCount = 0, seederCount = 0, peerBuffer = null, peerBufferSize = 0;
if (LEFT === 0 || !seeders || seeders === "")
seeders = new buffer_1.Buffer(0);
else {
seeders = seeders.split(",");
seederCount = seeders.length;
seeders = seeders.map((addressPort) => {
let addr = addressPort.split(":")[0];
let port = addressPort.split(":")[1];
addr = addr.split(".");
let b = new buffer_1.Buffer(6);
b.fill(0);
b.writeUInt8(addr[0], 0);
b.writeUInt8(addr[1], 1);
b.writeUInt8(addr[2], 2);
b.writeUInt8(addr[3], 3);
b.writeUInt16BE(port, 4);
return b;
});
seeders = buffer_1.Buffer.concat(seeders);
}
if (LEFT > 0 && seederCount > 50 && leechers > 15)
leechers = leechers.slice(0, 15);
if (!leechers || leechers === "")
leechers = new buffer_1.Buffer(0);
else {
leechers = leechers.split(",");
leecherCount = leechers.length;
leechers = leechers.map((addressPort) => {
let addr = addressPort.split(":")[0];
let port = addressPort.split(":")[1];
addr = addr.split(".");
let b = new buffer_1.Buffer(6);
b.fill(0);
b.writeUInt8(addr[0], 0);
b.writeUInt8(addr[1], 1);
b.writeUInt8(addr[2], 2);
b.writeUInt8(addr[3], 3);
b.writeUInt16BE(port, 4);
return b;
});
leechers = buffer_1.Buffer.concat(leechers);
}
peerBuffer = buffer_1.Buffer.concat([seeders, leechers]);
// Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize
return [leecherCount, seederCount, peerBuffer];
}
// Add a new hash to the swarm, ensure uniqeness
function addHash(hash) {
client.get("hashes", (err, reply) => {
if (err) {
ERROR();
return;
}
if (!reply)
reply = hash;
else
reply = hash + "," + reply;
reply = reply.split(",");
reply = _.uniq(reply);
reply = reply.join(",");
client.set("hashes", reply);
client.set(hash + ":time", Date.now());
});
}
function getHashes() {
let r = client.get("hashes", (err, reply) => {
if (err) {
ERROR();
return null;
}
reply = reply.split(",");
return reply;
});
return r;
}
}
function binaryToHex(str) {
if (typeof str !== "string") {
str = String(str);
}
return buffer_1.Buffer.from(str, "binary").toString("hex");
}
function hexToBinary(str) {
if (typeof str !== "string") {
str = String(str);
}
return buffer_1.Buffer.from(str, "hex").toString("binary");
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Server;
//# sourceMappingURL=/Users/connor/Desktop/Programming/myModules/peer-tracker/ts-node/b80e7f10257a0a2b7f29aee28a53e164f19fc5f2/98a6883f88ed207a422bce14e041cea9032231df.js.map
|
CraigglesO/peer-tracker
|
ts-node/b80e7f10257a0a2b7f29aee28a53e164f19fc5f2/98a6883f88ed207a422bce14e041cea9032231df.js
|
JavaScript
|
isc
| 23,105 |
var parseString = require('xml2js').parseString;
module.exports = function(req, res, next){
if (req.is('xml')){
var data = '';
req.setEncoding('utf8');
req.on('data', function(chunk){
data += chunk;
});
req.on('end', function(){
if (!data){
return next();
}
parseString(data, {
trim: true,
explicitArray: false
}, function(err, result){
if (!err){
req.body = result || {};
} else {
return res.error('BAD_REQUEST');
}
next();
});
});
} else {
next();
}
};
|
shcoder-ru/rest-req-res
|
middleware/xml-parser.js
|
JavaScript
|
isc
| 602 |
"use strict";
var CustomError = require('custom-error-instance');
var inventory = require('./inventory');
var menu = require('./menu');
var OrderError = CustomError('OrderError');
module.exports = function() {
var done = false;
var factory = {};
var store = {};
/**
* Add an item from the menu to the order.
* @param {string} name The name of the menu item to add.
*/
factory.add = function(name) {
var item = menu.get(name);
if (done) throw new OrderError('Order has been closed.', { code: 'EDONE' });
if (!item) throw new OrderError('Menu item does not exist: ' + name, { code: 'EDNE' });
if (!menu.available(name)) throw new OrderError('Insufficient inventory', { code: 'EINV' });
if (!store.hasOwnProperty(name)) store[name] = 0;
store[name]++;
item.ingredients.forEach(function(ingredient) {
inventory.changeQuantity(ingredient.name, -1 * ingredient.quantity);
});
return factory;
};
factory.checkout = function() {
done = true;
console.log('Order complete. Income: $' + factory.cost());
};
factory.cost = function() {
var total = 0;
Object.keys(store).forEach(function(menuItemName) {
var item = menu.get(menuItemName);
if (item) {
total += item.cost;
} else {
factory.remove(menuItemName);
}
});
return total;
};
factory.remove = function(name) {
var item;
if (done) throw new OrderError('Order has been closed.', { code: 'EDONE' });
if (!store.hasOwnProperty(name)) return;
store[name]--;
if (store[name] <= 0) delete store[name];
item = menu.get(name);
item.ingredients.forEach(function(ingredient) {
inventory.changeQuantity(ingredient.name, ingredient.quantity);
});
return factory;
};
return factory;
};
|
Gi60s/IT410
|
restaurant/order.js
|
JavaScript
|
isc
| 2,025 |
const test = require('tape')
const helpers = require('../test/helpers')
const bindFunc = helpers.bindFunc
const unary = require('./unary')
test('unary helper', t => {
const f = bindFunc(unary)
const err = /unary: Argument must be a Function/
t.throws(f(undefined), err, 'throws with undefined')
t.throws(f(null), err, 'throws with null')
t.throws(f(0), err, 'throws with falsey number')
t.throws(f(1), err, 'throws with truthy number')
t.throws(f(''), err, 'throws with falsey string')
t.throws(f('string'), err, 'throws with truthy string')
t.throws(f(false), err, 'throws with false')
t.throws(f(true), err, 'throws with true')
t.throws(f({}), err, 'throws with object')
t.throws(f([]), err, 'throws with array')
const fn = unary((x, y, z) => ({ x: x, y: y, z: z }))
t.same(fn(1, 2, 3), { x: 1, y: undefined, z: undefined }, 'only applies first argument to function')
t.end()
})
|
evilsoft/crocks
|
src/helpers/unary.spec.js
|
JavaScript
|
isc
| 917 |
export const DEFAULTS = {
API_BASE_URI: 'http://localhost:3000/axway',
granularity: 'monthly',
startDate: '2010-01-01',
cacheExpirySeconds: 300//5 minutes
};
export class Settings {
/**
* @param {string} setting
* @returns {*}
*/
getSetting(setting) {
return DEFAULTS[setting];
}
/**
* @param {string} customerNumber
* @param {string} meterType
* @returns {string} usageEndpoint
*/
getUsageEndpoint(customerNumber, meterType) {
return `/v1/customers/${customerNumber}/usage/${meterType}`;
}
}
export default new Settings;
|
scopevale/carpers-paradise
|
src/client/js/utils/Settings.js
|
JavaScript
|
isc
| 616 |
'use strict';
var DB = require('./lib/database');
var rc_util = require('./lib/utility.js');
var modelsFactory = require('./lib/models.js');
var selective = require('./program').selective;
var Promise = require('bluebird');
module.exports = function(dbUrl, commander, lastCrawl) {
return new Promise(function(resolve, reject) {
function useLatestCrawl(latestCrawl) {
var ipps = rc_util.getIpps(latestCrawl);
if (ipps) {
selective(ipps, commander)
.then(resolve)
.catch(reject);
}
}
if (lastCrawl) {
useLatestCrawl(lastCrawl);
} else {
rc_util.getLatestRow(dbUrl, commander.logsql)
.then(function(row) {
useLatestCrawl(JSON.parse(row.data));
})
.catch(reject);
}
});
};
|
bankonme/rippled-network-crawler
|
src/prior.js
|
JavaScript
|
isc
| 775 |
import {takeEvery} from 'redux-saga'
import {call, put, take, fork, select, cancel} from 'redux-saga/effects'
import * as Actions from './actions/actions'
let ws = null
const getUsername = state => state.username
function* createWebSocket(url) {
ws = new WebSocket(url)
let deferred, open_deferred, close_deferred, error_deferred;
ws.onopen = event => {
if (open_deferred) {
open_deferred.resolve(event)
open_deferred = null
}
}
ws.onmessage = event => {
if (deferred) {
deferred.resolve(JSON.parse(event.data))
deferred = null
}
}
ws.onerror = event => {
if (error_deferred) {
error_deferred.resolve(JSON.parse(event.data))
error_deferred = null
}
}
ws.onclose = event => {
if (close_deferred) {
close_deferred.resolve(event)
close_deferred = null
}
}
return {
open: {
nextMessage() {
if (!open_deferred) {
open_deferred = {}
open_deferred.promise = new Promise(resolve => open_deferred.resolve = resolve)
}
return open_deferred.promise
}
},
message: {
nextMessage() {
if (!deferred) {
deferred = {}
deferred.promise = new Promise(resolve => deferred.resolve = resolve)
}
return deferred.promise
}
},
error: {
nextMessage() {
if (!error_deferred) {
error_deferred = {}
error_deferred.promise = new Promise(resolve => error_deferred.resolve = resolve)
}
return error_deferred.promise
}
},
close: {
nextMessage() {
if (!close_deferred) {
close_deferred = {}
close_deferred.promise = new Promise(resolve => close_deferred.resolve = resolve)
}
return close_deferred.promise
}
}
}
}
function* watchOpen(ws) {
let msg = yield call(ws.nextMessage)
while (msg) {
yield put(Actions.connected(msg.srcElement))
msg = yield call(ws.nextMessage)
}
}
function* watchClose(ws) {
let msg = yield call(ws.nextMessage)
yield put(Actions.disconnected())
ws = null
}
function* watchErrors(ws) {
let msg = yield call(ws.nextMessage)
while (msg) {
msg = yield call(ws.nextMessage)
}
}
function* watchMessages(ws) {
let msg = yield call(ws.nextMessage)
while (msg) {
yield put(msg)
msg = yield call(ws.nextMessage)
}
}
function* connect() {
let openTask, msgTask, errTask, closeTask
while (true) {
const {ws_url} = yield take('connect')
const ws = yield call(createWebSocket, ws_url)
if (openTask) {
yield cancel(openTask)
yield cancel(msgTask)
yield cancel(errTask)
yield cancel(closeTask)
}
openTask = yield fork(watchOpen, ws.open)
msgTask = yield fork(watchMessages, ws.message)
errTask = yield fork(watchErrors, ws.error)
closeTask = yield fork(watchClose, ws.close)
}
}
const send = (data) => {
try {
ws.send(JSON.stringify(data))
} catch (error) {
alert("Send error: " + error)
}
}
function* login() {
while (true) {
const login_action = yield take('login')
send(login_action)
}
}
function* hello() {
while (true) {
const hello_action = yield take('hello')
const username = yield select(getUsername)
if (username) {
send(Actions.login(username))
}
}
}
function* disconnected() {
while (true) {
yield take('disconnected')
}
}
export default function* rootSaga() {
yield [
connect(),
hello(),
login(),
disconnected()
]
}
|
anyley/chat-sinatra-react
|
frontend/src/sagas.js
|
JavaScript
|
isc
| 4,180 |
import React from 'react';
const isArray = x => Array.isArray(x);
const isString = x => typeof x === 'string' && x.length > 0;
const isSelector = x => isString(x) && (startsWith(x, '.') || startsWith(x, '#'));
const isChildren = x => /string|number|boolean/.test(typeof x) || isArray(x);
const startsWith = (string, start) => string.indexOf(start) === 0;
const split = (string, separator) => string.split(separator);
const subString = (string, start, end) => string.substring(start, end);
const parseSelector = selector => {
const classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
const parts = split(selector, classIdSplit);
return parts.reduce((acc, part) => {
if (startsWith(part, '#')) {
acc.id = subString(part, 1);
} else if (startsWith(part, '.')) {
acc.className = `${acc.className} ${subString(part, 1)}`.trim();
}
return acc;
}, { className: '' });
};
const createElement = (nameOrType, properties = {}, children = []) => {
if (properties.isRendered !== undefined && !properties.isRendered) {
return null;
}
const { isRendered, ...props } = properties;
const args = [nameOrType, props];
if (!isArray(children)) {
args.push(children);
} else {
args.push(...children);
}
return React.createElement.apply(React, args);
};
export const hh = nameOrType => (first, second, third) => {
if (isSelector(first)) {
const selector = parseSelector(first);
// selector, children
if (isChildren(second)) {
return createElement(nameOrType, selector, second);
}
// selector, props, children
let { className = '' } = second || {};
className = `${selector.className} ${className} `.trim();
const props = { ...second, ...selector, className };
if (isChildren(third)) {
return createElement(nameOrType, props, third);
}
return createElement(nameOrType, props);
}
// children
if (isChildren(first)) {
return createElement(nameOrType, {}, first);
}
// props, children
if (isChildren(second)) {
return createElement(nameOrType, first, second);
}
return createElement(nameOrType, first);
};
const h = (nameOrType, ...rest) => hh(nameOrType)(...rest);
const TAG_NAMES = [
'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo',
'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col',
'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt',
'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4',
'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins',
'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem',
'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param',
'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select',
'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td',
'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'video',
'wbr', 'circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask',
'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'
];
module.exports = TAG_NAMES.reduce((exported, type) => {
exported[type] = hh(type);
return exported;
}, { h, hh });
|
Jador/react-hyperscript-helpers
|
src/index.js
|
JavaScript
|
isc
| 3,497 |
/**
* Created by Stefan on 9/19/2017
*/
/**
* Created by Stefan Endres on 08/16/2017.
*/
'use strict'
var http = require('http'),
https = require('https'),
url = require('url'),
util = require('util'),
fs = require('fs'),
path = require('path'),
sessions = require('./sessions'),
EventEmitter = require('events').EventEmitter;
function LHServer() {
this.fnStack = [];
this.defaultPort = 3000;
this.options = {};
this.viewEngine = null;
EventEmitter.call(this);
}
util.inherits(LHServer, EventEmitter);
LHServer.prototype.use = function(path, options, fn) {
if(typeof path === 'function') {
fn = path;
}
if(typeof options === 'function') {
fn = options;
}
if(!fn) return;
var fnObj = {
fn: fn,
method: null,
path: typeof path === 'string' ? path : null,
options: typeof options === 'object' ? options : {},
}
this.fnStack.push(fnObj);
}
LHServer.prototype.execute = function(req, res) {
var self = this;
var url_parts = url.parse(req.url);
var callbackStack = this.getFunctionList(url_parts.pathname, req.method);
if(callbackStack.length === 0) {
return;
}
var func = callbackStack.shift();
// add session capabilities
if(this.options['session']) {
var session = sessions.lookupOrCreate(req,{
lifetime: this.options['session'].lifetime || 604800,
secret: this.options['session'].secret || '',
});
if(!res.finished) {
res.setHeader('Set-Cookie', session.getSetCookieHeaderValue());
}
req.session = session;
}
// add template rendering
if(typeof this.options['view engine'] !== 'undefined') {
res.render = render.bind(this,res);
}
res.statusCode = 200;
res.send = send.bind(this,res);
res.redirect = redirect.bind(this,res);
res.status = status.bind(this,res);
res.header = header.bind(this,res);
try{
func.apply(this,[req,res, function(){self.callbackNextFunction(req,res,callbackStack)}]);
} catch (e) {
this.emit('error', e, res, req);
}
}
LHServer.prototype.callbackNextFunction = function(req,res,callbackStack) {
var self = this;
if(callbackStack.length === 0) {
return;
}
callbackStack[0] &&
callbackStack[0].apply &&
callbackStack[0].apply(this,[req,res,function() {
callbackStack.shift();
self.callbackNextFunction(req,res,callbackStack)
}]);
}
LHServer.prototype.listen = function(options, cb) {
var opt = {};
if(typeof options === 'number' || typeof options === 'string'){
opt.port = options;
} else {
opt = Object.assign(opt,options)
}
var httpServer;
if(opt.cert && opt.key) {
httpServer = https.createServer(opt, this.execute.bind(this)).listen(opt.port || this.defaultPort);
} else {
httpServer = http.createServer(this.execute.bind(this)).listen(opt.port || this.defaultPort);
}
if(httpServer) {
this.emit('ready');
};
cb && cb(httpServer);
}
LHServer.prototype.set = function(option, value) {
this.options[option] = value;
if(option === 'view engine' && value && value !== '') {
try {
this.viewEngine = require(value);
} catch (err) {
this.emit('error',err);
}
}
}
LHServer.prototype.getFunctionList = function(requestPath, method) {
var ret = [];
if(this.options['static']) {
ret.push(readStaticFile.bind(this));
}
for(var i in this.fnStack) {
var pathMatch = (
this.fnStack[i].options && this.fnStack[i].options.partialPath ?
this.fnStack[i].path === requestPath.substr(0, this.fnStack[i].path.length) :
this.fnStack[i].path === requestPath
) || this.fnStack[i].path === null;
if((this.fnStack[i].method === method || this.fnStack[i].method === null) &&
pathMatch) {
if(this.fnStack[i].fn) {
ret.push(this.fnStack[i].fn);
}
}
}
return ret;
}
LHServer.prototype.get =
LHServer.prototype.post =
LHServer.prototype.put =
LHServer.prototype.delete = function() {};
var methods = ['get', 'put', 'post', 'delete',];
methods.map(function(method) {
LHServer.prototype[method] = function(path, options, fn) {
if(typeof path === 'function') {
fn = path;
}
if(typeof options === 'function') {
fn = options;
}
if(!fn) return;
var fnObj = {
fn: fn,
method: method.toUpperCase(),
path: typeof path === 'string' ? path : null,
options: typeof options === 'object' ? options : {},
}
this.fnStack.push(fnObj);
}
})
function readStaticFile(req,res,next) {
if(res.finished){
return next && next();
}
var self = this;
var url_parts = url.parse(req.url);
var requestPath = path.normalize(url_parts.pathname ).replace(/^(\.\.(\/|\\|$))+/, '');
if(requestPath === '/'){
requestPath = '/index.html'
}
var filePath = path.join(this.options['static'],requestPath);
const contentTypes = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword'
};
var fExt = path.extname(filePath);
var contentType;
if(fExt && contentTypes.hasOwnProperty(fExt)) {
contentType = contentTypes[fExt];
} else {
return next && next();
}
fs.readFile(filePath, function(err, content) {
if (err) {
return next && next();
}
else {
res.header('Content-Type', contentType);
res.header('Content-Length', Buffer.byteLength(content));
res.writeHead(
res.statusCode,
res.headerValues
);
res.end(content, 'utf-8');
return next && next();
}
});
}
function send(res, data) {
if(res.finished){
return;
}
var contentType = 'text/html';
var responseBody = data;
if(typeof data === 'object') {
contentType = 'application/json'
responseBody = JSON.stringify(data);
}
res.header('Content-Type', contentType)
res.header('Content-Length', Buffer.byteLength(responseBody))
res.writeHead(
res.statusCode,
res.headerValues
);
res.end(responseBody);
}
function render(res,template,options,callback){
if(res.finished){
return;
}
var self = this;
if(typeof self.viewEngine === 'undefined') {
return callback && callback();
}
if(self.viewEngine.renderFile) {
return self.viewEngine.renderFile(
(self.options['views'] || '') + '/'+template+'.pug',
options, function(err, result) {
if(err){
self.emit('error',err);
}
if(result){
res.header('Content-Type', 'text/html')
res.header('Content-Length', Buffer.byteLength(result))
res.writeHead(
res.statusCode,
res.headerValues
);
res.end(result);
}
callback && callback(err,result);
}
)
}
}
function status(res,code) {
res.statusCode = code;
}
function header(res, key, value) {
if(typeof res.headerValues === 'undefined'){
res.headerValues = {};
}
res.headerValues[key] = value
}
function redirect(res,url) {
var address = url;
var status = 302;
if (arguments.length === 3) {
if (typeof arguments[1] === 'number') {
status = arguments[1];
address = arguments[2];
}
}
var responseBody = 'Redirecting to ' + address;
res.header('Content-Type', 'text/html')
res.header('Cache-Control', 'no-cache')
res.header('Content-Length', Buffer.byteLength(responseBody))
res.header('Location', address)
res.writeHead(
status,
res.headerValues
);
res.end(responseBody);
};
module.exports = new LHServer();
|
endresstefan/light-http-server
|
lib/server.js
|
JavaScript
|
isc
| 8,582 |
'use strict';
import path from 'path';
import webpack, { optimize, HotModuleReplacementPlugin, NoErrorsPlugin } from 'webpack';
export default {
devtool: 'eval-cheap-module-source-map',
entry: [
'webpack-hot-middleware/client',
'./app/js/bootstrap'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new optimize.OccurenceOrderPlugin(),
new HotModuleReplacementPlugin(),
new NoErrorsPlugin()
],
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel'],
exclude: path.resolve(__dirname, 'node_modules'),
include: [
path.resolve(__dirname)
]
}
]
}
};
|
hyphenbash/movies-search
|
webpack.config.js
|
JavaScript
|
isc
| 668 |
'use strict';
var expect = chai.expect;
function run(scope,done) {
done();
}
describe('SendCtrl', function(){
var rootScope, scope, controller_injector, dependencies, ctrl,
sendForm, network, timeout, spy, stub, mock, res, transaction, data;
beforeEach(module("rp"));
beforeEach(inject(function($rootScope, $controller, $q, $timeout, rpNetwork) {
network = rpNetwork;
rootScope = rootScope;
timeout = $timeout;
scope = $rootScope.$new();
scope.currencies_all = [{ name: 'XRP - Ripples', value: 'XRP'}];
controller_injector = $controller;
// Stub the sendForm, which should perhaps be tested using
// End To End tests
scope.sendForm = {
send_destination: {
$setValidity: function(){}
},
$setPristine: function(){},
$setValidity: function(){}
};
scope.$apply = function(func){func()};
scope.saveAddressForm = {
$setPristine: function () {}
}
scope.check_dt_visibility = function () {};
dependencies = {
$scope: scope,
$element: null,
$network: network,
rpId: {
loginStatus: true,
account: 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk'
}
}
ctrl = controller_injector("SendCtrl", dependencies);
}));
it('should be initialized with defaults', function (done) {
assert.equal(scope.mode, 'form');
assert.isObject(scope.send);
assert.equal(scope.send.currency, 'XRP - Ripples');
assert.isFalse(scope.show_save_address_form);
assert.isFalse(scope.addressSaved);
assert.equal(scope.saveAddressName, '');
assert.isFalse(scope.addressSaving);
done()
});
it('should reset destination dependencies', function (done) {
assert.isFunction(scope.reset_destination_deps);
done();
});
describe('updating the destination', function (done) {
beforeEach(function () {
scope.send.recipient_address = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk';
})
it('should have a function to do so', function (done) {
assert.isFunction(scope.update_destination);
done();
});
describe('when the recipient is the same as last time', function (done) {
beforeEach(function () {
scope.send.last_recipient = scope.send.recipient_address;
});
it('should not reset destination dependencies', function (done) {
spy = sinon.spy(scope, 'reset_destination_deps');
scope.update_destination();
assert(spy.notCalled);
done();
});
it('should not check destination tag visibility', function (done) {
spy = sinon.spy(scope, 'check_dt_visibility');
scope.update_destination();
assert(spy.notCalled);
done();
});
});
describe('when the recipient is new', function (done) {
beforeEach(function () {
scope.send.last_recipient = null;
});
it('should reset destination dependencies', function (done) {
spy = sinon.spy(scope, 'reset_destination_deps');
scope.update_destination();
assert(spy.called);
done();
});
it('should check destination tag visibility', function (done) {
spy = sinon.spy(scope, 'check_dt_visibility');
scope.update_destination();
assert(spy.called);
done();
});
});
})
describe('updating the destination remote', function (done) {
it('should have a function to do so', function (done) {
assert.isFunction(scope.update_destination_remote);
done();
});
it('should validate the federation field by default', function (done) {
var setValiditySpy = sinon.spy(
scope.sendForm.send_destination, '$setValidity');
scope.update_destination_remote();
assert(setValiditySpy.withArgs('federation', true).called);
done();
})
describe('when it is not bitcoin', function (done) {
beforeEach(function () {
scope.send.bitcoin = null
})
it('should check destination', function (done) {
var spy = sinon.spy(scope, 'check_destination');
scope.update_destination_remote();
assert(spy.calledOnce);
done();
});
});
describe('when it is bitcoin', function (done) {
beforeEach(function () {
scope.send.bitcoin = true;
});
it('should update currency constraints', function (done) {
var spy = sinon.spy(scope, 'update_currency_constraints');
scope.update_destination_remote();
spy.should.have.been.calledOnce;
done();
});
it('should not check destination', function (done) {
var spy = sinon.spy(scope, 'check_destination');
scope.update_destination_remote();
assert(!spy.called);
done();
});
})
})
it('should check the destination', function (done) {
assert.isFunction(scope.check_destination);
done();
})
it('should handle paths', function (done) {
assert.isFunction(scope.handle_paths);
done();
});
it('should update paths', function (done) {
assert.isFunction(scope.update_paths);
done();
});
describe('updating currency constraints', function () {
it('should have a function to do so', function (done) {
assert.isFunction(scope.update_currency_constraints);
done();
});
it('should update the currency', function (done) {
stub = sinon.stub(scope, 'update_currency');
scope.update_currency_constraints();
assert(spy.called);
done();
});
describe('when recipient info is not loaded', function () {
it('should not update the currency', function (done) {
stub = sinon.stub(scope, 'update_currency');
scope.send.recipient_info.loaded = false;
scope.update_currency_constraints();
assert(spy.called);
done();
});
});
});
it('should reset the currency dependencies', function (done) {
assert.isFunction(scope.reset_currency_deps);
var spy = sinon.spy(scope, 'reset_amount_deps');
scope.reset_currency_deps();
assert(spy.calledOnce);
done();
});
it('should update the currency', function (done) {
assert.isFunction(scope.update_currency);
done();
});
describe('resetting the amount dependencies', function (done) {
it('should have a function to do so', function (done) {
assert.isFunction(scope.reset_amount_deps);
done();
});
it('should set the quote to false', function (done) {
scope.send.quote = true;
scope.reset_amount_deps();
assert.isFalse(scope.send.quote);
done();
});
it('should falsify the sender insufficient xrp flag', function (done) {
scope.send.sender_insufficient_xrp = true;
scope.reset_amount_deps();
assert.isFalse(scope.send.sender_insufficient_xrp);
done();
});
it('should reset the paths', function (done) {
spy = sinon.spy(scope, 'reset_paths');
scope.reset_amount_deps();
assert(spy.calledOnce);
done();
});
});
it('should update the amount', function (done) {
assert.isFunction(scope.update_amount);
done();
});
it('should update the quote', function (done) {
assert.isFunction(scope.update_quote);
done();
});
describe('resetting paths', function (done) {
it('should have a function to do so', function (done) {
assert.isFunction(scope.reset_paths);
done();
});
it('should set the send alternatives to an empty array', function (done) {
scope.send.alternatives = ['not_an_empty_array'];
scope.reset_paths();
assert(Array.isArray(scope.send.alternatives));
assert.equal(scope.send.alternatives.length, 0);
done();
});
});
it('should rest the paths', function (done) {
assert.isFunction(scope.reset_paths);
done();
});
it('should cancel the form', function (done) {
assert.isFunction(scope.cancelConfirm);
scope.send.alt = '';
scope.mode = null;
scope.cancelConfirm();
assert.equal(scope.mode, 'form');
assert.isNull(scope.send.alt);
done();
});
describe('resetting the address form', function () {
it('should have a function to do so', function (done) {
assert.isFunction(scope.resetAddressForm);
done();
});
it('should falsify show_save_address_form field', function (done) {
scope.show_save_address_form = true
scope.resetAddressForm();
assert.isFalse(scope.show_save_address_form);
done();
});
it('should falsify the addressSaved field', function (done) {
scope.addressSaved = true;
scope.resetAddressForm();
assert.isFalse(scope.addressSaved);
done();
});
it('should falsify the addressSaving field', function (done) {
scope.saveAddressName = null;
scope.resetAddressForm();
assert.equal(scope.saveAddressName, '');
done();
});
it('should empty the saveAddressName field', function (done) {
scope.addressSaving = true;
scope.resetAddressForm();
assert.isFalse(scope.addressSaving);
done();
});
it('should set the form to pristine state', function (done) {
spy = sinon.spy(scope.saveAddressForm, '$setPristine');
scope.resetAddressForm();
assert(spy.calledOnce);
done();
});
});
describe('performing reset goto', function () {
it('should have a function to do so', function (done) {
assert.isFunction(scope.reset_goto);
done();
});
it('should reset the scope', function (done) {
spy = sinon.spy(scope, 'reset');
scope.reset_goto();
assert(spy.calledOnce);
done();
});
it('should navigate the page to the tabname provide', function (done) {
var tabName = 'someAwesomeTab';
scope.reset_goto(tabName);
assert.equal(document.location.hash, '#' + tabName);
done();
});
})
it('should perform a reset goto', function (done) {
var mock = sinon.mock(scope);
mock.expects('reset').once();
scope.reset_goto();
mock.verify();
done();
});
describe("handling when the send is prepared", function () {
it('should have a function to do so', function (done) {
assert.isFunction(scope.send_prepared);
done();
});
it('should set confirm wait to true', function (done) {
scope.send_prepared();
assert.isTrue(scope.confirm_wait);
done();
});
it("should set the mode to 'confirm'", function (done) {
assert.notEqual(scope.mode, 'confirm');
scope.send_prepared();
assert.equal(scope.mode, 'confirm');
done();
})
it('should set confirm_wait to false after a timeout', function (done) {
scope.send_prepared();
assert.isTrue(scope.confirm_wait);
// For some reason $timeout.flush() works but then raises an exception
try { timeout.flush() }
catch (e) {}
assert.isFalse(scope.confirm_wait);
done();
});
});
describe('handling when a transaction send is confirmed', function (done) {
beforeEach(function () {
scope.send.recipient_address = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk';
});
describe("handling a 'propose' event from ripple-lib", function (done) {
beforeEach(function () {
scope.send = {
amount_feedback: {
currency: function () {
function to_human () {
return 'somestring';
}
return { to_human: to_human }
}
}
}
transaction = {
hash: 'E64165A4ED2BF36E5922B11C4E192DF068E2ADC21836087DE5E0B1FDDCC9D82F'
}
res = {
engine_result: 'arbitrary_engine_result',
engine_result_message: 'arbitrary_engine_result_message'
}
});
it('should call send with the transaction hash', function (done) {
spy = sinon.spy(scope, 'sent');
scope.onTransactionProposed(res, transaction);
assert(spy.calledWith(transaction.hash));
done();
});
it('should set the engine status with the response', function (done) {
spy = sinon.spy(scope, 'setEngineStatus');
scope.onTransactionProposed(res, transaction);
assert(spy.called);
done();
});
});
describe("handling errors from the server", function () {
describe("any error", function (done) {
it('should set the mode to error', function (done) {
var res = { error: null };
scope.onTransactionError(res, null);
setTimeout(function (){
assert.equal(scope.mode, "error");
done();
}, 10)
});
});
});
it('should have a function to handle send confirmed', function (done) {
assert.isFunction(scope.send_confirmed);
done();
});
it('should create a transaction', function (done) {
spy = sinon.spy(network.remote, 'transaction');
scope.send_confirmed();
assert(spy.called);
done();
});
})
describe('saving an address', function () {
beforeEach(function () {
scope.userBlob = {
data: {
contacts: []
}
};
});
it('should have a function to do so', function (done) {
assert.isFunction(scope.saveAddress);
done();
});
it("should set the addressSaving property to true", function (done) {
assert.isFalse(scope.addressSaving);
scope.saveAddress();
assert.isTrue(scope.addressSaving);
done();
})
it("should listen for blobSave event", function (done) {
var onBlobSaveSpy = sinon.spy(scope, '$on');
scope.saveAddress();
assert(onBlobSaveSpy.withArgs('$blobSave').calledOnce);
done();
});
it("should add the contact to the blob's contacts", function (done) {
assert(scope.userBlob.data.contacts.length == 0);
scope.saveAddress();
assert(scope.userBlob.data.contacts.length == 1);
done();
});
describe('handling a blobSave event', function () {
describe('having called saveAddress', function () {
beforeEach(function () {
scope.saveAddress();
});
it('should set addressSaved to true', function (done) {
assert.isFalse(scope.addressSaved);
scope.$emit('$blobSave');
assert.isTrue(scope.addressSaved);
done();
});
it("should set the contact as the scope's contact", function (done) {
assert.isUndefined(scope.contact);
scope.$emit('$blobSave');
assert.isObject(scope.contact);
done();
});
})
describe('without having called saveAddress', function () {
it('should not set addressSaved', function (done) {
assert.isFalse(scope.addressSaved);
scope.$emit('$blobSave');
assert.isFalse(scope.addressSaved);
done();
});
})
})
});
describe('setting engine status', function () {
beforeEach(function () {
res = {
engine_result: 'arbitrary_engine_result',
engine_result_message: 'arbitrary_engine_result_message'
}
});
describe("when the response code is 'tes'", function() {
beforeEach(function () {
res.engine_result = 'tes';
})
describe('when the transaction is accepted', function () {
it("should set the transaction result to cleared", function (done) {
var accepted = true;
scope.setEngineStatus(res, accepted);
assert.equal(scope.tx_result, 'cleared');
done();
});
});
describe('when the transaction not accepted', function () {
it("should set the transaction result to pending", function (done) {
var accepted = false;
scope.setEngineStatus(res, accepted);
assert.equal(scope.tx_result, 'pending');
done();
});
});
});
describe("when the response code is 'tep'", function() {
beforeEach(function () {
res.engine_result = 'tep';
})
it("should set the transaction result to partial", function (done) {
scope.setEngineStatus(res, true);
assert.equal(scope.tx_result, 'partial');
done();
});
});
});
describe('handling sent transactions', function () {
it('should update the mode to status', function (done) {
assert.isFunction(scope.sent);
assert.equal(scope.mode, 'form');
scope.sent();
assert.equal(scope.mode, 'status');
done();
})
it('should listen for transactions on the network', function (done) {
var remoteListenerSpy = sinon.spy(network.remote, 'on');
scope.sent();
assert(remoteListenerSpy.calledWith('transaction'));
done();
})
describe('handling a transaction event', function () {
beforeEach(function () {
var hash = 'testhash';
scope.sent(hash);
data = {
transaction: {
hash: hash
}
}
stub = sinon.stub(scope, 'setEngineStatus');
});
afterEach(function () {
scope.setEngineStatus.restore();
})
it('should set the engine status', function (done) {
network.remote.emit('transaction', data);
assert(stub.called);
done();
});
it('should stop listening for transactions', function (done) {
spy = sinon.spy(network.remote, 'removeListener');
network.remote.emit('transaction', data);
assert(spy.called);
done();
})
})
})
});
|
yxxyun/ripple-client
|
test/unit/tabs/sendControllerSpec.js
|
JavaScript
|
isc
| 17,667 |
"use strict";
(function (ConflictType) {
ConflictType[ConflictType["IndividualAttendeeConflict"] = 0] = "IndividualAttendeeConflict";
ConflictType[ConflictType["GroupConflict"] = 1] = "GroupConflict";
ConflictType[ConflictType["GroupTooBigConflict"] = 2] = "GroupTooBigConflict";
ConflictType[ConflictType["UnknownAttendeeConflict"] = 3] = "UnknownAttendeeConflict";
})(exports.ConflictType || (exports.ConflictType = {}));
var ConflictType = exports.ConflictType;
|
eino-makitalo/ews-javascript-npmbuild
|
js/Enumerations/ConflictType.js
|
JavaScript
|
mit
| 481 |
export default function applyLocationOffset(rect, location, isOffsetBody) {
var top = rect.top;
var left = rect.left;
if (isOffsetBody) {
left = 0;
top = 0;
}
return {
top: top + location.top,
left: left + location.left,
height: rect.height,
width: rect.width
};
}
//# sourceMappingURL=apply-location-offset.js.map
|
antpost/antpost-client
|
node_modules/@progress/kendo-popup-common/dist/es/apply-location-offset.js
|
JavaScript
|
mit
| 390 |
KB.component('task-move-position', function (containerElement, options) {
function getSelectedValue(id) {
var element = KB.dom(document).find('#' + id);
if (element) {
return parseInt(element.options[element.selectedIndex].value);
}
return null;
}
function getSwimlaneId() {
var swimlaneId = getSelectedValue('form-swimlanes');
return swimlaneId === null ? options.board[0].id : swimlaneId;
}
function getColumnId() {
var columnId = getSelectedValue('form-columns');
return columnId === null ? options.board[0].columns[0].id : columnId;
}
function getPosition() {
var position = getSelectedValue('form-position');
return position === null ? 1 : position;
}
function getPositionChoice() {
var element = KB.find('input[name=positionChoice]:checked');
if (element) {
return element.value;
}
return 'before';
}
function onSwimlaneChanged() {
var columnSelect = KB.dom(document).find('#form-columns');
KB.dom(columnSelect).replace(buildColumnSelect());
var taskSection = KB.dom(document).find('#form-tasks');
KB.dom(taskSection).replace(buildTasks());
}
function onColumnChanged() {
var taskSection = KB.dom(document).find('#form-tasks');
KB.dom(taskSection).replace(buildTasks());
}
function onError(message) {
KB.trigger('modal.stop');
KB.find('#message-container')
.replace(KB.dom('div')
.attr('id', 'message-container')
.attr('class', 'alert alert-error')
.text(message)
.build()
);
}
function onSubmit() {
var position = getPosition();
var positionChoice = getPositionChoice();
if (positionChoice === 'after') {
position++;
}
KB.find('#message-container').replace(KB.dom('div').attr('id', 'message-container').build());
KB.http.postJson(options.saveUrl, {
"column_id": getColumnId(),
"swimlane_id": getSwimlaneId(),
"position": position
}).success(function () {
window.location.reload(true);
}).error(function (response) {
if (response) {
onError(response.message);
}
});
}
function buildSwimlaneSelect() {
var swimlanes = [];
options.board.forEach(function(swimlane) {
swimlanes.push({'value': swimlane.id, 'text': swimlane.name});
});
return KB.dom('select')
.attr('id', 'form-swimlanes')
.change(onSwimlaneChanged)
.for('option', swimlanes)
.build();
}
function buildColumnSelect() {
var columns = [];
var swimlaneId = getSwimlaneId();
options.board.forEach(function(swimlane) {
if (swimlaneId === swimlane.id) {
swimlane.columns.forEach(function(column) {
columns.push({'value': column.id, 'text': column.title});
});
}
});
return KB.dom('select')
.attr('id', 'form-columns')
.change(onColumnChanged)
.for('option', columns)
.build();
}
function buildTasks() {
var tasks = [];
var swimlaneId = getSwimlaneId();
var columnId = getColumnId();
var container = KB.dom('div').attr('id', 'form-tasks');
options.board.forEach(function (swimlane) {
if (swimlaneId === swimlane.id) {
swimlane.columns.forEach(function (column) {
if (columnId === column.id) {
column.tasks.forEach(function (task) {
tasks.push({'value': task.position, 'text': '#' + task.id + ' - ' + task.title});
});
}
});
}
});
if (tasks.length > 0) {
container
.add(KB.html.label(options.positionLabel, 'form-position'))
.add(KB.dom('select').attr('id', 'form-position').for('option', tasks).build())
.add(KB.html.radio(options.beforeLabel, 'positionChoice', 'before'))
.add(KB.html.radio(options.afterLabel, 'positionChoice', 'after'))
;
}
return container.build();
}
this.render = function () {
KB.on('modal.submit', onSubmit);
var form = KB.dom('div')
.on('submit', onSubmit)
.add(KB.dom('div').attr('id', 'message-container').build())
.add(KB.html.label(options.swimlaneLabel, 'form-swimlanes'))
.add(buildSwimlaneSelect())
.add(KB.html.label(options.columnLabel, 'form-columns'))
.add(buildColumnSelect())
.add(buildTasks())
.build();
containerElement.appendChild(form);
};
});
|
lianguan/kanboard
|
assets/js/components/task-move-position.js
|
JavaScript
|
mit
| 5,050 |
const AES = require('./aesjs');
function encrypt(text, key) {
key = new TextEncoder().encode(key);
const textBytes = AES.utils.utf8.toBytes(text);
const aesCtr = new AES.ModeOfOperation.ctr(key);
const encryptedBytes = aesCtr.encrypt(textBytes);
return AES.utils.hex.fromBytes(encryptedBytes);
}
function decrypt(encryptedHex, key) {
key = new TextEncoder().encode(key);
const encryptedBytes = AES.utils.hex.toBytes(encryptedHex);
const aesCtr = new AES.ModeOfOperation.ctr(key);
const decryptedBytes = aesCtr.decrypt(encryptedBytes);
return AES.utils.utf8.fromBytes(decryptedBytes);
}
module.exports = {
encrypt,
decrypt,
};
|
cheminfo-js/visualizer-helper
|
util/aes.js
|
JavaScript
|
mit
| 653 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _index = require('../../isSameWeek/index.js');
var _index2 = _interopRequireDefault(_index);
var _index3 = require('../_lib/convertToFP/index.js');
var _index4 = _interopRequireDefault(_index3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// This file is generated automatically by `scripts/build/fp.js`. Please, don't change it.
var isSameWeekWithOptions = (0, _index4.default)(_index2.default, 3);
exports.default = isSameWeekWithOptions;
module.exports = exports['default'];
|
lucionei/chamadotecnico
|
chamadosTecnicosFinal-app/node_modules/date-fns/fp/isSameWeekWithOptions/index.js
|
JavaScript
|
mit
| 621 |
angular.module('EggApp', ['ngRoute'], function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/app/view/search.html',
controller: 'SearchController'
})
.when('/show/:id', {
templateUrl: '/app/view/show.html',
controller: 'ShowController'
})
.otherwise({
redirectTo: '/'
});
});
|
kamilbiela/bowereggs-frontend
|
app/app.js
|
JavaScript
|
mit
| 402 |
var Phaser = require('phaser-unofficial');
/**
* Wall class.
* @param {object} game
* @param {number} x
* @param {number} y
*/
Wall = function (game, x, y) {
Phaser.Sprite.call(this, game, x, y, 'paddle');
this.game.physics.arcade.enable(this);
this.width = 200;
this.height = this.game.world.bounds.height;
this.blendMode = Phaser.blendModes.ADD;
this.body.bounce.setTo(1, 1);
this.body.immovable = true;
this.alpha = 0;
};
Wall.prototype = Object.create(Phaser.Sprite.prototype);
Wall.prototype.constructor = Wall;
module.exports = Wall;
|
cognizo/bogey-pong
|
lib/wall.js
|
JavaScript
|
mit
| 581 |
exports.definition = {
/**
* Add custom methods to your Model`s Records
* just define a function:
* ```js
* this.function_name = function(){
* //this == Record
* };
* ```
* This will automatically add the new method to your Record
*
* @class Definition
* @name Custom Record Methods
*
*/
mixinCallback: function() {
var objKeys = []
var self = this
this.use(function() {
// get all current property names
objKeys = Object.keys(this)
}, 90)
this.on('finished', function() {
// an now search for new ones ==> instance methods for our new model class
Object.keys(self).forEach(function(name) {
if (objKeys.indexOf(name) === -1) {
self.instanceMethods[name] = self[name]
delete self[name]
}
})
})
}
}
|
PhilWaldmann/openrecord
|
lib/base/methods.js
|
JavaScript
|
mit
| 843 |
/* ----------------------------------
* PUSH v2.0.0
* Licensed under The MIT License
* inspired by chris's jquery.pjax.js
* http://opensource.org/licenses/MIT
* ---------------------------------- */
!function () {
var noop = function () {};
// Pushstate cacheing
// ==================
var isScrolling;
var maxCacheLength = 20;
var cacheMapping = sessionStorage;
var domCache = {};
var transitionMap = {
'slide-in' : 'slide-out',
'slide-out' : 'slide-in',
'fade' : 'fade'
};
var bars = {
bartab : '.bar-tab',
barnav : '.bar-nav',
barfooter : '.bar-footer',
barheadersecondary : '.bar-header-secondary'
};
var cacheReplace = function (data, updates) {
PUSH.id = data.id;
if (updates) data = getCached(data.id);
cacheMapping[data.id] = JSON.stringify(data);
window.history.replaceState(data.id, data.title, data.url);
domCache[data.id] = document.body.cloneNode(true);
};
var cachePush = function () {
var id = PUSH.id;
var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]');
var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]');
cacheBackStack.push(id);
while (cacheForwardStack.length) delete cacheMapping[cacheForwardStack.shift()];
while (cacheBackStack.length > maxCacheLength) delete cacheMapping[cacheBackStack.shift()];
window.history.pushState(null, '', cacheMapping[PUSH.id].url);
cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack);
cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack);
};
var cachePop = function (id, direction) {
var forward = direction == 'forward';
var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]');
var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]');
var pushStack = forward ? cacheBackStack : cacheForwardStack;
var popStack = forward ? cacheForwardStack : cacheBackStack;
if (PUSH.id) pushStack.push(PUSH.id);
popStack.pop();
cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack);
cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack);
};
var getCached = function (id) {
return JSON.parse(cacheMapping[id] || null) || {};
};
var getTarget = function (e) {
var target = findTarget(e.target);
if (
! target
|| e.which > 1
|| e.metaKey
|| e.ctrlKey
|| isScrolling
|| location.protocol !== target.protocol
|| location.host !== target.host
|| !target.hash && /#/.test(target.href)
|| target.hash && target.href.replace(target.hash, '') === location.href.replace(location.hash, '')
|| target.getAttribute('data-ignore') == 'push'
) return;
return target;
};
// Main event handlers (touchend, popstate)
// ==========================================
var touchend = function (e) {
var target = getTarget(e);
if (!target) return;
e.preventDefault();
PUSH({
url : target.href,
hash : target.hash,
timeout : target.getAttribute('data-timeout'),
transition : target.getAttribute('data-transition')
});
};
var popstate = function (e) {
var key;
var barElement;
var activeObj;
var activeDom;
var direction;
var transition;
var transitionFrom;
var transitionFromObj;
var id = e.state;
if (!id || !cacheMapping[id]) return;
direction = PUSH.id < id ? 'forward' : 'back';
cachePop(id, direction);
activeObj = getCached(id);
activeDom = domCache[id];
if (activeObj.title) document.title = activeObj.title;
if (direction == 'back') {
transitionFrom = JSON.parse(direction == 'back' ? cacheMapping.cacheForwardStack : cacheMapping.cacheBackStack);
transitionFromObj = getCached(transitionFrom[transitionFrom.length - 1]);
} else {
transitionFromObj = activeObj;
}
if (direction == 'back' && !transitionFromObj.id) return PUSH.id = id;
transition = direction == 'back' ? transitionMap[transitionFromObj.transition] : transitionFromObj.transition;
if (!activeDom) {
return PUSH({
id : activeObj.id,
url : activeObj.url,
title : activeObj.title,
timeout : activeObj.timeout,
transition : transition,
ignorePush : true
});
}
if (transitionFromObj.transition) {
activeObj = extendWithDom(activeObj, '.content', activeDom.cloneNode(true));
for (key in bars) {
barElement = document.querySelector(bars[key])
if (activeObj[key]) swapContent(activeObj[key], barElement);
else if (barElement) barElement.parentNode.removeChild(barElement);
}
}
swapContent(
(activeObj.contents || activeDom).cloneNode(true),
document.querySelector('.content'),
transition
);
PUSH.id = id;
document.body.offsetHeight; // force reflow to prevent scroll
};
// Core PUSH functionality
// =======================
var PUSH = function (options) {
var key;
var data = {};
var xhr = PUSH.xhr;
options.container = options.container || options.transition ? document.querySelector('.content') : document.body;
for (key in bars) {
options[key] = options[key] || document.querySelector(bars[key]);
}
if (xhr && xhr.readyState < 4) {
xhr.onreadystatechange = noop;
xhr.abort()
}
xhr = new XMLHttpRequest();
xhr.open('GET', options.url, true);
xhr.setRequestHeader('X-PUSH', 'true');
xhr.onreadystatechange = function () {
if (options._timeout) clearTimeout(options._timeout);
if (xhr.readyState == 4) xhr.status == 200 ? success(xhr, options) : failure(options.url);
};
if (!PUSH.id) {
cacheReplace({
id : +new Date,
url : window.location.href,
title : document.title,
timeout : options.timeout,
transition : null
});
}
if (options.timeout) {
options._timeout = setTimeout(function () { xhr.abort('timeout'); }, options.timeout);
}
xhr.send();
if (xhr.readyState && !options.ignorePush) cachePush();
};
// Main XHR handlers
// =================
var success = function (xhr, options) {
var key;
var barElement;
var data = parseXHR(xhr, options);
if (!data.contents) return locationReplace(options.url);
if (data.title) document.title = data.title;
if (options.transition) {
for (key in bars) {
barElement = document.querySelector(bars[key])
if (data[key]) swapContent(data[key], barElement);
else if (barElement) barElement.parentNode.removeChild(barElement);
}
}
swapContent(data.contents, options.container, options.transition, function () {
cacheReplace({
id : options.id || +new Date,
url : data.url,
title : data.title,
timeout : options.timeout,
transition : options.transition
}, options.id);
triggerStateChange();
});
if (!options.ignorePush && window._gaq) _gaq.push(['_trackPageview']) // google analytics
if (!options.hash) return;
};
var failure = function (url) {
throw new Error('Could not get: ' + url)
};
// PUSH helpers
// ============
var swapContent = function (swap, container, transition, complete) {
var enter;
var containerDirection;
var swapDirection;
if (!transition) {
if (container) container.innerHTML = swap.innerHTML;
else if (swap.classList.contains('content')) document.body.appendChild(swap);
else document.body.insertBefore(swap, document.querySelector('.content'));
} else {
enter = /in$/.test(transition);
if (transition == 'fade') {
container.classList.add('in');
container.classList.add('fade');
swap.classList.add('fade');
}
if (/slide/.test(transition)) {
swap.classList.add('sliding-in', enter ? 'right' : 'left');
swap.classList.add('sliding');
container.classList.add('sliding');
}
container.parentNode.insertBefore(swap, container);
}
if (!transition) complete && complete();
if (transition == 'fade') {
container.offsetWidth; // force reflow
container.classList.remove('in');
container.addEventListener('webkitTransitionEnd', fadeContainerEnd);
function fadeContainerEnd() {
container.removeEventListener('webkitTransitionEnd', fadeContainerEnd);
swap.classList.add('in');
swap.addEventListener('webkitTransitionEnd', fadeSwapEnd);
}
function fadeSwapEnd () {
swap.removeEventListener('webkitTransitionEnd', fadeSwapEnd);
container.parentNode.removeChild(container);
swap.classList.remove('fade');
swap.classList.remove('in');
complete && complete();
}
}
if (/slide/.test(transition)) {
container.offsetWidth; // force reflow
swapDirection = enter ? 'right' : 'left'
containerDirection = enter ? 'left' : 'right'
container.classList.add(containerDirection);
swap.classList.remove(swapDirection);
swap.addEventListener('webkitTransitionEnd', slideEnd);
function slideEnd() {
swap.removeEventListener('webkitTransitionEnd', slideEnd);
swap.classList.remove('sliding', 'sliding-in');
swap.classList.remove(swapDirection);
container.parentNode.removeChild(container);
complete && complete();
}
}
};
var triggerStateChange = function () {
var e = new CustomEvent('push', {
detail: { state: getCached(PUSH.id) },
bubbles: true,
cancelable: true
});
window.dispatchEvent(e);
};
var findTarget = function (target) {
var i, toggles = document.querySelectorAll('a');
for (; target && target !== document; target = target.parentNode) {
for (i = toggles.length; i--;) { if (toggles[i] === target) return target; }
}
};
var locationReplace = function (url) {
window.history.replaceState(null, '', '#');
window.location.replace(url);
};
var parseURL = function (url) {
var a = document.createElement('a'); a.href = url; return a;
};
var extendWithDom = function (obj, fragment, dom) {
var i;
var result = {};
for (i in obj) result[i] = obj[i];
Object.keys(bars).forEach(function (key) {
var el = dom.querySelector(bars[key]);
if (el) el.parentNode.removeChild(el);
result[key] = el;
});
result.contents = dom.querySelector(fragment);
return result;
};
var parseXHR = function (xhr, options) {
var head;
var body;
var data = {};
var responseText = xhr.responseText;
data.url = options.url;
if (!responseText) return data;
if (/<html/i.test(responseText)) {
head = document.createElement('div');
body = document.createElement('div');
head.innerHTML = responseText.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0]
body.innerHTML = responseText.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0]
} else {
head = body = document.createElement('div');
head.innerHTML = responseText;
}
data.title = head.querySelector('title');
data.title = data.title && data.title.innerText.trim();
if (options.transition) data = extendWithDom(data, '.content', body);
else data.contents = body;
return data;
};
// Attach PUSH event handlers
// ==========================
window.addEventListener('touchstart', function () { isScrolling = false; });
window.addEventListener('touchmove', function () { isScrolling = true; })
window.addEventListener('touchend', touchend);
window.addEventListener('click', function (e) { if (getTarget(e)) e.preventDefault(); });
window.addEventListener('popstate', popstate);
window.PUSH = PUSH;
}();
|
vladikoff/ratchet
|
js/push.js
|
JavaScript
|
mit
| 12,122 |
/*****************************************************
* Copyright (c) 2014 Colby Brown *
* This program is released under the MIT license. *
* For more information about the MIT license, *
* visit http://opensource.org/licenses/MIT *
*****************************************************/
var app = angular.module('volunteer', [
'ajoslin.promise-tracker',
'cn.offCanvas',
'ncy-angular-breadcrumb',
'ngCookies',
'ui.bootstrap',
'ui.router',
'accentbows.controller',
'alerts.controller',
'bears.controller',
'configure.controller',
'confirm.controller',
'home.volunteer.controller',
'letters.controller',
'mums.volunteer.controller',
'mumtypes.controller',
'accessoriesAdd.controller',
'accessoriesAll.controller',
'accessoriesEdit.controller',
'accentbows.service',
'alerts.service',
'bears.service',
'confirm.service',
'letters.service',
'mum.service',
'mumtypes.service',
'pay.service',
'accessories.service',
'volunteer.service']);
app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'public/views/volunteer/home/index.html',
controller: 'homeController'
})
.state('home.logout', {
url: '/logout',
onEnter: function($cookieStore, $rootScope, $state) {
$cookieStore.remove('volunteerToken');
$rootScope.updateHeader();
$state.go('home');
}
})
.state('configure', {
url: '/configure',
templateUrl: 'public/views/volunteer/configure/index.html',
controller: 'configureController'
})
.state('configure.accentbows', {
url: '/accentbows',
templateUrl: 'public/views/volunteer/accentbows/index.html',
controller: 'accentbowsController'
})
.state('configure.bears', {
url: '/bears',
templateUrl: 'public/views/volunteer/bears/index.html',
controller: 'bearsController'
})
.state('configure.letters', {
url: '/letters',
templateUrl: 'public/views/volunteer/letters/index.html',
controller: 'lettersController'
})
.state('configure.volunteers', {
url: '/volunteers',
templateUrl: 'public/views/volunteer/configure/volunteers.html',
controller: 'configureVolunteerController'
})
.state('configure.yearly', {
url: '/yearly',
templateUrl: 'public/views/volunteer/configure/yearly.html',
controller: 'configureYearlyController'
})
.state('mums', {
url: '/mums',
templateUrl: 'public/views/volunteer/mums/index.html',
controller: 'mumsController',
abstract: true
})
.state('mums.all', {
url: '',
templateUrl: 'public/views/volunteer/mums/all.html',
controller: 'mumsAllController'
})
.state('mums.view', {
url: '/view/:mumId',
templateUrl: 'public/views/volunteer/mums/view.html',
controller: 'mumsViewController'
})
.state('configure.mumtypes', {
url: '/mumtypes',
templateUrl: 'public/views/volunteer/mumtypes/index.html',
controller: 'mumtypesController',
abstract: true
})
.state('configure.mumtypes.grade', {
url: '',
templateUrl: 'public/views/volunteer/mumtypes/grade.html',
controller: 'mumtypesItemsController',
resolve: {
itemDetails: function(MumtypesService) {
return {
formController: 'mumtypesEditGradeController',
service: MumtypesService.grades,
fetch: []
};
}
}
})
.state('configure.mumtypes.product', {
url: '/:gradeId',
templateUrl: 'public/views/volunteer/mumtypes/product.html',
controller: 'mumtypesItemsController',
resolve: {
itemDetails: function($stateParams, MumtypesService) {
return {
formController: 'mumtypesEditProductController',
service: MumtypesService.products,
fetch: [
function($scope) {
return MumtypesService.grades.fetch($stateParams.gradeId)
.success(function(data) {
$scope.grade = data;
});
}
]
};
}
}
})
.state('configure.mumtypes.size', {
url: '/:gradeId/:productId',
templateUrl: 'public/views/volunteer/mumtypes/size.html',
controller: 'mumtypesItemsController',
resolve: {
itemDetails: function($stateParams, MumtypesService) {
return {
formController: 'mumtypesEditSizeController',
service: MumtypesService.sizes,
fetch: [
function($scope) {
return MumtypesService.grades.fetch($stateParams.gradeId)
.success(function(data) {
$scope.grade = data;
});
},
function($scope) {
return MumtypesService.products.fetch($stateParams.productId)
.success(function(data) {
$scope.product = data;
});
}
]
};
}
}
})
.state('configure.mumtypes.backing', {
url: '/:gradeId/:productId/:sizeId',
templateUrl: 'public/views/volunteer/mumtypes/backing.html',
controller: 'mumtypesItemsController',
resolve: {
itemDetails: function($stateParams, MumtypesService) {
return {
formController: 'mumtypesEditBackingController',
service: MumtypesService.backings,
fetch: [
function($scope) {
return MumtypesService.grades.fetch($stateParams.gradeId)
.success(function(data) {
$scope.grade = data;
});
},
function($scope) {
return MumtypesService.products.fetch($stateParams.productId)
.success(function(data) {
$scope.product = data;
});
},
function($scope) {
return MumtypesService.sizes.fetch($stateParams.sizeId)
.success(function(data) {
$scope.size = data;
});
}
]
}
}
}
})
.state('configure.accessories', {
url: '/accessories',
template: '<ui-view />',
abstract: true
})
.state('configure.accessories.all', {
url: '',
templateUrl: 'public/views/volunteer/accessories/all.html',
controller: 'accessoriesAllController'
})
.state('configure.accessories.add', {
url: '/add',
templateUrl: 'public/views/volunteer/accessories/edit.html',
controller: 'accessoriesAddController'
})
.state('configure.accessories.edit', {
url: '/edit/:accessoryId',
templateUrl: 'public/views/volunteer/accessories/edit.html',
controller: 'accessoriesEditController'
});
$httpProvider.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
$httpProvider.defaults.headers.put = {'Content-Type': 'application/x-www-form-urlencoded'};
//PHP does not play nice with this feature. It's no big deal.
//$locationProvider.html5Mode(true);
});
app.run(['$cookieStore', '$injector', function($cookieStore, $injector) {
$injector.get("$http").defaults.transformRequest.unshift(function(data, headersGetter) {
var token = $cookieStore.get('volunteerToken');
if (token) {
headersGetter()['Authentication'] = token.jwt;
}
if (data === undefined) {
return data;
}
// If this is not an object, defer to native stringification.
if ( ! angular.isObject( data ) ) {
return( ( data == null ) ? "" : data.toString() );
}
var buffer = [];
// Serialize each key in the object.
for ( var name in data ) {
if ( ! data.hasOwnProperty( name ) ) {
continue;
}
var value = data[ name ];
buffer.push(
encodeURIComponent( name ) + "=" + encodeURIComponent( ( value == null ) ? "" : value )
);
}
// Serialize the buffer and clean it up for transportation.
var source = buffer.join( "&" ).replace( /%20/g, "+" );
return( source );
});
}]);
app.controller('headerController', function($rootScope, $cookieStore) {
$rootScope.updateHeader = function() {
$rootScope.volunteer = $cookieStore.get('volunteerToken');
};
$rootScope.updateHeader();
});
//This filter is used to convert MySQL datetimes into AngularJS a readable ISO format.
app.filter('dateToISO', function() {
return function(badTime) {
if (!badTime) return "";
if (badTime.date) {
return badTime.date.replace(/(.+) (.+)/, "$1T$2Z");
} else {
return badTime.replace(/(.+) (.+)/, "$1T$2Z");
}
};
});
|
brobo/mumshoppe-dep
|
public/js/volunteer.app.js
|
JavaScript
|
mit
| 8,235 |
import { exec, getById } from "../database/database";
import Gender from "../entities/gender";
export default class GenderController {
constructor() {}
static getById(id, as_object = true) {
let gender = null;
let results = getById(id,
`
SELECT
t1.id,
t1.identifier as name
FROM genders as t1
`);
if(results) {
gender = (as_object) ? new Gender(results) : results;
}
console.log(results);
return gender;
}
}
|
milk-shake/electron-pokemon
|
app/js/controllers/genderController.js
|
JavaScript
|
mit
| 485 |
'use strict';
var format = require('util').format
, scripts = require('./scripts')
, loadScriptSource = require('./load-script-source')
// Ports: https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp
function ignore(cb) { cb() }
function InspectorDebuggerAgent() {
if (!(this instanceof InspectorDebuggerAgent)) return new InspectorDebuggerAgent();
this._enabled = false;
this._breakpointsCookie = {}
}
module.exports = InspectorDebuggerAgent;
var proto = InspectorDebuggerAgent.prototype;
proto.enable = function enable(cb) {
this._enabled = true;
cb()
}
proto.disable = function disable(cb) {
this._enabled = false;
cb()
}
// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp&l=606
proto._resolveBreakpoint = function _resolveBreakpoint(breakpointId, script, breakpoint, cb) {
var result = { breakpointId: breakpointId, locations: [ ] };
// if a breakpoint registers on startup, the script's source may not have been loaded yet
// in that case we load it, the script's source is set automatically during that step
// should not be needed once other debugger methods are implemented
if (script.source) onensuredSource();
else loadScriptSource(script.url, onensuredSource)
function onensuredSource(err) {
if (err) return cb(err);
if (breakpoint.lineNumber < script.startLine || script.endLine < breakpoint.lineNumber) return cb(null, result);
// TODO: scriptDebugServer().setBreakpoint(scriptId, breakpoint, &actualLineNumber, &actualColumnNumber, false);
// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/bindings/core/v8/ScriptDebugServer.cpp&l=89
var debugServerBreakpointId = 'TBD'
if (!debugServerBreakpointId) return cb(null, result);
// will be returned from call to script debug server
var actualLineNumber = breakpoint.lineNumber
, actualColumnNumber = breakpoint.columnNumber
result.locations.push({
scriptId : script.id
, lineNumber : actualLineNumber
, columnNumber : actualColumnNumber
})
cb(null, result);
}
}
// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp&l=333
proto.setBreakpointByUrl = function setBreakpointByUrl(opts, cb) {
if (opts.urlRegex) return cb(new Error('Not supporting setBreakpointByUrl with urlRegex'));
var isAntibreakpoint = !!opts.isAntibreakpoint
, url = opts.url
, condition = opts.condition || ''
, lineNumber = opts.lineNumber
, columnNumber
if (typeof opts.columnNumber === Number) {
columnNumber = opts.columnNumber;
if (columnNumber < 0) return cb(new Error('Incorrect column number.'));
} else {
columnNumber = isAntibreakpoint ? -1 : 0;
}
var breakpointId = format('%s:%d:%d', url, lineNumber, columnNumber);
if (this._breakpointsCookie[breakpointId]) return cb(new Error('Breakpoint at specified location already exists.'));
this._breakpointsCookie[breakpointId] = {
url : url
, lineNumber : lineNumber
, columnNumber : columnNumber
, condition : condition
, isAntibreakpoint : isAntibreakpoint
}
if (isAntibreakpoint) return cb(null, { breakpointId: breakpointId });
var match = scripts.byUrl[url];
if (!match) return cb(null, { breakpointId: breakpointId, locations: [] })
var breakpoint = { lineNumber: lineNumber, columnNumber: columnNumber, condition: condition }
this._resolveBreakpoint(breakpointId, match, breakpoint, cb)
}
proto._removeBreakpoint = function _removeBreakpoint(breakpointId, cb) {
// todo
cb()
}
// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp&l=416
proto.removeBreakpoint = function removeBreakpoint(breakpointId, cb) {
var breakpoint = this._breakpointsCookie[breakpointId];
if (!breakpoint) return;
this._breakpointsCookie[breakpointId] = undefined;
if (!breakpoint.isAntibreakpoint) this._removeBreakpoint(breakpointId, cb);
else cb()
}
proto.getScriptSource = function getScriptSource(id, cb) {
var script = scripts.byId[id];
if (!script) return cb(new Error('Script with id ' + id + 'was not found'))
cb(null, { scriptSource: script.source })
}
proto.setBreakpointsActive = ignore
proto.setSkipAllPauses = ignore
proto.setBreakpoint = ignore
proto.continueToLocation = ignore
proto.stepOver = ignore
proto.stepInto = ignore
proto.stepOut = ignore
proto.pause = ignore
proto.resume = ignore
proto.searchInContent = ignore
proto.canSetScriptSource = ignore
proto.setScriptSource = ignore
proto.restartFrame = ignore
proto.getFunctionDetails = ignore
proto.getCollectionEntries = ignore
proto.setPauseOnExceptions = ignore
proto.evaluateOnCallFrame = ignore
proto.compileScript = ignore
proto.runScript = ignore
proto.setOverlayMessage = ignore
proto.setVariableValue = ignore
proto.getStepInPositions = ignore
proto.getBacktrace = ignore
proto.skipStackFrames = ignore
proto.setAsyncCallStackDepth = ignore
proto.enablePromiseTracker = ignore
proto.disablePromiseTracker = ignore
proto.getPromises = ignore
proto.getPromiseById = ignore
|
thlorenz/debugium
|
lib/inspector/InspectorDebuggerAgent.js
|
JavaScript
|
mit
| 5,597 |
/* eslint no-console: 0 */
'use strict';
const fs = require('fs');
const mkdirp = require('mkdirp');
const rollup = require('rollup');
const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const uglify = require('rollup-plugin-uglify');
const src = 'src';
const dest = 'dist/rollup-aot';
Promise.all([
// build main/app
rollup.rollup({
entry: `${src}/main-aot.js`,
context: 'this',
plugins: [
nodeResolve({ jsnext: true, module: true }),
commonjs(),
uglify({
output: {
comments: /@preserve|@license|@cc_on/i,
},
mangle: {
keep_fnames: true,
},
compress: {
warnings: false,
},
}),
],
}).then(app =>
app.write({
format: 'iife',
dest: `${dest}/app.js`,
sourceMap: false,
})
),
// build polyfills
rollup.rollup({
entry: `${src}/polyfills-aot.js`,
context: 'this',
plugins: [
nodeResolve({ jsnext: true, module: true }),
commonjs(),
uglify(),
],
}).then(app =>
app.write({
format: 'iife',
dest: `${dest}/polyfills.js`,
sourceMap: false,
})
),
// create index.html
new Promise((resolve, reject) => {
fs.readFile(`${src}/index.html`, 'utf-8', (readErr, indexHtml) => {
if (readErr) return reject(readErr);
const newIndexHtml = indexHtml
.replace('</head>', '<script src="polyfills.js"></script></head>')
.replace('</body>', '<script src="app.js"></script></body>');
mkdirp(dest, mkdirpErr => {
if (mkdirpErr) return reject(mkdirpErr);
return true;
});
return fs.writeFile(
`${dest}/index.html`,
newIndexHtml,
'utf-8',
writeErr => {
if (writeErr) return reject(writeErr);
console.log('Created index.html');
return resolve();
}
);
});
}),
]).then(() => {
console.log('Rollup complete');
}).catch(err => {
console.error('Rollup failed with ', err);
});
|
marcandrews/angular2-rollup-investigation
|
rollup-aot.config.js
|
JavaScript
|
mit
| 2,085 |
function checkHeadersSent(res, cb) {
return (err, results) => {
if (res.headersSent) {
if (err) {
return cb(err)
}
return null
}
cb(err, results)
}
}
exports.finish = function finish(req, res, next) {
const check = checkHeadersSent.bind(null, res)
if (req.method === 'GET') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
res.json(results)
})
} else if (req.method === 'POST') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
/* eslint-disable max-len */
// http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api?hn#useful-post-responses
if (results) {
res.json(results, 200)
} else {
res.json(204, {})
}
})
} else if (req.method === 'PUT') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
if (results) {
res.json(results, 200)
} else {
res.json(204, {})
}
})
} else if (req.method === 'PATCH') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
if (results) {
res.json(results)
} else {
res.json(204, {})
}
})
} else if (req.method === 'DELETE') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
if (results) {
res.json(results)
} else {
res.json(204, {})
}
})
}
}
|
cannoneyed/tmm-glare
|
server/webUtil/routing.js
|
JavaScript
|
mit
| 1,653 |
var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure();
var testCase = require('../deps/nodeunit').testCase,
debug = require('util').debug,
inspect = require('util').inspect,
nodeunit = require('../deps/nodeunit'),
gleak = require('../tools/gleak'),
Db = mongodb.Db,
Cursor = mongodb.Cursor,
Script = require('vm'),
Collection = mongodb.Collection,
Server = mongodb.Server,
Step = require("../deps/step/lib/step"),
ServerManager = require('./tools/server_manager').ServerManager;
var MONGODB = 'integration_tests';
var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)});
/**
* Module for parsing an ISO 8601 formatted string into a Date object.
*/
var ISODate = function (string) {
var match;
if (typeof string.getTime === "function")
return string;
else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) {
var date = new Date();
date.setUTCFullYear(Number(match[1]));
date.setUTCMonth(Number(match[3]) - 1 || 0);
date.setUTCDate(Number(match[5]) || 0);
date.setUTCHours(Number(match[7]) || 0);
date.setUTCMinutes(Number(match[8]) || 0);
date.setUTCSeconds(Number(match[10]) || 0);
date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0);
if (match[13] && match[13] !== "Z") {
var h = Number(match[16]) || 0,
m = Number(match[17]) || 0;
h *= 3600000;
m *= 60000;
var offset = h + m;
if (match[15] == "+")
offset = -offset;
new Date(date.valueOf() + offset);
}
return date;
} else
throw new Error("Invalid ISO 8601 date given.", __filename);
};
// Define the tests, we want them to run as a nested test so we only clean up the
// db connection once
var tests = testCase({
setUp: function(callback) {
client.open(function(err, db_p) {
if(numberOfTestsRun == Object.keys(tests).length) {
// If first test drop the db
client.dropDatabase(function(err, done) {
callback();
});
} else {
return callback();
}
});
},
tearDown: function(callback) {
numberOfTestsRun = numberOfTestsRun - 1;
// Drop the database and close it
if(numberOfTestsRun <= 0) {
// client.dropDatabase(function(err, done) {
// Close the client
client.close();
callback();
// });
} else {
client.close();
callback();
}
},
shouldForceMongoDbServerToAssignId : function(test) {
/// Set up server with custom pk factory
var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null), 'forceServerObjectId':true});
db.bson_deserializer = client.bson_deserializer;
db.bson_serializer = client.bson_serializer;
db.open(function(err, client) {
client.createCollection('test_insert2', function(err, r) {
client.collection('test_insert2', function(err, collection) {
Step(
function inserts() {
var group = this.group();
for(var i = 1; i < 1000; i++) {
collection.insert({c:i}, {safe:true}, group());
}
},
function done(err, result) {
collection.insert({a:2}, {safe:true}, function(err, r) {
collection.insert({a:3}, {safe:true}, function(err, r) {
collection.count(function(err, count) {
test.equal(1001, count);
// Locate all the entries using find
collection.find(function(err, cursor) {
cursor.toArray(function(err, results) {
test.equal(1001, results.length);
test.ok(results[0] != null);
client.close();
// Let's close the db
test.done();
});
});
});
});
});
}
)
});
});
});
},
shouldCorrectlyPerformSingleInsert : function(test) {
client.createCollection('shouldCorrectlyPerformSingleInsert', function(err, collection) {
collection.insert({a:1}, {safe:true}, function(err, result) {
collection.findOne(function(err, item) {
test.equal(1, item.a);
test.done();
})
})
})
},
shouldCorrectlyPerformBasicInsert : function(test) {
client.createCollection('test_insert', function(err, r) {
client.collection('test_insert', function(err, collection) {
Step(
function inserts() {
var group = this.group();
for(var i = 1; i < 1000; i++) {
collection.insert({c:i}, {safe:true}, group());
}
},
function done(err, result) {
collection.insert({a:2}, {safe:true}, function(err, r) {
collection.insert({a:3}, {safe:true}, function(err, r) {
collection.count(function(err, count) {
test.equal(1001, count);
// Locate all the entries using find
collection.find(function(err, cursor) {
cursor.toArray(function(err, results) {
test.equal(1001, results.length);
test.ok(results[0] != null);
// Let's close the db
test.done();
});
});
});
});
});
}
)
});
});
},
// Test multiple document insert
shouldCorrectlyHandleMultipleDocumentInsert : function(test) {
client.createCollection('test_multiple_insert', function(err, r) {
var collection = client.collection('test_multiple_insert', function(err, collection) {
var docs = [{a:1}, {a:2}];
collection.insert(docs, {safe:true}, function(err, ids) {
ids.forEach(function(doc) {
test.ok(((doc['_id']) instanceof client.bson_serializer.ObjectID || Object.prototype.toString.call(doc['_id']) === '[object ObjectID]'));
});
// Let's ensure we have both documents
collection.find(function(err, cursor) {
cursor.toArray(function(err, docs) {
test.equal(2, docs.length);
var results = [];
// Check that we have all the results we want
docs.forEach(function(doc) {
if(doc.a == 1 || doc.a == 2) results.push(1);
});
test.equal(2, results.length);
// Let's close the db
test.done();
});
});
});
});
});
},
shouldCorrectlyExecuteSaveInsertUpdate: function(test) {
client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) {
collection.save({ email : 'save' }, {safe:true}, function() {
collection.insert({ email : 'insert' }, {safe:true}, function() {
collection.update(
{ email : 'update' },
{ email : 'update' },
{ upsert: true, safe:true},
function() {
collection.find(function(e, c) {
c.toArray(function(e, a) {
test.equal(3, a.length)
test.done();
});
});
}
);
});
});
});
},
shouldCorrectlyInsertAndRetrieveLargeIntegratedArrayDocument : function(test) {
client.createCollection('test_should_deserialize_large_integrated_array', function(err, collection) {
var doc = {'a':0,
'b':['tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9', 'tmp10', 'tmp11', 'tmp12', 'tmp13', 'tmp14', 'tmp15', 'tmp16']
};
// Insert the collection
collection.insert(doc, {safe:true}, function(err, r) {
// Fetch and check the collection
collection.findOne({'a': 0}, function(err, result) {
test.deepEqual(doc.a, result.a);
test.deepEqual(doc.b, result.b);
test.done();
});
});
});
},
shouldCorrectlyInsertAndRetrieveDocumentWithAllTypes : function(test) {
client.createCollection('test_all_serialization_types', function(err, collection) {
var date = new Date();
var oid = new client.bson_serializer.ObjectID();
var string = 'binstring'
var bin = new client.bson_serializer.Binary()
for(var index = 0; index < string.length; index++) {
bin.put(string.charAt(index))
}
var motherOfAllDocuments = {
'string': 'hello',
'array': [1,2,3],
'hash': {'a':1, 'b':2},
'date': date,
'oid': oid,
'binary': bin,
'int': 42,
'float': 33.3333,
'regexp': /regexp/,
'boolean': true,
'long': date.getTime(),
'where': new client.bson_serializer.Code('this.a > i', {i:1}),
'dbref': new client.bson_serializer.DBRef('namespace', oid, 'integration_tests_')
}
collection.insert(motherOfAllDocuments, {safe:true}, function(err, docs) {
collection.findOne(function(err, doc) {
// Assert correct deserialization of the values
test.equal(motherOfAllDocuments.string, doc.string);
test.deepEqual(motherOfAllDocuments.array, doc.array);
test.equal(motherOfAllDocuments.hash.a, doc.hash.a);
test.equal(motherOfAllDocuments.hash.b, doc.hash.b);
test.equal(date.getTime(), doc.long);
test.equal(date.toString(), doc.date.toString());
test.equal(date.getTime(), doc.date.getTime());
test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString());
test.equal(motherOfAllDocuments.binary.value(), doc.binary.value());
test.equal(motherOfAllDocuments.int, doc.int);
test.equal(motherOfAllDocuments.long, doc.long);
test.equal(motherOfAllDocuments.float, doc.float);
test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString());
test.equal(motherOfAllDocuments.boolean, doc.boolean);
test.equal(motherOfAllDocuments.where.code, doc.where.code);
test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i);
test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace);
test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString());
test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db);
test.done();
})
});
});
},
shouldCorrectlyInsertAndUpdateDocumentWithNewScriptContext: function(test) {
var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)});
db.bson_deserializer = client.bson_deserializer;
db.bson_serializer = client.bson_serializer;
db.pkFactory = client.pkFactory;
db.open(function(err, db) {
//convience curried handler for functions of type 'a -> (err, result)
function getResult(callback){
return function(error, result) {
test.ok(error == null);
return callback(result);
}
};
db.collection('users', getResult(function(user_collection){
user_collection.remove({}, {safe:true}, function(err, result) {
//first, create a user object
var newUser = { name : 'Test Account', settings : {} };
user_collection.insert([newUser], {safe:true}, getResult(function(users){
var user = users[0];
var scriptCode = "settings.block = []; settings.block.push('test');";
var context = { settings : { thisOneWorks : "somestring" } };
Script.runInNewContext(scriptCode, context, "testScript");
//now create update command and issue it
var updateCommand = { $set : context };
user_collection.update({_id : user._id}, updateCommand, {safe:true},
getResult(function(updateCommand) {
// Fetch the object and check that the changes are persisted
user_collection.findOne({_id : user._id}, function(err, doc) {
test.ok(err == null);
test.equal("Test Account", doc.name);
test.equal("somestring", doc.settings.thisOneWorks);
test.equal("test", doc.settings.block[0]);
// Let's close the db
db.close();
test.done();
});
})
);
}));
});
}));
});
},
shouldCorrectlySerializeDocumentWithAllTypesInNewContext : function(test) {
client.createCollection('test_all_serialization_types_new_context', function(err, collection) {
var date = new Date();
var scriptCode =
"var string = 'binstring'\n" +
"var bin = new mongo.Binary()\n" +
"for(var index = 0; index < string.length; index++) {\n" +
" bin.put(string.charAt(index))\n" +
"}\n" +
"motherOfAllDocuments['string'] = 'hello';" +
"motherOfAllDocuments['array'] = [1,2,3];" +
"motherOfAllDocuments['hash'] = {'a':1, 'b':2};" +
"motherOfAllDocuments['date'] = date;" +
"motherOfAllDocuments['oid'] = new mongo.ObjectID();" +
"motherOfAllDocuments['binary'] = bin;" +
"motherOfAllDocuments['int'] = 42;" +
"motherOfAllDocuments['float'] = 33.3333;" +
"motherOfAllDocuments['regexp'] = /regexp/;" +
"motherOfAllDocuments['boolean'] = true;" +
"motherOfAllDocuments['long'] = motherOfAllDocuments['date'].getTime();" +
"motherOfAllDocuments['where'] = new mongo.Code('this.a > i', {i:1});" +
"motherOfAllDocuments['dbref'] = new mongo.DBRef('namespace', motherOfAllDocuments['oid'], 'integration_tests_');";
var context = { motherOfAllDocuments : {}, mongo:client.bson_serializer, date:date};
// Execute function in context
Script.runInNewContext(scriptCode, context, "testScript");
// sys.puts(sys.inspect(context.motherOfAllDocuments))
var motherOfAllDocuments = context.motherOfAllDocuments;
collection.insert(context.motherOfAllDocuments, {safe:true}, function(err, docs) {
collection.findOne(function(err, doc) {
// Assert correct deserialization of the values
test.equal(motherOfAllDocuments.string, doc.string);
test.deepEqual(motherOfAllDocuments.array, doc.array);
test.equal(motherOfAllDocuments.hash.a, doc.hash.a);
test.equal(motherOfAllDocuments.hash.b, doc.hash.b);
test.equal(date.getTime(), doc.long);
test.equal(date.toString(), doc.date.toString());
test.equal(date.getTime(), doc.date.getTime());
test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString());
test.equal(motherOfAllDocuments.binary.value(), doc.binary.value());
test.equal(motherOfAllDocuments.int, doc.int);
test.equal(motherOfAllDocuments.long, doc.long);
test.equal(motherOfAllDocuments.float, doc.float);
test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString());
test.equal(motherOfAllDocuments.boolean, doc.boolean);
test.equal(motherOfAllDocuments.where.code, doc.where.code);
test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i);
test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace);
test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString());
test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db);
test.done();
})
});
});
},
shouldCorrectlyDoToJsonForLongValue : function(test) {
client.createCollection('test_to_json_for_long', function(err, collection) {
test.ok(collection instanceof Collection);
collection.insertAll([{value: client.bson_serializer.Long.fromNumber(32222432)}], {safe:true}, function(err, ids) {
collection.findOne({}, function(err, item) {
test.equal(32222432, item.value);
test.done();
});
});
});
},
shouldCorrectlyInsertAndUpdateWithNoCallback : function(test) {
var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)});
db.bson_deserializer = client.bson_deserializer;
db.bson_serializer = client.bson_serializer;
db.pkFactory = client.pkFactory;
db.open(function(err, client) {
client.createCollection('test_insert_and_update_no_callback', function(err, collection) {
// Insert the update
collection.insert({i:1}, {safe:true})
// Update the record
collection.update({i:1}, {"$set":{i:2}}, {safe:true})
// Make sure we leave enough time for mongodb to record the data
setTimeout(function() {
// Locate document
collection.findOne({}, function(err, item) {
test.equal(2, item.i)
client.close();
test.done();
});
}, 100)
})
});
},
shouldInsertAndQueryTimestamp : function(test) {
client.createCollection('test_insert_and_query_timestamp', function(err, collection) {
// Insert the update
collection.insert({i:client.bson_serializer.Timestamp.fromNumber(100), j:client.bson_serializer.Long.fromNumber(200)}, {safe:true}, function(err, r) {
// Locate document
collection.findOne({}, function(err, item) {
test.ok(item.i instanceof client.bson_serializer.Timestamp);
test.equal(100, item.i);
test.ok(typeof item.j == "number");
test.equal(200, item.j);
test.done();
});
})
})
},
shouldCorrectlyInsertAndQueryUndefined : function(test) {
client.createCollection('test_insert_and_query_undefined', function(err, collection) {
// Insert the update
collection.insert({i:undefined}, {safe:true}, function(err, r) {
// Locate document
collection.findOne({}, function(err, item) {
test.equal(null, item.i)
test.done();
});
})
})
},
shouldCorrectlySerializeDBRefToJSON : function(test) {
var dbref = new client.bson_serializer.DBRef("foo",
client.bson_serializer.ObjectID.createFromHexString("fc24a04d4560531f00000000"),
null);
JSON.stringify(dbref);
test.done();
},
shouldCorrectlyPerformSafeInsert : function(test) {
var fixtures = [{
name: "empty", array: [], bool: false, dict: {}, float: 0.0, string: ""
}, {
name: "not empty", array: [1], bool: true, dict: {x: "y"}, float: 1.0, string: "something"
}, {
name: "simple nested", array: [1, [2, [3]]], bool: true, dict: {x: "y", array: [1,2,3,4], dict: {x: "y", array: [1,2,3,4]}}, float: 1.5, string: "something simply nested"
}];
client.createCollection('test_safe_insert', function(err, collection) {
Step(
function inserts() {
var group = this.group();
for(var i = 0; i < fixtures.length; i++) {
collection.insert(fixtures[i], {safe:true}, group());
}
},
function done() {
collection.count(function(err, count) {
test.equal(3, count);
collection.find().toArray(function(err, docs) {
test.equal(3, docs.length)
});
});
collection.find({}, {}, function(err, cursor) {
var counter = 0;
cursor.each(function(err, doc) {
if(doc == null) {
test.equal(3, counter);
test.done();
} else {
counter = counter + 1;
}
});
});
}
)
})
},
shouldThrowErrorIfSerializingFunction : function(test) {
client.createCollection('test_should_throw_error_if_serializing_function', function(err, collection) {
var func = function() { return 1};
// Insert the update
collection.insert({i:1, z:func }, {safe:true}, function(err, result) {
collection.findOne({_id:result[0]._id}, function(err, object) {
test.equal(func.toString(), object.z.code);
test.equal(1, object.i);
test.done();
})
})
})
},
shouldCorrectlyInsertDocumentWithUUID : function(test) {
client.collection("insert_doc_with_uuid", function(err, collection) {
collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) {
test.equal(null, err);
collection.find({_id : "12345678123456781234567812345678"}).toArray(function(err, items) {
test.equal(null, err);
test.equal(items[0]._id, "12345678123456781234567812345678")
test.equal(items[0].field, '1')
// Generate a binary id
var binaryUUID = new client.bson_serializer.Binary('00000078123456781234567812345678', client.bson_serializer.BSON.BSON_BINARY_SUBTYPE_UUID);
collection.insert({_id : binaryUUID, field: '2'}, {safe:true}, function(err, result) {
collection.find({_id : binaryUUID}).toArray(function(err, items) {
test.equal(null, err);
test.equal(items[0].field, '2')
test.done();
});
});
})
});
});
},
shouldCorrectlyCallCallbackWithDbDriverInStrictMode : function(test) {
var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)});
db.bson_deserializer = client.bson_deserializer;
db.bson_serializer = client.bson_serializer;
db.pkFactory = client.pkFactory;
db.open(function(err, client) {
client.createCollection('test_insert_and_update_no_callback_strict', function(err, collection) {
collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) {
test.equal(null, err);
collection.update({ '_id': "12345678123456781234567812345678" }, { '$set': { 'field': 0 }}, function(err, numberOfUpdates) {
test.equal(null, err);
test.equal(1, numberOfUpdates);
db.close();
test.done();
});
});
});
});
},
shouldCorrectlyInsertDBRefWithDbNotDefined : function(test) {
client.createCollection('shouldCorrectlyInsertDBRefWithDbNotDefined', function(err, collection) {
var doc = {_id: new client.bson_serializer.ObjectID()};
var doc2 = {_id: new client.bson_serializer.ObjectID()};
var doc3 = {_id: new client.bson_serializer.ObjectID()};
collection.insert(doc, {safe:true}, function(err, result) {
// Create object with dbref
doc2.ref = new client.bson_serializer.DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id);
doc3.ref = new client.bson_serializer.DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id, MONGODB);
collection.insert([doc2, doc3], {safe:true}, function(err, result) {
// Get all items
collection.find().toArray(function(err, items) {
test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[1].ref.namespace);
test.equal(doc._id.toString(), items[1].ref.oid.toString());
test.equal(null, items[1].ref.db);
test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[2].ref.namespace);
test.equal(doc._id.toString(), items[2].ref.oid.toString());
test.equal(MONGODB, items[2].ref.db);
test.done();
})
});
});
});
},
shouldCorrectlyInsertUpdateRemoveWithNoOptions : function(test) {
var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)});
db.bson_deserializer = client.bson_deserializer;
db.bson_serializer = client.bson_serializer;
db.pkFactory = client.pkFactory;
db.open(function(err, db) {
db.collection('shouldCorrectlyInsertUpdateRemoveWithNoOptions', function(err, collection) {
collection.insert({a:1});//, function(err, result) {
collection.update({a:1}, {a:2});//, function(err, result) {
collection.remove({a:2});//, function(err, result) {
collection.count(function(err, count) {
test.equal(0, count);
db.close();
test.done();
})
});
});
},
shouldCorrectlyExecuteMultipleFetches : function(test) {
var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)});
db.bson_deserializer = client.bson_deserializer;
db.bson_serializer = client.bson_serializer;
db.pkFactory = client.pkFactory;
// Search parameter
var to = 'ralph'
// Execute query
db.open(function(err, db) {
db.collection('shouldCorrectlyExecuteMultipleFetches', function(err, collection) {
collection.insert({addresses:{localPart:'ralph'}}, {safe:true}, function(err, result) {
// Let's find our user
collection.findOne({"addresses.localPart" : to}, function( err, doc ) {
test.equal(null, err);
test.equal(to, doc.addresses.localPart);
db.close();
test.done();
});
});
});
});
},
shouldCorrectlyFailWhenNoObjectToUpdate: function(test) {
client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) {
collection.update({_id : new client.bson_serializer.ObjectID()}, { email : 'update' }, {safe:true},
function(err, result) {
test.equal(0, result);
test.done();
}
);
});
},
'Should correctly insert object and retrieve it when containing array and IsoDate' : function(test) {
var doc = {
"_id" : new client.bson_serializer.ObjectID("4e886e687ff7ef5e00000162"),
"str" : "foreign",
"type" : 2,
"timestamp" : ISODate("2011-10-02T14:00:08.383Z"),
"links" : [
"http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/"
]
}
client.createCollection('Should_correctly_insert_object_and_retrieve_it_when_containing_array_and_IsoDate', function(err, collection) {
collection.insert(doc, {safe:true}, function(err, result) {
test.ok(err == null);
collection.findOne(function(err, item) {
test.ok(err == null);
test.deepEqual(doc, item);
test.done();
});
});
});
},
'Should correctly insert object with timestamps' : function(test) {
var doc = {
"_id" : new client.bson_serializer.ObjectID("4e886e687ff7ef5e00000162"),
"str" : "foreign",
"type" : 2,
"timestamp" : new client.bson_serializer.Timestamp(10000),
"links" : [
"http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/"
],
"timestamp2" : new client.bson_serializer.Timestamp(33333),
}
client.createCollection('Should_correctly_insert_object_with_timestamps', function(err, collection) {
collection.insert(doc, {safe:true}, function(err, result) {
test.ok(err == null);
collection.findOne(function(err, item) {
test.ok(err == null);
test.deepEqual(doc, item);
test.done();
});
});
});
},
noGlobalsLeaked : function(test) {
var leaks = gleak.detectNew();
test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
test.done();
}
})
// Stupid freaking workaround due to there being no way to run setup once for each suite
var numberOfTestsRun = Object.keys(tests).length;
// Assign out tests
module.exports = tests;
|
zencephalon/deftdraftjs
|
node_modules/mongoose/node_modules/mongodb/test/insert_test.js
|
JavaScript
|
mit
| 29,311 |
const createImmutableEqualsSelector = require('./customSelectorCreator');
const compare = require('../util/compare');
const exampleReducers = require('../reducers/exampleReducers');
/**
* Get state function
*/
const getSortingState = exampleReducers.getSortingState;
const getPaginationState = exampleReducers.getPaginationState;
const getDataState = exampleReducers.getDataState;
/**
* Sorting immutable data source
* @param {Map} source immutable data source
* @param {string} sortingKey property of data
* @param {string} orderByCondition 'asc' or 'desc'
* @return {List} immutable testing data source with sorting
*/
const sortingData = (source, sortingKey, orderByCondition) => {
let orderBy = orderByCondition === 'asc' ? 1 : -1;
return source.sortBy(data => data.get(sortingKey), (v, k) => orderBy * compare(v, k));
}
/**
* Paginating data from sortingSelector
* @param {List} sortedData immutable data source with sorting
* @param {number} start
* @param {number} end
* @return {array} sorting data with pagination and converting Immutable.List to array
*/
const pagination = (sortedData, start, end) => sortedData.slice(start, end).toList().toJS()
/**
* Partial selector only to do sorting
*/
const sortingSelector = createImmutableEqualsSelector(
[
getDataState, // get data source
getSortingState
],
(dataState, sortingCondition) => sortingData(dataState, sortingCondition.get('sortingKey'), sortingCondition.get('orderBy'))
)
/**
* Root selector to paginate data from sortingSelector
*/
const paginationSelector = createImmutableEqualsSelector(
[
sortingSelector, // bind selector to be new data source
getPaginationState
],
(sortedData, paginationCondition) => pagination(sortedData, paginationCondition.get('start'), paginationCondition.get('end'))
)
module.exports = paginationSelector;
|
ysaaron/reselect-demo
|
src/selector/exampleSelector.js
|
JavaScript
|
mit
| 1,908 |
var stream = require('readable-stream')
var util = require('util')
var fifo = require('fifo')
var toStreams2 = function(s) {
if (s._readableState) return s
var wrap = new stream.Readable().wrap(s)
if (s.destroy) wrap.destroy = s.destroy.bind(s)
return wrap
}
var Parallel = function(streams, opts) {
if (!(this instanceof Parallel)) return new Parallel(streams, opts)
stream.Readable.call(this, opts)
this.destroyed = false
this._forwarding = false
this._drained = false
this._queue = fifo()
for (var i = 0; i < streams.length; i++) this.add(streams[i])
this._current = this._queue.node
}
util.inherits(Parallel, stream.Readable)
Parallel.obj = function(streams) {
return new Parallel(streams, {objectMode: true, highWaterMark: 16})
}
Parallel.prototype.add = function(s) {
s = toStreams2(s)
var self = this
var node = this._queue.push(s)
var onend = function() {
if (node === self._current) self._current = node.next
self._queue.remove(node)
s.removeListener('readable', onreadable)
s.removeListener('end', onend)
s.removeListener('error', onerror)
s.removeListener('close', onclose)
self._forward()
}
var onreadable = function() {
self._forward()
}
var onclose = function() {
if (!s._readableState.ended) self.destroy()
}
var onerror = function(err) {
self.destroy(err)
}
s.on('end', onend)
s.on('readable', onreadable)
s.on('close', onclose)
s.on('error', onerror)
}
Parallel.prototype._read = function () {
this._drained = true
this._forward()
}
Parallel.prototype._forward = function () {
if (this._forwarding || !this._drained) return
this._forwarding = true
var stream = this._get()
if (!stream) return
var chunk
while ((chunk = stream.read()) !== null) {
this._current = this._current.next
this._drained = this.push(chunk)
stream = this._get()
if (!stream) return
}
this._forwarding = false
}
Parallel.prototype._get = function() {
var stream = this._current && this._queue.get(this._current)
if (!stream) this.push(null)
else return stream
}
Parallel.prototype.destroy = function (err) {
if (this.destroyed) return
this.destroyed = true
var next
while ((next = this._queue.shift())) {
if (next.destroy) next.destroy()
}
if (err) this.emit('error', err)
this.emit('close')
}
module.exports = Parallel
|
mafintosh/parallel-multistream
|
index.js
|
JavaScript
|
mit
| 2,398 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.