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 |
|---|---|---|---|---|---|
import{LineLinkedShadow}from"./LineLinkedShadow";import{Color}from"./Color";export class LineLinked{constructor(){this.blink=!1,this.color=new Color,this.consent=!1,this.distance=100,this.enable=!1,this.opacity=1,this.shadow=new LineLinkedShadow,this.width=1}load(o){void 0!==o&&(void 0!==o.blink&&(this.blink=o.blink),void 0!==o.color&&("string"==typeof o.color?this.color.value=o.color:this.color.load(o.color)),void 0!==o.consent&&(this.consent=o.consent),void 0!==o.distance&&(this.distance=o.distance),void 0!==o.enable&&(this.enable=o.enable),void 0!==o.opacity&&(this.opacity=o.opacity),this.shadow.load(o.shadow),void 0!==o.width&&(this.width=o.width))}}; | cdnjs/cdnjs | ajax/libs/tsparticles/1.12.9/Classes/Options/Particles/LineLinked.min.js | JavaScript | mit | 663 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isPrivate = exports.isChild = exports.isParent = exports.isModule = exports.isView = exports.isElement = exports.isCollection = exports.isAddon = exports.isType = exports.isMeta = exports.TYPES = undefined;
var _startsWith2 = require('lodash/fp/startsWith');
var _startsWith3 = _interopRequireDefault(_startsWith2);
var _has2 = require('lodash/fp/has');
var _has3 = _interopRequireDefault(_has2);
var _eq2 = require('lodash/fp/eq');
var _eq3 = _interopRequireDefault(_eq2);
var _flow2 = require('lodash/fp/flow');
var _flow3 = _interopRequireDefault(_flow2);
var _curry2 = require('lodash/fp/curry');
var _curry3 = _interopRequireDefault(_curry2);
var _get2 = require('lodash/fp/get');
var _get3 = _interopRequireDefault(_get2);
var _includes2 = require('lodash/fp/includes');
var _includes3 = _interopRequireDefault(_includes2);
var _values2 = require('lodash/fp/values');
var _values3 = _interopRequireDefault(_values2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TYPES = exports.TYPES = {
ADDON: 'addon',
COLLECTION: 'collection',
ELEMENT: 'element',
VIEW: 'view',
MODULE: 'module'
};
var TYPE_VALUES = (0, _values3.default)(TYPES);
/**
* Determine if an object qualifies as a META object.
* It must have the required keys and valid values.
* @private
* @param {Object} _meta A proposed component _meta object.
* @returns {Boolean}
*/
var isMeta = exports.isMeta = function isMeta(_meta) {
return (0, _includes3.default)((0, _get3.default)('type', _meta), TYPE_VALUES);
};
/**
* Extract a component's _meta object and optional key.
* Handles literal _meta objects, classes with _meta, objects with _meta
* @private
* @param {function|object} metaArg A class, a component instance, or meta object..
* @returns {object|string|undefined}
*/
var getMeta = function getMeta(metaArg) {
// literal
if (isMeta(metaArg)) return metaArg;
// from prop
else if (isMeta((0, _get3.default)('_meta', metaArg))) return metaArg._meta;
// from class
else if (isMeta((0, _get3.default)('constructor._meta', metaArg))) return metaArg.constructor._meta;
};
var metaHasKeyValue = (0, _curry3.default)(function (key, val, metaArg) {
return (0, _flow3.default)(getMeta, (0, _get3.default)(key), (0, _eq3.default)(val))(metaArg);
});
var isType = exports.isType = metaHasKeyValue('type');
// ----------------------------------------
// Export
// ----------------------------------------
// type
var isAddon = exports.isAddon = isType(TYPES.ADDON);
var isCollection = exports.isCollection = isType(TYPES.COLLECTION);
var isElement = exports.isElement = isType(TYPES.ELEMENT);
var isView = exports.isView = isType(TYPES.VIEW);
var isModule = exports.isModule = isType(TYPES.MODULE);
// parent
var isParent = exports.isParent = (0, _flow3.default)(getMeta, (0, _has3.default)('parent'), (0, _eq3.default)(false));
var isChild = exports.isChild = (0, _flow3.default)(getMeta, (0, _has3.default)('parent'));
// other
var isPrivate = exports.isPrivate = (0, _flow3.default)(getMeta, (0, _get3.default)('name'), (0, _startsWith3.default)('_')); | jessicaappelbaum/cljs-update | node_modules/semantic-ui-react/dist/commonjs/lib/META.js | JavaScript | epl-1.0 | 3,230 |
/*******************************************************************************
* @license
* Copyright (c) 2012 VMware, Inc. All Rights Reserved.
* THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
* ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
* CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
* You can obtain a current copy of the Eclipse Public License from
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* Contributors:
* Kris De Volder - initial API and implementation
******************************************************************************/
/*global require exports console */
var esprima = require("../../client/scripts/lib/esprima/esprima");
function emptyParseTree() { return {}; }
var esprimaOptions = {
tolerant: true
};
//call esprima parser. If it throws an exception ignore it and return an empty parse tree.
function parse(text, errback) {
if (typeof(errback)!=='function') {
errback = function (error) {
//Silently drop parse errors and return something suitable for most
//contexts.
return emptyParseTree();
};
}
try {
return esprima.parse(text, esprimaOptions);
} catch (error) {
return errback(error);
}
}
function dummyparse() {
return {};
}
exports.parse = parse;
//like parse, but when there's an error in parsing, throw an exception
exports.parseAndThrow = function (text) {
return parse(text, function (error) {
throw error;
});
};
//like parse, but when there's an error in parsing, log it to the console.
exports.parseAndLog = function (text) {
return parse(text, function (error) {
console.log(error); //Typically only shows stack 'below' this point.
console.trace('More stack frames'); //Shows stack 'above' this point.
return emptyParseTree();
});
};
| sirspock/scripted_token | server/jsdepend/parser.js | JavaScript | epl-1.0 | 1,801 |
import mock$data from '../core.js';
import $data from 'jaydata/core';
import { EntityContextTests } from './T1.js';
import { T3 } from './T3.js';
// T4_CrossProviderTests();
EntityContextTests({ name: 'oData', oDataServiceHost: "http://localhost:9000/odata", serviceUrl: 'http://localhost:9000/odata', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'oDataV4');
T3({ name: 'oData', oDataServiceHost: "http://localhost:9000/odata", serviceUrl: 'http://localhost:9000/odata', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'oDataV4');
// T3_oDataV3({ name: 'oData', oDataServiceHost: "http://localhost:9000/odata", serviceUrl: 'http://localhost:9000/odata', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'oDataV4');
// if ($data.StorageProviderLoader.isSupported('sqLite')) {
// EntityContextTests({ name: "sqLite", databaseName: 'T1', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, '_Web_SQL');
// T3({ name: "sqLite", databaseName: 'T1', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, '_Web_SQL');
// GeoTests({ name: "sqLite", databaseName: 'GeoTests_T1', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, '_Web_SQL');
// GuidTests({ name: "sqLite", databaseName: 'GuidTests_T1', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, '_Web_SQL');
// TypeTests({ name: 'sqLite', databaseName: 'TypeTests_T2' }, 'sqLite');
// CollectionTests({ name: 'sqLite', databaseName: 'CollectionTests_T2' }, 'sqLite');
// LocalContextTests({ name: 'sqLite', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, 'sqLite');
// }
// GeoTests({ name: "InMemory", databaseName: 'GeoTests_T1', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, '_InMemory');
// GuidTests({ name: "InMemory", databaseName: 'GuidTests_T1', dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables }, '_InMemory'); | Malyngo/jaydata | test/unit-tests/T2.js | JavaScript | gpl-2.0 | 2,046 |
/**
* SyntaxHighlighter
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
//typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
// Contributed by Jean-Lou Dupont
// http://jldupont.blogspot.com/2009/06/erlang-syntax-highlighter.html
// According to: http://erlang.org/doc/reference_manual/introduction.html#1.5
var keywords = 'after and andalso band begin bnot bor bsl bsr bxor '+
'case catch cond div end fun if let not of or orelse '+
'query receive rem try when xor'+
// additional
' module export import define';
this.regexList = [
{ regex: new RegExp("[A-Z][A-Za-z0-9_]+", 'g'), css: 'constants' },
{ regex: new RegExp("\\%.+", 'gm'), css: 'comments' },
{ regex: new RegExp("\\?[A-Za-z0-9_]+", 'g'), css: 'preprocessor' },
{ regex: new RegExp("[a-z0-9_]+:[a-z0-9_]+", 'g'), css: 'functions' },
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' },
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' },
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }
];
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['erl', 'erlang'];
SyntaxHighlighter.brushes.Erland = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| beck24/KnownSyntaxHighlight | vendor/syntaxhighlighter/scripts/shBrushErlang.js | JavaScript | gpl-2.0 | 1,714 |
require("source-map-support").install();
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _this2 = this;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
__webpack_require__(14);
var _path = __webpack_require__(17);
var _path2 = _interopRequireDefault(_path);
var _express = __webpack_require__(15);
var _express2 = _interopRequireDefault(_express);
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDomServer = __webpack_require__(18);
var _reactDomServer2 = _interopRequireDefault(_reactDomServer);
var _routerRoutes = __webpack_require__(6);
var _routerRoutes2 = _interopRequireDefault(_routerRoutes);
var _srcComponentsHtml = __webpack_require__(8);
var _srcComponentsHtml2 = _interopRequireDefault(_srcComponentsHtml);
var _srcConfigConf = __webpack_require__(2);
var server = global.server = (0, _express2['default'])();
server.set('port', process.env.PORT || _srcConfigConf._SERVER.PORT);
server.use(_express2['default']['static'](_path2['default'].join(__dirname, '../assets')));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', function callee$0$0(req, res, next) {
return regeneratorRuntime.async(function callee$0$0$(context$1$0) {
var _this = this;
while (1) switch (context$1$0.prev = context$1$0.next) {
case 0:
context$1$0.prev = 0;
context$1$0.next = 3;
return regeneratorRuntime.awrap((function callee$1$0() {
var statusCode, data, css, context, html;
return regeneratorRuntime.async(function callee$1$0$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
statusCode = 200;
data = { title: '', description: '', css: '', body: '' };
css = [];
context = {
onInsertCss: function onInsertCss(value) {
return css.push(value);
},
onSetTitle: function onSetTitle(value) {
return data.title = value;
},
onSetMeta: function onSetMeta(key, value) {
return data[key] = value;
},
onPageNotFound: function onPageNotFound() {
return statusCode = 404;
}
};
context$2$0.next = 6;
return regeneratorRuntime.awrap(_routerRoutes2['default'].dispatch({ path: req.path, context: context }, function (state, component) {
data.body = _reactDomServer2['default'].renderToString(component);
data.css = css.join('');
}));
case 6:
html = _reactDomServer2['default'].renderToStaticMarkup(_react2['default'].createElement(_srcComponentsHtml2['default'], data));
res.status(statusCode).send('<!doctype html>\n' + html);
case 8:
case 'end':
return context$2$0.stop();
}
}, null, _this);
})());
case 3:
context$1$0.next = 8;
break;
case 5:
context$1$0.prev = 5;
context$1$0.t0 = context$1$0['catch'](0);
next(context$1$0.t0);
case 8:
case 'end':
return context$1$0.stop();
}
}, null, _this2, [[0, 5]]);
});
//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(server.get('port'), function () {
/* eslint-disable no-console */
console.log('[sucess] The server is running at http://localhost:' + server.get('port'));
if (process.send) {
process.send('online');
}
});
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = require("react");
/***/ },
/* 2 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = {
_SERVER: {
PORT: 3030
},
_GLOBAL: {
WATCH: true
},
_WEBSITE: {
charSet: 'utf-8',
signs: '<link rel="apple-touch-icon" href="apple-touch-icon.png" />\n',
googleAnalyticsId: 'UA-XXXXX-X'
}
};
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports) {
/**
* React Routing | http://www.kriasoft.com/react-routing
* Copyright (c) Konstantin Tarkus <hello@tarkus.me> | The MIT License
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var Match = function Match(route, path, keys, match) {
_classCallCheck(this, Match);
this.route = route;
this.path = path;
this.params = Object.create(null);
for (var i = 1; i < match.length; i++) {
this.params[keys[i - 1].name] = decodeParam(match[i]);
}
};
function decodeParam(val) {
if (!(typeof val === 'string' || val instanceof String)) {
return val;
}
try {
return decodeURIComponent(val);
} catch (e) {
var err = new TypeError('Failed to decode param \'' + val + '\'');
err.status = 400;
throw err;
}
}
exports['default'] = Match;
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/**
* React Routing | http://www.kriasoft.com/react-routing
* Copyright (c) Konstantin Tarkus <hello@tarkus.me> | The MIT License
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: 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; }; })();
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'); } }
var _pathToRegexp = __webpack_require__(12);
var _pathToRegexp2 = _interopRequireDefault(_pathToRegexp);
var _Match = __webpack_require__(3);
var _Match2 = _interopRequireDefault(_Match);
var Route = (function () {
function Route(path, handlers) {
_classCallCheck(this, Route);
this.path = path;
this.handlers = handlers;
this.regExp = (0, _pathToRegexp2['default'])(path, this.keys = []);
}
_createClass(Route, [{
key: 'match',
value: function match(path) {
var match = this.regExp.exec(path);
return match ? new _Match2['default'](this, path, this.keys, match) : null;
}
}]);
return Route;
})();
exports['default'] = Route;
module.exports = exports['default'];
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
/**
* React Routing | http://www.kriasoft.com/react-routing
* Copyright (c) Konstantin Tarkus <hello@tarkus.me> | The MIT License
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
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; }; })();
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'); } }
var _Route = __webpack_require__(4);
var _Route2 = _interopRequireDefault(_Route);
var emptyFunction = function emptyFunction() {};
var Router = (function () {
/**
* Creates a new instance of the `Router` class.
*/
function Router(initialize) {
_classCallCheck(this, Router);
this.routes = [];
this.events = Object.create(null);
if (typeof initialize === 'function') {
initialize(this.on.bind(this));
}
}
/**
* Adds a new route to the routing table or registers an event listener.
*
* @param {String} path A string in the Express format, an array of strings, or a regular expression.
* @param {Function|Array} handlers Asynchronous route handler function(s).
*/
_createClass(Router, [{
key: 'on',
value: function on(path) {
for (var _len = arguments.length, handlers = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
handlers[_key - 1] = arguments[_key];
}
if (path === 'error') {
this.events[path] = handlers[0];
} else {
this.routes.push(new _Route2['default'](path, handlers));
}
}
}, {
key: 'dispatch',
value: function dispatch(state, cb) {
var routes, handlers, value, result, done, next;
return regeneratorRuntime.async(function dispatch$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
next = function next() {
var _handlers$next;
var _value, _value2, match, handler;
return regeneratorRuntime.async(function next$(context$3$0) {
while (1) switch (context$3$0.prev = context$3$0.next) {
case 0:
if (!((_handlers$next = handlers.next(), value = _handlers$next.value, done = _handlers$next.done, _handlers$next) && !done)) {
context$3$0.next = 16;
break;
}
_value = value;
_value2 = _slicedToArray(_value, 2);
match = _value2[0];
handler = _value2[1];
state.params = match.params;
if (!(handler.length > 1)) {
context$3$0.next = 12;
break;
}
context$3$0.next = 9;
return regeneratorRuntime.awrap(handler(state, next));
case 9:
context$3$0.t0 = context$3$0.sent;
context$3$0.next = 15;
break;
case 12:
context$3$0.next = 14;
return regeneratorRuntime.awrap(handler(state));
case 14:
context$3$0.t0 = context$3$0.sent;
case 15:
return context$3$0.abrupt('return', context$3$0.t0);
case 16:
case 'end':
return context$3$0.stop();
}
}, null, this);
};
if (typeof state === 'string' || state instanceof String) {
state = { path: state };
}
cb = cb || emptyFunction;
routes = this.routes;
handlers = regeneratorRuntime.mark(function callee$2$0() {
var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, route, match, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, handler;
return regeneratorRuntime.wrap(function callee$2$0$(context$3$0) {
while (1) switch (context$3$0.prev = context$3$0.next) {
case 0:
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
context$3$0.prev = 3;
_iterator = routes[Symbol.iterator]();
case 5:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
context$3$0.next = 38;
break;
}
route = _step.value;
match = route.match(state.path);
if (!match) {
context$3$0.next = 35;
break;
}
_iteratorNormalCompletion2 = true;
_didIteratorError2 = false;
_iteratorError2 = undefined;
context$3$0.prev = 12;
_iterator2 = match.route.handlers[Symbol.iterator]();
case 14:
if (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done) {
context$3$0.next = 21;
break;
}
handler = _step2.value;
context$3$0.next = 18;
return [match, handler];
case 18:
_iteratorNormalCompletion2 = true;
context$3$0.next = 14;
break;
case 21:
context$3$0.next = 27;
break;
case 23:
context$3$0.prev = 23;
context$3$0.t0 = context$3$0['catch'](12);
_didIteratorError2 = true;
_iteratorError2 = context$3$0.t0;
case 27:
context$3$0.prev = 27;
context$3$0.prev = 28;
if (!_iteratorNormalCompletion2 && _iterator2['return']) {
_iterator2['return']();
}
case 30:
context$3$0.prev = 30;
if (!_didIteratorError2) {
context$3$0.next = 33;
break;
}
throw _iteratorError2;
case 33:
return context$3$0.finish(30);
case 34:
return context$3$0.finish(27);
case 35:
_iteratorNormalCompletion = true;
context$3$0.next = 5;
break;
case 38:
context$3$0.next = 44;
break;
case 40:
context$3$0.prev = 40;
context$3$0.t1 = context$3$0['catch'](3);
_didIteratorError = true;
_iteratorError = context$3$0.t1;
case 44:
context$3$0.prev = 44;
context$3$0.prev = 45;
if (!_iteratorNormalCompletion && _iterator['return']) {
_iterator['return']();
}
case 47:
context$3$0.prev = 47;
if (!_didIteratorError) {
context$3$0.next = 50;
break;
}
throw _iteratorError;
case 50:
return context$3$0.finish(47);
case 51:
return context$3$0.finish(44);
case 52:
case 'end':
return context$3$0.stop();
}
}, callee$2$0, this, [[3, 40, 44, 52], [12, 23, 27, 35], [28,, 30, 34], [45,, 47, 51]]);
})();
value = undefined, result = undefined, done = false;
case 6:
if (done) {
context$2$0.next = 16;
break;
}
context$2$0.next = 9;
return regeneratorRuntime.awrap(next());
case 9:
result = context$2$0.sent;
if (!result) {
context$2$0.next = 14;
break;
}
state.statusCode = 200;
cb(state, result);
return context$2$0.abrupt('return');
case 14:
context$2$0.next = 6;
break;
case 16:
if (!this.events.error) {
context$2$0.next = 32;
break;
}
context$2$0.prev = 17;
state.statusCode = 404;
context$2$0.next = 21;
return regeneratorRuntime.awrap(this.events.error(state, new Error('Cannot found a route matching \'' + state.path + '\'.')));
case 21:
result = context$2$0.sent;
cb(state, result);
context$2$0.next = 32;
break;
case 25:
context$2$0.prev = 25;
context$2$0.t0 = context$2$0['catch'](17);
state.statusCode = 500;
context$2$0.next = 30;
return regeneratorRuntime.awrap(this.events.error(state, context$2$0.t0));
case 30:
result = context$2$0.sent;
cb(state, result);
case 32:
case 'end':
return context$2$0.stop();
}
}, null, this, [[17, 25]]);
}
}]);
return Router;
})();
exports['default'] = Router;
module.exports = exports['default'];
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _this = this;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactRoutingSrcRouter = __webpack_require__(5);
var _reactRoutingSrcRouter2 = _interopRequireDefault(_reactRoutingSrcRouter);
var _srcCoreHttpClient = __webpack_require__(9);
var _srcCoreHttpClient2 = _interopRequireDefault(_srcCoreHttpClient);
var _srcComponentsApp = __webpack_require__(7);
var _srcComponentsApp2 = _interopRequireDefault(_srcComponentsApp);
var _srcLayoutCommonNotFoundPage = __webpack_require__(11);
var _srcLayoutCommonNotFoundPage2 = _interopRequireDefault(_srcLayoutCommonNotFoundPage);
var _srcLayoutCommonErrorPage = __webpack_require__(10);
var _srcLayoutCommonErrorPage2 = _interopRequireDefault(_srcLayoutCommonErrorPage);
var router = new _reactRoutingSrcRouter2['default'](function (on) {
on('*', function callee$1$0(state, next) {
var component;
return regeneratorRuntime.async(function callee$1$0$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
context$2$0.next = 2;
return regeneratorRuntime.awrap(next());
case 2:
component = context$2$0.sent;
return context$2$0.abrupt('return', component && _react2['default'].createElement(
_srcComponentsApp2['default'],
{ context: state.context },
component
));
case 4:
case 'end':
return context$2$0.stop();
}
}, null, _this);
});
// on('/contact', async () => <ContactPage />);
on('*', function callee$1$0(state) {
var content;
return regeneratorRuntime.async(function callee$1$0$(context$2$0) {
while (1) switch (context$2$0.prev = context$2$0.next) {
case 0:
context$2$0.next = 2;
return regeneratorRuntime.awrap(_srcCoreHttpClient2['default'].get('/api/content?path=' + state.path));
case 2:
content = context$2$0.sent;
return context$2$0.abrupt('return', content && _react2['default'].createElement(ContentPage, content));
case 4:
case 'end':
return context$2$0.stop();
}
}, null, _this);
});
on('error', function (state, error) {
return state.statusCode === 404 ? _react2['default'].createElement(
_srcComponentsApp2['default'],
{ context: state.context, error: error },
_react2['default'].createElement(_srcLayoutCommonNotFoundPage2['default'], null)
) : _react2['default'].createElement(
_srcComponentsApp2['default'],
{ context: state.context, error: error },
_react2['default'].createElement(_srcLayoutCommonErrorPage2['default'], null)
);
});
});
exports['default'] = router;
module.exports = exports['default'];
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
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 _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 _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var App = (function (_Component) {
_inherits(App, _Component);
function App() {
_classCallCheck(this, App);
_get(Object.getPrototypeOf(App.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(App, [{
key: 'render',
value: function render() {
return !this.props.error ? _react2['default'].createElement(
'div',
null,
this.props.children
) : this.props.children;
}
}], [{
key: 'propTypes',
value: {
children: _react.PropTypes.element.isRequired,
error: _react.PropTypes.object
},
enumerable: true
}]);
return App;
})(_react.Component);
exports['default'] = App;
module.exports = exports['default'];
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
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 _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 _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _configConf = __webpack_require__(2);
var Html = (function (_Component) {
_inherits(Html, _Component);
function Html() {
_classCallCheck(this, Html);
_get(Object.getPrototypeOf(Html.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Html, [{
key: 'trackingCode',
value: function trackingCode() {
return { __html: '(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=' + 'function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;' + 'e=o.createElement(i);r=o.getElementsByTagName(i)[0];' + 'e.src=\'https://www.google-analytics.com/analytics.js\';' + 'r.parentNode.insertBefore(e,r)}(window,document,\'script\',\'ga\'));' + ('ga(\'create\',\'' + _configConf._WEBSITE.googleAnalyticsId + '\',\'auto\');ga(\'send\',\'pageview\');')
};
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement(
'html',
{ className: 'no-js', lang: '' },
_react2['default'].createElement(
'head',
null,
_react2['default'].createElement('meta', { charSet: _configConf._WEBSITE.charSet }),
_react2['default'].createElement('meta', { httpEquiv: 'X-UA-Compatible', content: 'IE=edge' }),
_react2['default'].createElement(
'title',
null,
this.props.title
),
_react2['default'].createElement('meta', { name: 'description', content: this.props.description }),
_react2['default'].createElement('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1, user-scalable=no' }),
_configConf._WEBSITE.signs,
_react2['default'].createElement('style', { id: 'css', dangerouslySetInnerHTML: { __html: this.props.css } })
),
_react2['default'].createElement(
'body',
null,
_react2['default'].createElement('div', { id: 'app', dangerouslySetInnerHTML: { __html: this.props.body } }),
_react2['default'].createElement('script', { src: '/app.js' }),
_react2['default'].createElement('script', { dangerouslySetInnerHTML: this.trackingCode() })
)
);
}
}], [{
key: 'propTypes',
value: {
title: _react.PropTypes.string,
description: _react.PropTypes.string,
css: _react.PropTypes.string,
body: _react.PropTypes.string.isRequired
},
enumerable: true
}, {
key: 'defaultProps',
value: {
title: '',
description: ''
},
enumerable: true
}]);
return Html;
})(_react.Component);
exports['default'] = Html;
module.exports = exports['default'];
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _superagent = __webpack_require__(19);
var _superagent2 = _interopRequireDefault(_superagent);
var _fbjsLibExecutionEnvironment = __webpack_require__(16);
function getUrl(path) {
if (path.startsWith('http') || _fbjsLibExecutionEnvironment.canUseDOM) {
return path;
}
return process.env.WEBSITE_HOSTNAME ? 'http://' + process.env.WEBSITE_HOSTNAME + path : 'http://127.0.0.1:' + global.server.get('port') + path;
}
var HttpClient = {
get: function get(path) {
return new Promise(function (resolve, reject) {
_superagent2['default'].get(getUrl(path)).accept('application/json').end(function (err, res) {
if (err) {
if (err.status === 404) {
resolve(null);
} else {
reject(err);
}
} else {
resolve(res.body);
}
});
});
}
};
exports['default'] = HttpClient;
module.exports = exports['default'];
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
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 _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 _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var NotFoundPage = (function (_Component) {
_inherits(NotFoundPage, _Component);
function NotFoundPage() {
_classCallCheck(this, NotFoundPage);
_get(Object.getPrototypeOf(NotFoundPage.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(NotFoundPage, [{
key: 'render',
value: function render() {
return _react2['default'].createElement(
'h2',
null,
'Sorry, an critical error occurred on this page.'
);
}
}]);
return NotFoundPage;
})(_react.Component);
exports['default'] = NotFoundPage;
module.exports = exports['default'];
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
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 _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 _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var NotFoundPage = (function (_Component) {
_inherits(NotFoundPage, _Component);
function NotFoundPage() {
_classCallCheck(this, NotFoundPage);
_get(Object.getPrototypeOf(NotFoundPage.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(NotFoundPage, [{
key: 'render',
value: function render() {
return _react2['default'].createElement(
'h2',
null,
'Sorry, but the page you were trying to view does not exist.'
);
}
}]);
return NotFoundPage;
})(_react.Component);
exports['default'] = NotFoundPage;
module.exports = exports['default'];
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var isarray = __webpack_require__(13)
/**
* Expose `pathToRegexp`.
*/
module.exports = pathToRegexp
module.exports.parse = parse
module.exports.compile = compile
module.exports.tokensToFunction = tokensToFunction
module.exports.tokensToRegExp = tokensToRegExp
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^()])+)\\))?|\\(((?:\\\\.|[^()])+)\\))([+*?])?|(\\*))'
].join('|'), 'g')
/**
* Parse a string for the raw tokens.
*
* @param {String} str
* @return {Array}
*/
function parse (str) {
var tokens = []
var key = 0
var index = 0
var path = ''
var res
while ((res = PATH_REGEXP.exec(str)) != null) {
var m = res[0]
var escaped = res[1]
var offset = res.index
path += str.slice(index, offset)
index = offset + m.length
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1]
continue
}
// Push the current path onto the tokens.
if (path) {
tokens.push(path)
path = ''
}
var prefix = res[2]
var name = res[3]
var capture = res[4]
var group = res[5]
var suffix = res[6]
var asterisk = res[7]
var repeat = suffix === '+' || suffix === '*'
var optional = suffix === '?' || suffix === '*'
var delimiter = prefix || '/'
var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?')
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
pattern: escapeGroup(pattern)
})
}
// Match any characters still remaining.
if (index < str.length) {
path += str.substr(index)
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path)
}
return tokens
}
/**
* Compile a string to a template function for the path.
*
* @param {String} str
* @return {Function}
*/
function compile (str) {
return tokensToFunction(parse(str))
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction (tokens) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length)
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'object') {
matches[i] = new RegExp('^' + tokens[i].pattern + '$')
}
}
return function (obj) {
var path = ''
var data = obj || {}
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i]
if (typeof token === 'string') {
path += token
continue
}
var value = data[token.name]
var segment
if (value == null) {
if (token.optional) {
continue
} else {
throw new TypeError('Expected "' + token.name + '" to be defined')
}
}
if (isarray(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but received "' + value + '"')
}
if (value.length === 0) {
if (token.optional) {
continue
} else {
throw new TypeError('Expected "' + token.name + '" to not be empty')
}
}
for (var j = 0; j < value.length; j++) {
segment = encodeURIComponent(value[j])
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
}
path += (j === 0 ? token.prefix : token.delimiter) + segment
}
continue
}
segment = encodeURIComponent(value)
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
}
path += token.prefix + segment
}
return path
}
}
/**
* Escape a regular expression string.
*
* @param {String} str
* @return {String}
*/
function escapeString (str) {
return str.replace(/([.+*?=^!:${}()[\]|\/])/g, '\\$1')
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {String} group
* @return {String}
*/
function escapeGroup (group) {
return group.replace(/([=!:$\/()])/g, '\\$1')
}
/**
* Attach the keys as a property of the regexp.
*
* @param {RegExp} re
* @param {Array} keys
* @return {RegExp}
*/
function attachKeys (re, keys) {
re.keys = keys
return re
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {String}
*/
function flags (options) {
return options.sensitive ? '' : 'i'
}
/**
* Pull out keys from a regexp.
*
* @param {RegExp} path
* @param {Array} keys
* @return {RegExp}
*/
function regexpToRegexp (path, keys) {
// Use a negative lookahead to match only capturing groups.
var groups = path.source.match(/\((?!\?)/g)
if (groups) {
for (var i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: null,
delimiter: null,
optional: false,
repeat: false,
pattern: null
})
}
}
return attachKeys(path, keys)
}
/**
* Transform an array into a regexp.
*
* @param {Array} path
* @param {Array} keys
* @param {Object} options
* @return {RegExp}
*/
function arrayToRegexp (path, keys, options) {
var parts = []
for (var i = 0; i < path.length; i++) {
parts.push(pathToRegexp(path[i], keys, options).source)
}
var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options))
return attachKeys(regexp, keys)
}
/**
* Create a path regexp from string input.
*
* @param {String} path
* @param {Array} keys
* @param {Object} options
* @return {RegExp}
*/
function stringToRegexp (path, keys, options) {
var tokens = parse(path)
var re = tokensToRegExp(tokens, options)
// Attach keys back to the regexp.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] !== 'string') {
keys.push(tokens[i])
}
}
return attachKeys(re, keys)
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {Array} tokens
* @param {Array} keys
* @param {Object} options
* @return {RegExp}
*/
function tokensToRegExp (tokens, options) {
options = options || {}
var strict = options.strict
var end = options.end !== false
var route = ''
var lastToken = tokens[tokens.length - 1]
var endsWithSlash = typeof lastToken === 'string' && /\/$/.test(lastToken)
// Iterate over the tokens and create our regexp string.
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i]
if (typeof token === 'string') {
route += escapeString(token)
} else {
var prefix = escapeString(token.prefix)
var capture = token.pattern
if (token.repeat) {
capture += '(?:' + prefix + capture + ')*'
}
if (token.optional) {
if (prefix) {
capture = '(?:' + prefix + '(' + capture + '))?'
} else {
capture = '(' + capture + ')?'
}
} else {
capture = prefix + '(' + capture + ')'
}
route += capture
}
}
// In non-strict mode we allow a slash at the end of match. If the path to
// match already ends with a slash, we remove it for consistency. The slash
// is valid at the end of a path match, not in the middle. This is important
// in non-ending mode, where "/test/" shouldn't match "/test//route".
if (!strict) {
route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\/(?=$))?'
}
if (end) {
route += '$'
} else {
// In non-ending mode, we need the capturing groups to match as much as
// possible by using a positive lookahead to the end or next path segment.
route += strict && endsWithSlash ? '' : '(?=\\/|$)'
}
return new RegExp('^' + route, flags(options))
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*
* @param {(String|RegExp|Array)} path
* @param {Array} [keys]
* @param {Object} [options]
* @return {RegExp}
*/
function pathToRegexp (path, keys, options) {
keys = keys || []
if (!isarray(keys)) {
options = keys
keys = []
} else if (!options) {
options = {}
}
if (path instanceof RegExp) {
return regexpToRegexp(path, keys, options)
}
if (isarray(path)) {
return arrayToRegexp(path, keys, options)
}
return stringToRegexp(path, keys, options)
}
/***/ },
/* 13 */
/***/ function(module, exports) {
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
/***/ },
/* 14 */
/***/ function(module, exports) {
module.exports = require("babel-core/polyfill");
/***/ },
/* 15 */
/***/ function(module, exports) {
module.exports = require("express");
/***/ },
/* 16 */
/***/ function(module, exports) {
module.exports = require("fbjs/lib/ExecutionEnvironment");
/***/ },
/* 17 */
/***/ function(module, exports) {
module.exports = require("path");
/***/ },
/* 18 */
/***/ function(module, exports) {
module.exports = require("react-dom/server");
/***/ },
/* 19 */
/***/ function(module, exports) {
module.exports = require("superagent");
/***/ }
/******/ ]);
//# sourceMappingURL=server.js.map | wmkcc/uiams | build/server.js | JavaScript | gpl-2.0 | 50,686 |
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'pl', {
title: 'Instrukcje dotyczące dostępności',
contents: 'Zawartość pomocy. Wciśnij ESC, aby zamknąć to okno.',
legend: [
{
name: 'Informacje ogólne',
items: [
{
name: 'Pasek narzędzi edytora',
legend: 'Naciśnij ${toolbarFocus}, by przejść do paska narzędzi. Przejdź do następnej i poprzedniej grupy narzędzi używając TAB oraz SHIFT+TAB. Przejdź do następnego i poprzedniego przycisku paska narzędzi za pomocą STRZAŁKI W PRAWO lub STRZAŁKI W LEWO. Naciśnij SPACJĘ lub ENTER by aktywować przycisk paska narzędzi.'
},
{
name: 'Okno dialogowe edytora',
legend:
'Wewnątrz okna dialogowego naciśnij TAB, by przejść do kolejnego elementu tego okna lub SHIFT+TAB, by przejść do poprzedniego elementu okna. Naciśnij ENTER w celu zatwierdzenia opcji okna dialogowego lub ESC w celu anulowania zmian. Jeśli okno dialogowe ma kilka zakładek, do listy zakładek można przejść za pomocą ALT+F10 lub TAB. Gdy lista zakładek jest aktywna, możesz przejść do kolejnej i poprzedniej zakładki za pomocą STRZAŁKI W PRAWO i STRZAŁKI W LEWO.'
},
{
name: 'Menu kontekstowe edytora',
legend: 'Wciśnij ${contextMenu} lub PRZYCISK APLIKACJI aby otworzyć menu kontekstowe. Przejdź do następnej pozycji menu wciskając TAB lub STRZAŁKĘ W DÓŁ. Przejdź do poprzedniej pozycji menu wciskając SHIFT + TAB lub STRZAŁKĘ W GÓRĘ. Wciśnij SPACJĘ lub ENTER aby wygrać pozycję menu. Otwórz pod-menu obecnej pozycji wciskając SPACJĘ lub ENTER lub STRZAŁKĘ W PRAWO. Wróć do pozycji nadrzędnego menu wciskając ESC lub STRZAŁKĘ W LEWO. Zamknij menu wciskając ESC.'
},
{
name: 'Lista w edytorze',
legend: 'Wewnątrz listy przejdź do kolejnego elementu listy za pomocą przycisku TAB lub STRZAŁKI W DÓŁ. Przejdź do poprzedniego elementu listy za pomocą SHIFT+TAB lub STRZAŁKI W GÓRĘ. Naciśnij SPACJĘ lub ENTER w celu wybrania opcji z listy. Naciśnij ESC, by zamknąć listę.'
},
{
name: 'Pasek ścieżki elementów edytora',
legend: 'Naciśnij ${elementsPathFocus} w celu przejścia do paska ścieżki elementów edytora. W celu przejścia do kolejnego elementu naciśnij klawisz TAB lub STRZAŁKI W PRAWO. W celu przejścia do poprzedniego elementu naciśnij klawisze SHIFT+TAB lub STRZAŁKI W LEWO. By wybrać element w edytorze, użyj klawisza SPACJI lub ENTER.'
}
]
},
{
name: 'Polecenia',
items: [
{
name: 'Polecenie Cofnij',
legend: 'Naciśnij ${undo}'
},
{
name: 'Polecenie Ponów',
legend: 'Naciśnij ${redo}'
},
{
name: 'Polecenie Pogrubienie',
legend: 'Naciśnij ${bold}'
},
{
name: 'Polecenie Kursywa',
legend: 'Naciśnij ${italic}'
},
{
name: 'Polecenie Podkreślenie',
legend: 'Naciśnij ${underline}'
},
{
name: 'Polecenie Wstaw/ edytuj odnośnik',
legend: 'Naciśnij ${link}'
},
{
name: 'Polecenie schowaj pasek narzędzi',
legend: 'Naciśnij ${toolbarCollapse}'
},
{
name: ' Access previous focus space command', // MISSING
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.' // MISSING
},
{
name: ' Access next focus space command', // MISSING
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.' // MISSING
},
{
name: 'Pomoc dotycząca dostępności',
legend: 'Naciśnij ${a11yHelp}'
}
]
}
],
backspace: 'Backspace',
tab: 'Tab',
enter: 'Enter',
shift: 'Shift',
ctrl: 'Ctrl',
alt: 'Alt',
pause: 'Pause',
capslock: 'Caps Lock',
escape: 'Escape',
pageUp: 'Page Up',
pageDown: 'Page Down',
end: 'End',
home: 'Home',
leftArrow: 'Strzałka w lewo',
upArrow: 'Strzałka w górę',
rightArrow: 'Strzałka w prawo',
downArrow: 'Strzałka w dół',
insert: 'Insert',
'delete': 'Delete',
leftWindowKey: 'Lewy klawisz Windows',
rightWindowKey: 'Prawy klawisz Windows',
selectKey: 'Klawisz wyboru',
numpad0: 'Klawisz 0 na klawiaturze numerycznej',
numpad1: 'Klawisz 1 na klawiaturze numerycznej',
numpad2: 'Klawisz 2 na klawiaturze numerycznej',
numpad3: 'Klawisz 3 na klawiaturze numerycznej',
numpad4: 'Klawisz 4 na klawiaturze numerycznej',
numpad5: 'Klawisz 5 na klawiaturze numerycznej',
numpad6: 'Klawisz 6 na klawiaturze numerycznej',
numpad7: 'Klawisz 7 na klawiaturze numerycznej',
numpad8: 'Klawisz 8 na klawiaturze numerycznej',
numpad9: 'Klawisz 9 na klawiaturze numerycznej',
multiply: 'Przemnóż',
add: 'Plus',
subtract: 'Minus',
decimalPoint: 'Separator dziesiętny',
divide: 'Podziel',
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: 'Średnik',
equalSign: 'Znak równości',
comma: 'Przecinek',
dash: 'Pauza',
period: 'Kropka',
forwardSlash: 'Ukośnik prawy',
graveAccent: 'Akcent słaby',
openBracket: 'Nawias kwadratowy otwierający',
backSlash: 'Ukośnik lewy',
closeBracket: 'Nawias kwadratowy zamykający',
singleQuote: 'Apostrof'
} );
| SeeyaSia/www | web/libraries/ckeditor/plugins/a11yhelp/dialogs/lang/pl.js | JavaScript | gpl-2.0 | 5,500 |
/**
* Copyright 2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public
* License as published by the Free Software Foundation; either version
* 2 of the License (GPLv2) or (at your option) any later version.
* There is NO WARRANTY for this software, express or implied,
* including the implied warranties of MERCHANTABILITY,
* NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
* have received a copy of GPLv2 along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*/
describe('Controller: ActivationKeyAddSubscriptionsController', function() {
var $scope,
ActivationKey,
SubscriptionsHelper,
Nutupane,
subscriptions;
beforeEach(module('Bastion.activation-keys', 'Bastion.subscriptions', 'Bastion.test-mocks',
'activation-keys/details/views/activation-key-add-subscriptions.html'));
beforeEach(function() {
Nutupane = function() {
this.table = {
showColumns: function() {}
};
this.get = function() {};
};
ActivationKey = {};
});
beforeEach(inject(function($controller, $rootScope, $location, $state, $injector) {
$scope = $rootScope.$new();
SubscriptionsHelper = $injector.get('SubscriptionsHelper')
subscriptions = {
"total": 9,
"subtotal": 9,
"offset": null,
"limit": null,
"search": "",
"sort": {
"by": "name",
"order": "ASC"
},
"results": [
{
"organization": {"name": "Mega Corporation", "label": "megacorp"},
"id": "ff80808143f94b760143fcee78210166",
"description": "",
"product_name": "Point of Sale",
"start_date": "2014-02-04",
"end_date": "2044-01-28",
"available": -1,
"quantity": -1,
"consumed": 0,
"amount": null,
"account_number": null,
"contract_number": null,
"support_type": "",
"support_level": "",
"product_id": "1391517922933",
"arch": "ALL",
"virt_only": false,
"sockets": 0,
"cores": 0,
"ram": 0,
"instance_multiplier": null,
"stacking_id": "",
"multi_entitlement": false
},
{
"organization": {"name": "Mega Corporation", "label": "megacorp"},
"id": "ff80808143f94b760143fceb9aca014b",
"description": "RHEV",
"product_name": "Red Hat Enterprise Virtualization Offering, Premium (2-socket)",
"start_date": "2013-12-31",
"end_date": "2016-12-31",
"available": 1,
"quantity": 1,
"consumed": 0,
"amount": null,
"account_number": "5364043",
"contract_number": "10317431",
"support_type": "L1-L3",
"support_level": "Premium",
"product_id": "MCT2927F3",
"arch": "x86_64,ppc64,ia64,ppc,x86,s390,s390x",
"virt_only": false,
"sockets": 2,
"cores": 0,
"ram": 0,
"instance_multiplier": null,
"stacking_id": "MCT2927F3",
"multi_entitlement": true,
"provided_products": [
{"id": "ff80808143f94b760143fceb9acb015c", "name": "Red Hat Beta"},
{"id": "ff80808143f94b760143fceb9acb015d", "name": "Red Hat Enterprise Linux Server - Extended Update Support"},
{"id": "ff80808143f94b760143fceb9acb015e", "name": "Red Hat Software Collections (for RHEL Server)"},
{"id": "ff80808143f94b760143fceb9acb015f", "name": "Red Hat Enterprise Virtualization"},
{"id": "ff80808143f94b760143fceb9acb0160", "name": "Red Hat Enterprise Linux Server"},
{"id": "ff80808143f94b760143fceb9acb0161", "name": "Red Hat Software Collections Beta (for RHEL Server)"}
]
},
{
"organization": { "name": "Mega Corporation", "label": "megacorp"},
"id": "ff80808143f94b760143fceb9aa40134",
"description": "RHEV",
"product_name": "Red Hat Enterprise Virtualization Offering, Premium (2-socket)",
"start_date": "2013-12-31",
"end_date": "2016-12-31",
"available": 1,
"quantity": 1,
"consumed": 0,
"amount": null,
"account_number": "5364043",
"contract_number": "10317433",
"support_type": "L1-L3",
"support_level": "Premium",
"product_id": "MCT2927F3RN",
"arch": "x86_64,ppc64,ia64,ppc,s390,x86,s390x",
"virt_only": false,
"sockets": 2,
"cores": 0,
"ram": 0,
"instance_multiplier": null,
"stacking_id": "MCT2927F3",
"multi_entitlement": true,
"provided_products": [
{"id": "ff80808143f94b760143fceb9aa50145", "name": "Red Hat Beta"},
{"id": "ff80808143f94b760143fceb9aa50146", "name": "Red Hat Enterprise Linux Server - Extended Update Support"},
{"id": "ff80808143f94b760143fceb9aa50147", "name": "Red Hat Software Collections (for RHEL Server)"},
{"id": "ff80808143f94b760143fceb9aa50148", "name": "Red Hat Enterprise Virtualization"},
{"id": "ff80808143f94b760143fceb9aa50149", "name": "Red Hat Enterprise Linux Server"},
{"id": "ff80808143f94b760143fceb9aa5014a", "name": "Red Hat Software Collections Beta (for RHEL Server)"}
]
},
{
"organization": {"name": "Mega Corporation", "label": "megacorp"},
"id": "ff80808143f94b760143fceb9a8a011d",
"description": "RHEV",
"product_name": "Red Hat Enterprise Virtualization Offering, Premium (2-socket)",
"start_date": "2012-12-31",
"end_date": "2015-12-31",
"available": 1,
"quantity": 1,
"consumed": 0,
"amount": null,
"account_number": "5364043",
"contract_number": "10300070",
"support_type": "L1-L3",
"support_level": "Premium",
"product_id": "MCT2927F3RN",
"arch": "x86_64,ppc64,ia64,ppc,s390,x86,s390x",
"virt_only": false,
"sockets": 2,
"cores": 0,
"ram": 0,
"instance_multiplier": null,
"stacking_id": "MCT2927F3",
"multi_entitlement": true,
"provided_products": [
{"id": "ff80808143f94b760143fceb9a8b012e", "name": "Red Hat Beta"},
{"id": "ff80808143f94b760143fceb9a8b012f", "name": "Red Hat Enterprise Linux Server - Extended Update Support"},
{"id": "ff80808143f94b760143fceb9a8b0130", "name": "Red Hat Software Collections (for RHEL Server)"},
{"id": "ff80808143f94b760143fceb9a8b0131", "name": "Red Hat Enterprise Virtualization"},
{"id": "ff80808143f94b760143fceb9a8b0132", "name": "Red Hat Enterprise Linux Server"},
{"id": "ff80808143f94b760143fceb9a8b0133", "name": "Red Hat Software Collections Beta (for RHEL Server)"}
]
},
{
"organization": {"name": "Mega Corporation", "label": "megacorp"},
"id": "ff80808143f94b760143fceb9a720106",
"description": "RHEV",
"product_name": "Red Hat Enterprise Virtualization Offering, Premium (2-socket)",
"start_date": "2012-12-31",
"end_date": "2015-12-31",
"available": 1,
"quantity": 1,
"consumed": 0,
"amount": null,
"account_number": "5364043",
"contract_number": "10300053",
"support_type": "L1-L3",
"support_level": "Premium",
"product_id": "MCT2927F3",
"arch": "x86_64,ppc64,ia64,ppc,x86,s390,s390x",
"virt_only": false,
"sockets": 2,
"cores": 0,
"ram": 0,
"instance_multiplier": null,
"stacking_id": "MCT2927F3",
"multi_entitlement": true,
"provided_products": [
{"id": "ff80808143f94b760143fceb9a730117", "name": "Red Hat Beta"},
{"id": "ff80808143f94b760143fceb9a730118", "name": "Red Hat Enterprise Linux Server - Extended Update Support"},
{"id": "ff80808143f94b760143fceb9a730119", "name": "Red Hat Software Collections (for RHEL Server)"},
{"id": "ff80808143f94b760143fceb9a73011a", "name": "Red Hat Enterprise Virtualization"},
{"id": "ff80808143f94b760143fceb9a73011b", "name": "Red Hat Enterprise Linux Server"},
{"id": "ff80808143f94b760143fceb9a73011c", "name": "Red Hat Software Collections Beta (for RHEL Server)"}
]
},
{
"organization": {"name": "Mega Corporation", "label": "megacorp"},
"id": "ff80808143f94b760143fceb9a5d00ed",
"description": "Red Hat Enterprise Linux",
"product_name": "Red Hat Enterprise Linux Server, Standard (Physical or Virtual Nodes)",
"start_date": "2013-12-31",
"end_date": "2014-12-31",
"available": 17,
"quantity": 20,
"consumed": 3,
"amount": null,
"account_number": "5364043",
"contract_number": "10317216",
"support_type": "L1-L3",
"support_level": "Standard",
"product_id": "RH00004",
"arch": "x86_64,ppc64,ia64,ppc,s390,x86,s390x",
"virt_only": false,
"sockets": 2,
"cores": 0,
"ram": 0,
"instance_multiplier": 2,
"stacking_id": "RH00004",
"multi_entitlement": true,
"provided_products": [
{"id": "ff80808143f94b760143fceb9a5e0101", "name": "Red Hat Beta"},
{"id": "ff80808143f94b760143fceb9a5e0102", "name": "Red Hat Enterprise Linux 7 Public Beta"},
{"id": "ff80808143f94b760143fceb9a5e0103", "name": "Red Hat Software Collections (for RHEL Server)"},
{"id": "ff80808143f94b760143fceb9a5e0104", "name": "Red Hat Enterprise Linux Server"},
{"id": "ff80808143f94b760143fceb9a5e0105", "name": "Red Hat Software Collections Beta (for RHEL Server)"}
]
},
{
"organization": {"name": "Mega Corporation", "label": "megacorp"},
"id": "ff80808143f94b760143fceb9a0f00b8",
"description": "Red Hat Enterprise Linux",
"product_name": "Red Hat Enterprise Linux Server, Premium (8 sockets) (Up to 4 guests)",
"start_date": "2013-12-31",
"end_date": "2014-12-31",
"available": 4,
"quantity": 4,
"consumed": 0,
"amount": null,
"account_number": "5364043",
"contract_number": "10317242",
"support_type": "L1-L3",
"support_level": "PREMIUM",
"product_id": "RH0103708",
"arch": "x86_64,ppc64,ia64,ppc,s390,x86,s390x",
"virt_only": false,
"sockets": 8,
"cores": 0,
"ram": 0,
"instance_multiplier": null,
"stacking_id": "",
"multi_entitlement": false,
"provided_products": [
{"id": "ff80808143f94b760143fceb9a1000c8", "name": "Red Hat Beta"},
{"id": "ff80808143f94b760143fceb9a1000c9", "name": "Red Hat Enterprise Linux 7 Public Beta"},
{"id": "ff80808143f94b760143fceb9a1000ca", "name": "Red Hat Enterprise Linux Server"},
{"id": "ff80808143f94b760143fceb9a1000cb", "name": "Red Hat Software Collections Beta (for RHEL Server)"}
]
},
{
"organization": {"name": "Mega Corporation", "label": "megacorp"},
"id": "ff80808143f94b760143fceb993300a4",
"description": "Red Hat Enterprise Linux",
"product_name": "Red Hat Enterprise Linux Server, Premium (8 sockets) (Up to 4 guests)",
"start_date": "2013-12-31",
"end_date": "2014-12-31",
"available": 3,
"quantity": 3,
"consumed": 0,
"amount": null,
"account_number": "5364043",
"contract_number": "10317242",
"support_type": "L1-L3",
"support_level": "PREMIUM",
"product_id": "RH0103708",
"arch": "x86_64,ppc64,ia64,ppc,s390,x86,s390x",
"virt_only": false,
"sockets": 8,
"cores": 0,
"ram": 0,
"instance_multiplier": null,
"stacking_id": "",
"multi_entitlement": false,
"provided_products": [
{"id": "ff80808143f94b760143fceb993a00b4", "name": "Red Hat Beta"},
{"id": "ff80808143f94b760143fceb993a00b5", "name": "Red Hat Enterprise Linux 7 Public Beta"},
{"id": "ff80808143f94b760143fceb993a00b6", "name": "Red Hat Enterprise Linux Server"},
{"id": "ff80808143f94b760143fceb993a00b7", "name": "Red Hat Software Collections Beta (for RHEL Server)"}
]
}
]
};
$controller('ActivationKeyAddSubscriptionsController', {
$scope: $scope,
$state: $state,
$location: $location,
translate: function() {},
Nutupane: Nutupane,
CurrentOrganization: function () {},
Subscription: function () {},
ActivationKey: ActivationKey,
SubscriptionsHelper: SubscriptionsHelper
});
}));
it('attaches the nutupane table to the scope', function () {
expect($scope.addSubscriptionsTable).toBeDefined();
});
it('groups subscriptions', function () {
spyOn(SubscriptionsHelper, 'groupByProductName').andCallThrough();
$scope.addSubscriptionsTable.rows = subscriptions.results;
$scope.$digest();
expect(SubscriptionsHelper.groupByProductName).toHaveBeenCalled();
expect($scope.groupedSubscriptions["Red Hat Enterprise Linux Server, Premium (8 sockets) (Up to 4 guests)"].length).toBe(2);
expect($scope.groupedSubscriptions["Point of Sale"].length).toBe(1);
expect($scope.groupedSubscriptions["Red Hat Enterprise Virtualization Offering, Premium (2-socket)"].length).toBe(4);
expect($scope.groupedSubscriptions["Red Hat Enterprise Linux Server, Standard (Physical or Virtual Nodes)"].length).toBe(1);
});
it('gets amount selector values appropriately', function() {
expect($scope.amountSelectorValues(subscriptions.results[0])).toEqual([-1]);
expect($scope.amountSelectorValues(subscriptions.results[1])).toEqual([1]);
expect($scope.amountSelectorValues(subscriptions.results[5])).toEqual([1, 2, 3, 4, 5, 20]);
expect($scope.amountSelectorValues(subscriptions.results[6])).toEqual([1, 2, 3, 4]);
expect($scope.amountSelectorValues(subscriptions.results[7])).toEqual([1, 2, 3]);
});
});
| ShimShtein/katello | engines/bastion_katello/test/activation-keys/details/activation-key-add-subscriptions.controller.test.js | JavaScript | gpl-2.0 | 20,341 |
/*! jQuery UI - v1.10.3 - 2013-09-10
* http://jqueryui.com
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.es={closeText:"Cerrar",prevText:"<Ant",nextText:"Sig>",currentText:"Hoy",monthNames:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],monthNamesShort:["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"],dayNames:["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"],dayNamesShort:["Dom","Lun","Mar","Mié","Juv","Vie","Sáb"],dayNamesMin:["Do","Lu","Ma","Mi","Ju","Vi","Sá"],weekHeader:"Sm",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.es)}); | eblipsky/NOW-web | laravel/public/jquery/development-bundle/ui/minified/i18n/jquery.ui.datepicker-es.min.js | JavaScript | gpl-2.0 | 813 |
(function() {
var button_name = 'simple_tooltips'; //set button name
tinymce.create('tinymce.plugins.'+button_name, {
init : function(ed, url) {
ed.addButton(button_name, {
title : 'Add a Tooltip', //set button label
image : url+'/icon.png', //set icon filename (20 X 20px). put icon in same folder
onclick : function() {
//idPattern = /(?:(?:[^v]+)+v.)?([^&=]{11})(?=&|$)/;
//var vidId = prompt("YouTube Video", "Enter the id or url for your video");
//var m = idPattern.exec(vidId);
//if (m != null && m != 'undefined')
ed.execCommand('mceInsertContent', false, '[simple_tooltip content=\'This is the content for the tooltip bubble\']This triggers the tooltip[/simple_tooltip]');
}
});
},
createControl : function(n, cm) {
return null;
},
getInfo : function() {
return {
longname : button_name,
author : 'Justin Saad',
authorurl : 'http://clevelandwebdeveloper.com/',
infourl : 'http://clevelandwebdeveloper.com/',
version : "1.0"
};
}
});
tinymce.PluginManager.add(button_name, tinymce.plugins[button_name]);
})(); | lonewolf/rot | wp-content/plugins/simple-tooltips/editor_plugin.js | JavaScript | gpl-2.0 | 1,143 |
jQuery(document).ready(function() {
tinymce.create('tinymce.plugins.yasr_plugin', {
init : function(ed, url) {
// Register command for when button is clicked
ed.addCommand('yasr_insert_shortcode', function() {
jQuery('#yasr-tinypopup-form').dialog({
title: 'Insert YASR shortcode',
width: 530, // overcomes width:'auto' and maxWidth bug
maxWidth: 600,
height: 'auto',
modal: true,
fluid: true, //new option
resizable: false
});
});
// Register buttons - trigger above command when clicked
ed.addButton('yasr_button', {title : 'Yasr Shortcode', cmd : 'yasr_insert_shortcode', image: url + '/../img/star_tiny.png' });
},
});
// Register our TinyMCE plugin
// first parameter is the button ID1
// second parameter must match the first parameter of the tinymce.create() function above
tinymce.PluginManager.add('yasr_button', tinymce.plugins.yasr_plugin);
// executes this when the DOM is ready
jQuery(document).ready(function(){
var data = {
action: 'yasr_create_shortcode'
}
jQuery.post(ajaxurl, data, function(button_content) {
// creates a table to be displayed everytime the button is clicked
var response=button_content;
jQuery(response).appendTo('body').hide();
});
});
}); | ProyectosUNED/ProifedBlog | wp-content/plugins/yet-another-stars-rating/js/addButton_tinymcs.js | JavaScript | gpl-2.0 | 1,639 |
'user strict';
module.exports = {
Server : require('./server')
}; | vincent-tr/mylife-home-studio | lib/web/index.js | JavaScript | gpl-3.0 | 68 |
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.edgehovers');
/**
* This hover renderer will display the edge with a different color or size.
* It will also display the label with a background.
*
* @param {object} edge The edge object.
* @param {object} source node The edge source node.
* @param {object} target node The edge target node.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.edgehovers.curvedArrow =
function(edge, source, target, context, settings) {
var color = edge.active ?
edge.active_color || settings('defaultEdgeActiveColor') :
edge.color,
prefix = settings('prefix') || '',
edgeColor = settings('edgeColor'),
defaultNodeColor = settings('defaultNodeColor'),
defaultEdgeColor = settings('defaultEdgeColor'),
level = settings('edgeHoverLevel'),
cp = {},
size = settings('edgeHoverSizeRatio') * (edge[prefix + 'size'] || 1),
tSize = target[prefix + 'size'],
sX = source[prefix + 'x'],
sY = source[prefix + 'y'],
tX = target[prefix + 'x'],
tY = target[prefix + 'y'],
d,
aSize,
aX,
aY,
vX,
vY;
cp = (source.id === target.id) ?
sigma.utils.getSelfLoopControlPoints(sX, sY, tSize) :
sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY);
if (source.id === target.id) {
d = Math.sqrt(Math.pow(tX - cp.x1, 2) + Math.pow(tY - cp.y1, 2));
aSize = size * 2.5;
aX = cp.x1 + (tX - cp.x1) * (d - aSize - tSize) / d;
aY = cp.y1 + (tY - cp.y1) * (d - aSize - tSize) / d;
vX = (tX - cp.x1) * aSize / d;
vY = (tY - cp.y1) * aSize / d;
}
else {
d = Math.sqrt(Math.pow(tX - cp.x, 2) + Math.pow(tY - cp.y, 2));
aSize = size * 2.5;
aX = cp.x + (tX - cp.x) * (d - aSize - tSize) / d;
aY = cp.y + (tY - cp.y) * (d - aSize - tSize) / d;
vX = (tX - cp.x) * aSize / d;
vY = (tY - cp.y) * aSize / d;
}
// Level:
if (level) {
context.shadowOffsetX = 0;
// inspired by Material Design shadows, level from 1 to 5:
switch(level) {
case 1:
context.shadowOffsetY = 1.5;
context.shadowBlur = 4;
context.shadowColor = 'rgba(0,0,0,0.36)';
break;
case 2:
context.shadowOffsetY = 3;
context.shadowBlur = 12;
context.shadowColor = 'rgba(0,0,0,0.39)';
break;
case 3:
context.shadowOffsetY = 6;
context.shadowBlur = 12;
context.shadowColor = 'rgba(0,0,0,0.42)';
break;
case 4:
context.shadowOffsetY = 10;
context.shadowBlur = 20;
context.shadowColor = 'rgba(0,0,0,0.47)';
break;
case 5:
context.shadowOffsetY = 15;
context.shadowBlur = 24;
context.shadowColor = 'rgba(0,0,0,0.52)';
break;
}
}
if (!color)
switch (edgeColor) {
case 'source':
color = source.color || defaultNodeColor;
break;
case 'target':
color = target.color || defaultNodeColor;
break;
default:
color = defaultEdgeColor;
break;
}
if (settings('edgeHoverColor') === 'edge') {
color = edge.hover_color || color;
} else {
color = edge.hover_color || settings('defaultEdgeHoverColor') || color;
}
context.strokeStyle = color;
context.lineWidth = size;
context.beginPath();
context.moveTo(sX, sY);
if (source.id === target.id) {
context.bezierCurveTo(cp.x2, cp.y2, cp.x1, cp.y1, aX, aY);
} else {
context.quadraticCurveTo(cp.x, cp.y, aX, aY);
}
context.stroke();
context.fillStyle = color;
context.beginPath();
context.moveTo(aX + vX, aY + vY);
context.lineTo(aX + vY * 0.6, aY - vX * 0.6);
context.lineTo(aX - vY * 0.6, aY + vX * 0.6);
context.lineTo(aX + vX, aY + vY);
context.closePath();
context.fill();
// reset shadow
if (level) {
context.shadowOffsetY = 0;
context.shadowBlur = 0;
context.shadowColor = '#000000'
}
// draw label with a background
if (sigma.canvas.edges.labels.curvedArrow) {
edge.hover = true;
sigma.canvas.edges.labels.curvedArrow(edge, source, target, context, settings);
edge.hover = false;
}
};
})();
| mv15/graph-visualization | src/plugins/sigma.renderers.linkurious/canvas/sigma.canvas.edgehovers.curvedArrow.js | JavaScript | gpl-3.0 | 4,619 |
var gri__interleaved__short__to__complex_8h =
[
[ "gri_interleaved_short_to_complex", "gri__interleaved__short__to__complex_8h.html#af1c7c784fed964841bd252bb8575fb61", null ]
]; | aviralchandra/Sandhi | build/gr36/docs/doxygen/html/gri__interleaved__short__to__complex_8h.js | JavaScript | gpl-3.0 | 181 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'codemirror', 'ms', {
toolbar: 'Sumber'
});
| zilgrg/opencart | upload/admin/view/journal2/lib/ckeditor/plugins/codemirror/lang/ms.js | JavaScript | gpl-3.0 | 216 |
.pragma library
.import QtQuick 2.4 as JSQtQuick
function foo(url)
{
}
| geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/qmllint/data/QTBUG-45916.js | JavaScript | gpl-3.0 | 72 |
/*
Copyright (C) 2014 PencilBlue, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Loads a single article
*/
function Article(){}
//dependencies
var Index = require('./index.js');
//inheritance
util.inherits(Article, Index);
Article.prototype.render = function(cb) {
var self = this;
var custUrl = this.pathVars.customUrl;
//check for object ID as the custom URL
var doRedirect = false;
var where = null;
try {
where = {_id: pb.DAO.getObjectID(custUrl)};
doRedirect = true;
}
catch(e){
if (pb.log.isSilly()) {
pb.log.silly("ArticleController: The custom URL was not an object ID [%s]. Will now search url field. [%s]", custUrl, e.message);
}
}
// fall through to URL key
if (where === null) {
where = {url: custUrl};
}
//attempt to load object
var dao = new pb.DAO();
dao.loadByValues(where, 'article', function(err, article) {
if (util.isError(err) || article == null) {
self.reqHandler.serve404();
return;
}
else if (doRedirect) {
self.redirect(pb.UrlService.urlJoin('/article', article.url), cb);
return;
}
self.req.pencilblue_article = article._id.toString();
this.article = article;
self.setPageName(article.name);
Article.super_.prototype.render.apply(self, [cb]);
});
};
//exports
module.exports = Article;
| bitcot/bitcot | plugins/pencilblue/controllers/article.js | JavaScript | gpl-3.0 | 1,926 |
export default class HelpBlockDirective {
constructor ($parse, $compile) {
this.scope = {}
this.$compile = $compile
this.$parse = $parse
this.restrict = 'E'
this.replace = true
this.require = '^ngModel'
this.showErrors = true
this.controller = () => {
}
this.controllerAs = 'hc'
this.bindToController = {
field: '=',
ngModel: '='
}
}
compile (tElem, tAttrs) {
return this.postLinkFn.bind(this)
}
postLinkFn (scope, elm, attrs, ngModel) {
scope.$watch(() => {
return this.$parse(attrs.field)(scope.$parent)
}, field => {
const options = field[2]
if (options) this.showErrors = options.show_errors === undefined ? true: options.show_errors
ngModel.formValidators = {}
if (options && options.validators) {
options.validators.forEach(validator => {
ngModel.formValidators[validator.constructor.name] = validator
ngModel.$validators[validator.constructor.name] = modelValue => validator.validate(modelValue)
})
}
ngModel.$validate()
this.addErrors(ngModel, elm)
})
scope.$watch(() => {
return ngModel.$modelValue
}, newValue => {
this.addErrors(ngModel, elm)
})
}
addErrors (ngModel, elm) {
elm.html('')
if (this.showErrors) {
Object.keys(ngModel.$error).forEach(validator => {
if (ngModel.formValidators[validator]) {
elm.append(this.buildHelpBlock(ngModel.formValidators[validator].getErrorMessage()))
}
})
}
}
buildHelpBlock (message) {
return `<p class="help-block">${message}</p>`
}
}
| ClaroBot/Distribution | main/core/Resources/modules/form/HelpBlock/HelpBlockDirective.js | JavaScript | gpl-3.0 | 1,660 |
module.exports = {
path: 'analytic',
getComponent(nextState, callback) {
callback(null, require('../../component/options_analytic'));
}
}
| jerrybendy/firekylin | www/static/src/admin/page/options/analytic.js | JavaScript | gpl-3.0 | 148 |
define([],function(){
"use strict";
var utils = {};
utils.makeUntypedArrayCopy = function(array){
var newArray = new Array(array.length);
for (var i = 0, li = array.length; i < li; i++){
if (typeof array[i] === "object" && array[i] != null)
newArray[i] = this.makeUntypedArrayCopy(array[i]);
else
newArray[i] = array[i];
}
return newArray;
}
utils.copy = function(from,to){
for (var i = 0, li = from.length; i < li; i++){
if (typeof from[i] === "object" && from[i] != null){
if (to[i] == null)
to[i] = [];
this.copy(from[i],to[i]);
}
else
to[i] = from[i];
}
}
return utils;
}); | Belthazor2008/googulator | public_html/js/CopyUtils.js | JavaScript | gpl-3.0 | 818 |
require.def('Carousel', function () {
return function Carousel(service) {
this.service = service;
this.someType = 'Carousel';
};
});
require.def('app', ['Carousel'], function () {
});
| tfe/cloud9 | support/ace/support/requirejs/tests/priority/priorityWithDeps/script/req/app.js | JavaScript | gpl-3.0 | 214 |
/* BasicUpdate-spec.js
*
* copyright (c) 2010-2022, Christian Mayer and the CometVisu contributers.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
describe('testing the basic update mixin', function() {
afterEach(function() {
delete cv.Config.configSettings.mappings.test;
});
it('should test the mapping', function () {
cv.Config.addMapping('test', {
'0': 'OFF',
'1': 'ON',
'defaultValue': -1
});
var trigger = new cv.ui.structure.pure.Trigger({
path: 'id_0',
$$type: 'trigger',
value: '0'
});
expect(trigger.applyMapping('0', 'test')).toBe('OFF');
expect(trigger.applyMapping('1', 'test')).toBe('ON');
expect(trigger.applyMapping(0, 'test')).toBe('OFF');
expect(trigger.applyMapping(1, 'test')).toBe('ON');
expect(trigger.applyMapping(null, 'test')).toBe(-1);
});
it('should test the range mapping', function () {
cv.Config.addMapping('test', {
'range': {
'0': [99, 'range1'],
'100': [1000, 'range2']
}
});
var trigger = new cv.ui.structure.pure.Trigger({
path: 'id_0',
$$type: 'trigger',
value: '0'
});
expect(trigger.applyMapping('0', 'test')).toBe('range1');
expect(trigger.applyMapping('50', 'test')).toBe('range1');
expect(trigger.applyMapping(0, 'test')).toBe('range1');
expect(trigger.applyMapping(50, 'test')).toBe('range1');
expect(trigger.applyMapping('100', 'test')).toBe('range2');
expect(trigger.applyMapping('150', 'test')).toBe('range2');
expect(trigger.applyMapping(100, 'test')).toBe('range2');
expect(trigger.applyMapping(150, 'test')).toBe('range2');
expect(trigger.applyMapping(1500, 'test')).toBe(1500);
});
it('should test the NULL and * mapping', function () {
cv.Config.addMapping('test', {
'NULL': 'no value',
'*': 'catch all'
});
var trigger = new cv.ui.structure.pure.Trigger({
path: 'id_0',
$$type: 'trigger',
value: '0'
});
expect(trigger.applyMapping(null, 'test')).toBe('no value');
expect(trigger.applyMapping('0', 'test')).toBe('catch all');
expect(trigger.applyMapping('test', 'test')).toBe('catch all');
expect(trigger.applyMapping(undefined, 'test')).toBe('catch all');
});
it('should test the formula mapping', function () {
cv.Config.addMapping('test', {
'formula': function(val) {
return val + 10;
}
});
var trigger = new cv.ui.structure.pure.Trigger({
path: 'id_0',
$$type: 'trigger',
value: '0'
});
expect(trigger.applyMapping(10, 'test')).toBe(20);
});
});
| ChristianMayer/CometVisu | source/test/karma/ui/structure/common/BasicUpdate-spec.js | JavaScript | gpl-3.0 | 3,303 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
declare var describe: (name: string, func: () => void) => void;
declare var test: (desc: string, func: () => void) => void;
declare var expect: (value: any) => any;
import update, {
createQuickOpenState,
getQuickOpenEnabled,
getQuickOpenQuery,
getQuickOpenType
} from "../quick-open";
import {
setQuickOpenQuery,
openQuickOpen,
closeQuickOpen
} from "../../actions/quick-open";
describe("quickOpen reducer", () => {
test("initial state", () => {
const state = update(undefined, { type: "FAKE" });
expect(getQuickOpenQuery({ quickOpen: state })).toEqual("");
expect(getQuickOpenType({ quickOpen: state })).toEqual("sources");
});
test("opens the quickOpen modal", () => {
const state = update(createQuickOpenState(), openQuickOpen());
expect(getQuickOpenEnabled({ quickOpen: state })).toEqual(true);
});
test("closes the quickOpen modal", () => {
let state = update(createQuickOpenState(), openQuickOpen());
expect(getQuickOpenEnabled({ quickOpen: state })).toEqual(true);
state = update(createQuickOpenState(), closeQuickOpen());
expect(getQuickOpenEnabled({ quickOpen: state })).toEqual(false);
});
test("leaves query alone on open if not provided", () => {
const state = update(createQuickOpenState(), openQuickOpen());
expect(getQuickOpenQuery({ quickOpen: state })).toEqual("");
expect(getQuickOpenType({ quickOpen: state })).toEqual("sources");
});
test("set query on open if provided", () => {
const state = update(createQuickOpenState(), openQuickOpen("@"));
expect(getQuickOpenQuery({ quickOpen: state })).toEqual("@");
expect(getQuickOpenType({ quickOpen: state })).toEqual("functions");
});
test("clear query on close", () => {
const state = update(createQuickOpenState(), closeQuickOpen());
expect(getQuickOpenQuery({ quickOpen: state })).toEqual("");
expect(getQuickOpenType({ quickOpen: state })).toEqual("sources");
});
test("sets the query to the provided string", () => {
const state = update(createQuickOpenState(), setQuickOpenQuery("test"));
expect(getQuickOpenQuery({ quickOpen: state })).toEqual("test");
expect(getQuickOpenType({ quickOpen: state })).toEqual("sources");
});
});
| jbhoosreddy/debugger.html | src/reducers/tests/quick-open.spec.js | JavaScript | mpl-2.0 | 2,452 |
/**
* Mailvelope - secure email with OpenPGP encryption for Webmail
* Copyright (C) 2015 Mailvelope GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation.
*
* 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.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
define(function(require, exports, module) {
var sub = require('./sub.controller');
var uiLog = require('../uiLog');
var pwdCache = require('../pwdCache');
var sync = require('./sync.controller');
function PrivateKeyController(port) {
sub.SubController.call(this, port);
this.keyring = require('../keyring');
this.done = null;
this.keyringId = null;
this.options = null;
this.backupCodePopup = null;
this.host = null;
this.keyBackup = null;
this.pwdControl = null;
this.initialSetup = true;
this.restorePassword = false;
}
PrivateKeyController.prototype = Object.create(sub.SubController.prototype);
PrivateKeyController.prototype.generateKey = function(password, options) {
var that = this;
if (options.keySize !== 2048 && options.keySize !== 4096) {
this.ports.keyGenDialog.postMessage({event: 'show-password'});
this.ports.keyGenCont.postMessage({event: 'generate-done', error: {message: 'Invalid key length', code: 'KEY_LENGTH_INVALID'}});
return;
}
this.ports.keyGenDialog.postMessage({event: 'show-waiting'});
this.keyring.getById(this.keyringId).generateKey({
userIds: options.userIds,
numBits: options.keySize,
passphrase: password
}, function(err, data) {
if (that.prefs.data().security.password_cache) {
pwdCache.set({key: data.key}, password);
}
that.ports.keyGenCont.postMessage({event: 'generate-done', publicKey: data.publicKeyArmored, error: err});
});
};
PrivateKeyController.prototype.createPrivateKeyBackup = function() {
var that = this;
var primaryKey = this.keyring.getById(this.keyringId).getPrimaryKey();
if (!primaryKey) {
throw { message: 'No private key for backup', code: 'NO_PRIVATE_KEY' };
}
this.pwdControl = sub.factory.get('pwdDialog');
primaryKey.reason = 'PWD_DIALOG_REASON_CREATE_BACKUP';
primaryKey.keyringId = this.keyringId;
// get password from cache or ask user
this.pwdControl.unlockKey(primaryKey)
.then(function(primaryKey) {
sync.triggerSync(primaryKey);
that.keyBackup = that.model.createPrivateKeyBackup(primaryKey.key, primaryKey.password);
})
.then(function() {
return sync.getByKeyring(that.keyringId).backup({backup: that.keyBackup.message});
})
.then(function() {
var page = 'recoverySheet';
if (that.host.indexOf('web.de') >= 0) {
page += '.webde.html';
} else if (that.host.indexOf('gmx') >= 0) {
page += '.gmxnet.html';
} else {
page += '.html';
}
var path = 'common/ui/modal/recoverySheet/' + page;
that.mvelo.windows.openPopup(path + '?id=' + that.id, {width: 1024, height: 550, modal: false}, function(window) {
that.backupCodePopup = window;
});
})
.catch(function(err) {
that.ports.keyBackupDialog.postMessage({event: 'error-message', error: err});
});
};
PrivateKeyController.prototype.restorePrivateKeyBackup = function(code) {
//console.log('PrivateKeyController.prototype.restorePrivateKeyBackup()', code);
var that = this;
sync.getByKeyring(that.keyringId).restore()
.then(function(data) {
var backup = that.model.restorePrivateKeyBackup(data.backup, code);
if (backup.error) {
if (backup.error.code === 'WRONG_RESTORE_CODE') {
that.ports.restoreBackupDialog.postMessage({event: 'error-message', error: backup.error});
} else {
that.ports.restoreBackupCont.postMessage({event: 'restore-backup-done', error: backup.error});
}
return;
}
var result = that.keyring.getById(that.keyringId).importKeys([{armored: backup.key.armor(), type: 'private'}]);
for (var i = 0; i < result.length; i++) {
if (result[i].type === 'error') {
that.ports.restoreBackupCont.postMessage({event: 'restore-backup-done', error: result[i].message});
return;
}
}
if (that.restorePassword) {
that.ports.restoreBackupDialog.postMessage({event: 'set-password', password: backup.password});
}
that.ports.restoreBackupCont.postMessage({event: 'restore-backup-done', data: backup.key.toPublic().armor()});
sync.triggerSync({keyringId: that.keyringId, key: backup.key, password: backup.password});
})
.catch(function(err) {
that.ports.restoreBackupDialog.postMessage({event: 'error-message', error: err});
});
};
PrivateKeyController.prototype.getLogoImage = function() {
var attr = this.keyring.getById(this.keyringId).getAttributes();
return (attr && attr.logo_data_url) ? attr.logo_data_url : null;
};
PrivateKeyController.prototype.getBackupCode = function() {
return this.keyBackup.backupCode;
};
PrivateKeyController.prototype.handlePortMessage = function(msg) {
switch (msg.event) {
case 'set-init-data':
var data = msg.data;
this.keyringId = data.keyringId || this.keyringId;
this.restorePassword = data.restorePassword || this.restorePassword;
break;
case 'keygen-user-input':
case 'key-backup-user-input':
uiLog.push(msg.source, msg.type);
break;
case 'open-security-settings':
this.openSecuritySettings();
break;
case 'generate-key':
this.keyringId = msg.keyringId;
this.options = msg.options;
this.ports.keyGenDialog.postMessage({event: 'check-dialog-inputs'});
break;
case 'set-keybackup-window-props':
this.keyringId = msg.keyringId;
this.host = msg.host;
this.initialSetup = msg.initialSetup;
break;
case 'input-check':
if (msg.isValid) {
this.generateKey(msg.pwd, this.options);
} else {
this.ports.keyGenCont.postMessage({event: 'generate-done', error: {message: 'The inputs "password" and "confirm" are not valid', code: 'INPUT_NOT_VALID'}});
}
break;
case 'keygen-dialog-init':
this.ports.keyGenCont.postMessage({event: 'dialog-done'});
break;
case 'keybackup-dialog-init':
this.ports.keyBackupDialog.postMessage({event: 'set-init-data', data: {initialSetup: this.initialSetup}});
this.ports.keyBackupCont.postMessage({event: 'dialog-done'});
break;
case 'restore-backup-dialog-init':
this.ports.restoreBackupCont.postMessage({event: 'dialog-done'});
break;
case 'restore-backup-code':
this.restorePrivateKeyBackup(msg.code);
break;
case 'backup-code-window-init':
this.ports.keyBackupCont.postMessage({event: 'popup-isready'});
break;
case 'get-logo-image':
this.ports.backupCodeWindow.postMessage({event: 'set-logo-image', image: this.getLogoImage()});
break;
case 'get-backup-code':
this.ports.backupCodeWindow.postMessage({event: 'set-backup-code', backupCode: this.getBackupCode()});
break;
case 'create-backup-code-window':
try {
this.createPrivateKeyBackup();
} catch (err) {
this.ports.keyBackupCont.postMessage({event: 'popup-isready', error: err});
}
break;
case 'error-message':
if (msg.sender.indexOf('keyBackupDialog') >= 0) {
this.ports.keyBackupCont.postMessage({event: 'error-message', error: msg.err});
}
break;
default:
console.log('unknown event', msg);
}
};
exports.PrivateKeyController = PrivateKeyController;
});
| mommel/mailvelope | common/lib/controller/privateKey.controller.js | JavaScript | agpl-3.0 | 8,385 |
/* global angular */
(function () {
'use strict';
angular.module('cloudbrain.home')
.controller('HomeCtrl', ['$scope','$http','$interval','$log','apiService', 'API_URL', '$state',
function ($scope , $http , $interval , $log , apiService , dataService, API_URL, $state) {
$scope.model = {
deviceIds: [],
deviceNames: [],
};
$scope.changeColor = function () {
var color_val = 'rgba(255, 255, 255, 0.8)';
$scope.chartPolar.options.chart.backgroundColor = color_val;
$scope.chartBar.options.chart.backgroundColor = color_val;
};
apiService.refreshPhysicalDeviceNames().then(function(response) {
angular.copy(response.data, $scope.model.deviceNames);
console.log('devices loaded:', response);
});
var setChannelSeries = function(data){
var keys = Object.keys(data[0]);
keys.forEach(function(key){
if (key != 'timestamp'){
for (var a=[],i=0;i<500;++i) a[i]=0;
$scope.chartStock.series.push({name: key, data: a, id: key});
}
});
};
// FIXME: considering only the first point right now...
function updatePowerBandGraph(graphName, data) {
if (data.length) {
$scope[graphName].series[0].data.length = 0;
$scope[graphName].series[0].data.push(data[0].gamma);
$scope[graphName].series[0].data.push(data[0].delta);
$scope[graphName].series[0].data.push(data[0].theta);
$scope[graphName].series[0].data.push(data[0].beta);
$scope[graphName].series[0].data.push(data[0].alfa);
}
}
//$scope.url = 'http://mock.cloudbrain.rocks/data?device_name=openbci&metric=eeg&device_id=marion&callback=JSON_CALLBACK';
$scope.showClick = false;
$scope.chartMuse = false;
$scope.selectedDevice = '';
$scope.getData = function (device, url) {
$state.go('rtchart', {device:$scope.selectedDevice});
}
}
]);
})();
| octopicorn/cloudbrain | cloudbrain/frontend/home/home.controller.js | JavaScript | agpl-3.0 | 1,930 |
// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on('Blanket Order', {
onload: function(frm) {
frm.trigger('set_tc_name_filter');
},
setup: function(frm) {
frm.add_fetch("customer", "customer_name", "customer_name");
frm.add_fetch("supplier", "supplier_name", "supplier_name");
},
refresh: function(frm) {
erpnext.hide_company();
if (frm.doc.customer && frm.doc.docstatus === 1) {
frm.add_custom_button(__("Sales Order"), function() {
frappe.model.open_mapped_doc({
method: "erpnext.manufacturing.doctype.blanket_order.blanket_order.make_order",
frm: frm,
args: {
doctype: 'Sales Order'
}
});
}, __('Create'));
frm.add_custom_button(__("Quotation"), function() {
frappe.model.open_mapped_doc({
method: "erpnext.manufacturing.doctype.blanket_order.blanket_order.make_order",
frm: frm,
args: {
doctype: 'Quotation'
}
});
}, __('Create'));
}
if (frm.doc.supplier && frm.doc.docstatus === 1) {
frm.add_custom_button(__("Purchase Order"), function(){
frappe.model.open_mapped_doc({
method: "erpnext.manufacturing.doctype.blanket_order.blanket_order.make_order",
frm: frm,
args: {
doctype: 'Purchase Order'
}
});
}, __('Create'));
}
},
onload_post_render: function(frm) {
frm.get_field("items").grid.set_multiple_add("item_code", "qty");
},
tc_name: function (frm) {
erpnext.utils.get_terms(frm.doc.tc_name, frm.doc, function (r) {
if (!r.exc) {
frm.set_value("terms", r.message);
}
});
},
set_tc_name_filter: function(frm) {
if (frm.doc.blanket_order_type === 'Selling') {
frm.set_df_property("customer","reqd", 1);
frm.set_df_property("supplier","reqd", 0);
frm.set_value("supplier", "");
frm.set_query("tc_name", function() {
return { filters: { selling: 1 } };
});
}
if (frm.doc.blanket_order_type === 'Purchasing') {
frm.set_df_property("supplier","reqd", 1);
frm.set_df_property("customer","reqd", 0);
frm.set_value("customer", "");
frm.set_query("tc_name", function() {
return { filters: { buying: 1 } };
});
}
},
blanket_order_type: function (frm) {
frm.trigger('set_tc_name_filter');
}
});
| gsnbng/erpnext | erpnext/manufacturing/doctype/blanket_order/blanket_order.js | JavaScript | agpl-3.0 | 2,307 |
/**
* @file common/js/xe.min.js
* @author NHN (developers@xpressengine.com)
* @brief XE Common JavaScript
**/
(function(a){function b(){return function(){var g=this;a.isArray(this._plugins)&&(this._plugins=[]);this._messages?this._messages={}:this._binded_fn={};a.each(this,function(c,b){if(!a.isFunction(b)||!/^API_([A-Z0-9_]+)$/.test(c))return true;var d=RegExp.$1,e=function(a,b){return g[c](a,b)};g._messages?g._messages[d]=[e]:g._binded_fn[d]=e});a.isFunction(this.init)&&this.init.apply(this,arguments)}}var d,c,e=[];d={_plugins:[],_messages:{},getPlugin:function(g){g=g.toLowerCase();return a.isArray(this._plugins[g])?
this._plugins[g]:[]},registerPlugin:function(g){var c=this,b=g.getName().toLowerCase();if(0<=a.inArray(g,this._plugins))return!1;this._plugins.push(g);a.isArray(this._plugins[b])||(this._plugins[b]=[]);this._plugins[b].push(g);a.each(g._binded_fn,function(a,g){c.registerHandler(a,g)});g.oApp=this;a.isFunction(g.activate)&&g.activate();return!0},registerHandler:function(g,c){var b=this._messages,g=g.toUpperCase();a.isArray(b[g])||(b[g]=[]);b[g].push(c)},cast:function(a,c){return this._cast(this,a,
c||[])},broadcast:function(a,c,b){this.parent&&this.parent._broadcast&&this.parent._broadcast(a,c,b)},_cast:function(c,b,d){var e,m=this._messages,b=b.toUpperCase();if(!m["BEFORE_"+b]&&!this["API_BEFORE_"+b]||this._cast(c,"BEFORE_"+b,d)){var h=[];if(a.isArray(m[b]))for(e=0;e<m[b].length;e++)h.push(m[b][e](c,d));2>h.length&&(h=h[0]);(m["AFTER_"+b]||this["API_AFTER_"+b])&&this._cast(c,"AFTER_"+b,d);return!/^(?:AFTER|BEFORE)_/.test(b)?h:a.isArray(h)?0>a.inArray(!1,h):"undefined"==typeof h?!0:!!h}}};
c={oApp:null,cast:function(a,c){if(this.oApp&&this.oApp._cast)return this.oApp._cast(this,a,c||[])},broadcast:function(a,c){this.oApp&&this.oApp.broadcast&&this.oApp.broadcast(this,mag,c||[])}};window.xe=a.extend(d,{getName:function(){return"Core"},createApp:function(c,e){var i=b();a.extend(i.prototype,d,e);i.prototype.getName=function(){return c};return i},createPlugin:function(g,d){var e=b();a.extend(e.prototype,c,d);e.prototype.getName=function(){return g};return e},getApps:function(){return a.makeArray(e)},
getApp:function(a){a=(a||"").toLowerCase();return"undefined"!=typeof e[a]?e[a]:null},registerApp:function(c){var b=c.getName().toLowerCase();e.push(c);a.isArray(e[b])||(e[b]=[]);e[b].push(c);c.parent=this;a.isFunction(c.activate)&&c.activate()},unregisterApp:function(c){var b=c.getName().toLowerCase(),d=a.inArray(c,e);0<=d&&(e=e.splice(d,1));a.isArray(e[b])&&(d=a.inArray(c,e[b]),0<=d&&(e[b]=e[b].splice(d,1)));a.isFunction(c.deactivate)&&c.deactivate()},broadcast:function(a,c){this._broadcast(this,
a,c)},_broadcast:function(a,c,b){for(var d=0;d<e.length;d++)e[d]._cast(a,c,b);this._cast(a,c,b)}});window.xe.lang={};a(function(){xe.broadcast("ONREADY")});a(window).load(function(){xe.broadcast("ONLOAD")})})(jQuery);jQuery&&jQuery.noConflict();
(function(a){var b=navigator.userAgent.toLowerCase();a.os={Linux:/linux/.test(b),Unix:/x11/.test(b),Mac:/mac/.test(b),Windows:/win/.test(b)};a.os.name=a.os.Windows?"Windows":a.os.Linux?"Linux":a.os.Unix?"Unix":a.os.Mac?"Mac":"";window.XE={loaded_popup_menus:[],addedDocument:[],checkboxToggleAll:function(b){is_def(b)||(b="cart");var c={wrap:null,checked:"toggle",doClick:!1};switch(arguments.length){case 1:"string"==typeof arguments[0]?b=arguments[0]:(a.extend(c,arguments[0]||{}),b="cart");break;case 2:b=
arguments[0],a.extend(c,arguments[1]||{})}!0==c.doClick&&(c.checked=null);"string"==typeof c.wrap&&(c.wrap="#"+c.wrap);var e=c.wrap?a(c.wrap).find("input[name="+b+"]:checkbox"):a("input[name="+b+"]:checkbox");"toggle"==c.checked?e.each(function(){a(this).attr("checked",a(this).attr("checked")?false:true)}):!0==c.doClick?e.click():e.attr("checked",c.checked)},displayPopupMenu:function(b,c,e){var c=e.menu_id,g=b.menus,b="";if(this.loaded_popup_menus[c])b=this.loaded_popup_menus[c];else{if(g){g=g.item;
if("undefined"==typeof g.length||1>g.length)g=Array(g);if(g.length)for(var j=0;j<g.length;j++){var i=g[j].url,l=g[j].str,m=g[j].target,h="";switch(m){case "popup":h=" onclick=\"popopen(this.href,'"+m+"'); return false;\"";break;case "javascript":h=' onclick="'+i+'; return false; "';i="#";break;default:h=' onclick="window.open(this.href); return false;"'}b+='<li ><a href="'+i+'"'+h+">"+l+"</a></li> "}}this.loaded_popup_menus[c]=b}b&&(c=a("#popup_menu_area").html("<ul>"+b+"</ul>"),b=e.page_y,e=e.page_x,
c.outerHeight()+b>a(window).height()+a(window).scrollTop()&&(b=a(window).height()-c.outerHeight()+a(window).scrollTop()),c.outerWidth()+e>a(window).width()+a(window).scrollLeft()&&(e=a(window).width()-c.outerWidth()+a(window).scrollLeft()),c.css({top:b,left:e}).show())}}})(jQuery);
jQuery(function(a){a.browser.msie&&a("select").each(function(a,b){for(var g=!1,d=[],i=0;i<b.options.length;i++)b.options[i].disabled?(b.options[i].style.color="#CCCCCC",g=!0):d[a]=-1<d[a]?d[a]:i;if(g&&(b.oldonchange=b.onchange,b.onchange=function(){this.options[this.selectedIndex].disabled?this.selectedIndex=d[a]:this.oldonchange&&this.oldonchange()},0<=b.selectedIndex&&b.options[b.selectedIndex].disabled))b.onchange()});var b=a(".xe_content .fold_button");if(b.size()){var d=a("div.fold_container",
b);a("button.more",b).click(function(){a(this).hide().next("button").show().parent().next(d).show()});a("button.less",b).click(function(){a(this).hide().prev("button").show().parent().next(d).hide()})}jQuery('input[type="submit"]').click(function(a){var b=jQuery(a.currentTarget);setTimeout(function(){b.attr("disabled","disabled")},0);setTimeout(function(){b.removeAttr("disabled")},3E3)})});
(function(){var a=Array.isArray||function(a){return"[object Array]"==Object.prototype.toString.call(a)};String.prototype.getQuery=function(a){var d=this.replace(/#.*$/,"")===window.location.href.replace(/#.*$/,"")?current_url:this,c=d.indexOf("?");if(-1==c)return null;var e={};d.substr(c+1,this.length).replace(/([^=]+)=([^&]*)(&|$)/g,function(a,b,c){e[b]=c});a=e[a];"undefined"==typeof a&&(a="");return a};String.prototype.setQuery=function(b,d){var c=this.replace(/#.*$/,"")===window.location.href.replace(/#.*$/,
"")?current_url:this,e=c.indexOf("?"),g=c.replace(/#$/,""),j,i;"undefined"==typeof d&&(d="");if(-1!=e){var l=g.substr(e+1,c.length),m={},h=[],g=c.substr(0,e);l.replace(/([^=]+)=([^&]*)(&|$)/g,function(a,b,c){m[b]=c});m[b]=d;for(var n in m)m.hasOwnProperty(n)&&(i=String(m[n]).trim())&&h.push(n+"="+decodeURI(i));l=h.join("&");g+=l?"?"+l:""}else String(d).trim()&&(g=g+"?"+b+"="+d);e=/^https:\/\/([^:\/]+)(:\d+|)/i;e.test(g)&&(c="http://"+RegExp.$1,window.http_port&&80!=http_port&&(c+=":"+http_port),g=
g.replace(e,c));c=!!window.enforce_ssl;if(!c&&a(window.ssl_actions)&&(j=g.getQuery("act"))){e=0;for(i=ssl_actions.length;e<i;e++)if(ssl_actions[e]===j){c=!0;break}}e=/http:\/\/([^:\/]+)(:\d+|)/i;c&&e.test(g)&&(c="https://"+RegExp.$1,window.https_port&&443!=https_port&&(c+=":"+https_port),g=g.replace(e,c));g=g.replace(/\/(index\.php)?\?/,"/index.php?");return encodeURI(g)};String.prototype.trim=function(){return this.replace(/(^\s*)|(\s*$)/g,"")}})();
function xSleep(a){for(var a=a/1E3,b=new Date,d=new Date;d.getTime()-b.getTime()<a;)d=new Date}function isDef(){for(var a=0;a<arguments.length;++a)if("undefined"==typeof arguments[a])return!1;return!0}var winopen_list=[];
function winopen(a,b,d){"undefined"!=typeof xeVid&&(-1<a.indexOf(request_uri)&&!a.getQuery("vid"))&&(a=a.setQuery("vid",xeVid));try{"_blank"!=b&&winopen_list[b]&&(winopen_list[b].close(),winopen_list[b]=null)}catch(c){}"undefined"==typeof b&&(b="_blank");"undefined"==typeof d&&(d="");a=window.open(a,b,d);a.focus();"_blank"!=b&&(winopen_list[b]=a)}
function popopen(a,b){"undefined"==typeof b&&(b="_blank");"undefined"!=typeof xeVid&&(-1<a.indexOf(request_uri)&&!a.getQuery("vid"))&&(a=a.setQuery("vid",xeVid));winopen(a,b,"width=650,height=500,scrollbars=yes,resizable=yes,toolbars=no")}function sendMailTo(a){location.href="mailto:"+a}function move_url(a,b){if(!a)return!1;"undefined"==typeof b&&(b="N");b="N"==b?!1:!0;/^\./.test(a)&&(a=request_uri+a);b?winopen(a):location.href=a;return!1}
function displayMultimedia(a,b,d,c){(a=_displayMultimedia(a,b,d,c))&&document.writeln(a)}
function _displayMultimedia(a,b,d,c){0==a.indexOf("files")&&(a=request_uri+a);var c=jQuery.extend({wmode:"transparent",allowScriptAccess:"sameDomain",quality:"high",flashvars:"",autostart:!1},c||{}),e=c.autostart&&"false"!=c.autostart?"true":"false";delete c.autostart;var g="",g="";if(/\.(gif|jpg|jpeg|bmp|png)$/i.test(a))g='<img src="'+a+'" width="'+b+'" height="'+d+'" />';else if(/\.flv$/i.test(a)||/\.mov$/i.test(a)||/\.moov$/i.test(a)||/\.m4v$/i.test(a))g='<embed src="'+request_uri+'common/img/flvplayer.swf" allowfullscreen="true" autostart="'+
e+'" width="'+b+'" height="'+d+'" flashvars="&file='+a+"&width="+b+"&height="+d+"&autostart="+e+'" wmode="'+c.wmode+'" />';else if(/\.swf/i.test(a)){var g="undefined"!=typeof enforce_ssl&&enforce_ssl?"https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0":"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0",g='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+g+'" width="'+b+'" height="'+d+'" flashvars="'+c.flashvars+
'">',g=g+('<param name="movie" value="'+a+'" />'),j;for(j in c)"undefined"!=c[j]&&""!=c[j]&&(g+='<param name="'+j+'" value="'+c[j]+'" />');g+='<embed src="'+a+'" autostart="'+e+'" width="'+b+'" height="'+d+'" flashvars="'+c.flashvars+'" wmode="'+c.wmode+'"></embed></object>'}else{if(jQuery.browser.mozilla||jQuery.browser.opera)e=c.autostart&&"false"!=c.autostart?"1":"0";g='<embed src="'+a+'" autostart="'+e+'" width="'+b+'" height="'+d+'"';"transparent"==c.wmode&&(g+=' windowlessvideo="1"');g+="></embed>"}return g}
function zbxe_folder_open(a){jQuery("#folder_open_"+a).hide();jQuery("#folder_close_"+a).show();jQuery("#folder_"+a).show()}function zbxe_folder_close(a){jQuery("#folder_open_"+a).show();jQuery("#folder_close_"+a).hide();jQuery("#folder_"+a).hide()}
function setFixedPopupSize(){var a=jQuery,b=a(window),a=a("body>.popup"),d,c,e,g;g=a.css({overflow:"scroll"}).offset();d=a.width(10).height(1E4).get(0).scrollWidth+2*g.left;c=a.height(10).width(1E4).get(0).scrollHeight+2*g.top;600>d&&(d=600+2*g.left);e=b.width();b=b.height();d!=e&&window.resizeBy(d-e,0);c!=b&&window.resizeBy(0,c-b);a.width(d-2*g.left).css({overflow:"",height:""})}
function doCallModuleAction(a,b,d){exec_xml(a,b,{target_srl:d,cur_mid:current_mid,mid:current_mid},completeCallModuleAction)}function completeCallModuleAction(a){"success"!=a.message&&alert(a.message);location.reload()}function completeMessage(a){alert(a.message);location.reload()}function doChangeLangType(a){"string"==typeof a?setLangType(a):setLangType(a.options[a.selectedIndex].value);location.href=location.href.setQuery("l","")}
function setLangType(a){var b=new Date;b.setTime(b.getTime()+6048E8);setCookie("lang_type",a,b,"/")}
function doDocumentPreview(a){for(;"FORM"!=a.nodeName;)a=a.parentNode;if("FORM"==a.nodeName){a=a.getAttribute("editor_sequence");a=editorGetContent(a);window.open("","previewDocument","toolbars=no,width=700px;height=800px,scrollbars=yes,resizable=yes");var b=jQuery("#previewDocument");b.length?b=b[0]:(jQuery('<form id="previewDocument" target="previewDocument" method="post" action="'+request_uri+'"><input type="hidden" name="module" value="document" /><input type="hidden" name="act" value="dispDocumentPreview" /><input type="hidden" name="content" /></form>').appendTo(document.body),b=
jQuery("#previewDocument")[0]);b&&(b.content.value=a,b.submit())}}
function doDocumentSave(a){var b=a.form.getAttribute("editor_sequence"),d=editorRelKeys[b].content.value;if("undefined"!=typeof b&&b&&"undefined"!=typeof editorRelKeys&&"function"==typeof editorGetContent){var c=editorGetContent(b);editorRelKeys[b].content.value=c}var e={},c=jQuery(a.form).serializeArray();jQuery.each(c,function(a,b){var c=jQuery.trim(b.value);if(!c)return!0;/\[\]$/.test(b.name)&&(b.name=b.name.replace(/\[\]$/,""));e[b.name]=e[b.name]?e[b.name]+("|@|"+c):b.value});exec_xml("document",
"procDocumentTempSave",e,completeDocumentSave,["error","message","document_srl"],e,a.form);editorRelKeys[b].content.value=d;return!1}function completeDocumentSave(a){jQuery("input[name=document_srl]").eq(0).val(a.document_srl);alert(a.message)}var objForSavedDoc=null;function doDocumentLoad(a){objForSavedDoc=a.form;popopen(request_uri.setQuery("module","document").setQuery("act","dispTempSavedList"))}
function doDocumentSelect(a){opener&&opener.objForSavedDoc&&(opener.location.href=opener.current_url.setQuery("document_srl",a).setQuery("act","dispBoardWrite"));window.close()}function viewSkinInfo(a,b){popopen("./?module=module&act=dispModuleSkinInfo&selected_module="+a+"&skin="+b,"SkinInfo")}var addedDocument=[];function doAddDocumentCart(a){addedDocument[addedDocument.length]=a.value;setTimeout(function(){callAddDocumentCart(addedDocument.length)},100)}
function callAddDocumentCart(a){1>addedDocument.length||a!=addedDocument.length||(a=[],a.srls=addedDocument.join(","),exec_xml("document","procDocumentAddCart",a,null),addedDocument=[])}
function transRGB2Hex(a){if(!a)return a;if(-1<a.indexOf("#"))return a.replace(/^#/,"");if(0>a.toLowerCase().indexOf("rgb"))return a;a=a.replace(/^rgb\(/i,"").replace(/\)$/,"");value_list=a.split(",");for(var a="",b=0;b<value_list.length;b++){var d=parseInt(value_list[b],10).toString(16);1==d.length&&(d="0"+d);a+=d}return a}function toggleSecuritySignIn(){var a=location.href;location.href=/https:\/\//i.test(a)?a.replace(/^https/i,"http"):a.replace(/^http/i,"https")}
function reloadDocument(){location.reload()}
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(a){for(var b="",d,c,e,g,j,i,l=0,a=Base64._utf8_encode(a);l<a.length;)d=a.charCodeAt(l++),c=a.charCodeAt(l++),e=a.charCodeAt(l++),g=d>>2,d=(d&3)<<4|c>>4,j=(c&15)<<2|e>>6,i=e&63,isNaN(c)?j=i=64:isNaN(e)&&(i=64),b=b+this._keyStr.charAt(g)+this._keyStr.charAt(d)+this._keyStr.charAt(j)+this._keyStr.charAt(i);return b},decode:function(a){for(var b="",d,c,e,g,j,i=0,a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");i<
a.length;)d=this._keyStr.indexOf(a.charAt(i++)),c=this._keyStr.indexOf(a.charAt(i++)),g=this._keyStr.indexOf(a.charAt(i++)),j=this._keyStr.indexOf(a.charAt(i++)),d=d<<2|c>>4,c=(c&15)<<4|g>>2,e=(g&3)<<6|j,b+=String.fromCharCode(d),64!=g&&(b+=String.fromCharCode(c)),64!=j&&(b+=String.fromCharCode(e));return b=Base64._utf8_decode(b)},_utf8_encode:function(a){for(var a=a.replace(/\r\n/g,"\n"),b="",d=0;d<a.length;d++){var c=a.charCodeAt(d);128>c?b+=String.fromCharCode(c):(127<c&&2048>c?b+=String.fromCharCode(c>>
6|192):(b+=String.fromCharCode(c>>12|224),b+=String.fromCharCode(c>>6&63|128)),b+=String.fromCharCode(c&63|128))}return b},_utf8_decode:function(a){for(var b="",d=0,c=c1=c2=0;d<a.length;)c=a.charCodeAt(d),128>c?(b+=String.fromCharCode(c),d++):191<c&&224>c?(c2=a.charCodeAt(d+1),b+=String.fromCharCode((c&31)<<6|c2&63),d+=2):(c2=a.charCodeAt(d+1),c3=a.charCodeAt(d+2),b+=String.fromCharCode((c&15)<<12|(c2&63)<<6|c3&63),d+=3);return b}};
if("undefined"==typeof resizeImageContents)var resizeImageContents=function(){};if("undefined"==typeof activateOptionDisabled)var activateOptionDisabled=function(){};objectExtend=jQuery.extend;function toggleDisplay(a){jQuery("#"+a).toggle()}function checkboxSelectAll(a,b,d){var c={};"undefined"!=typeof a&&(c.wrap=a);"undefined"!=typeof d&&(c.checked=d);XE.checkboxToggleAll(b,c)}function clickCheckBoxAll(a,b){var d={doClick:!0};"undefined"!=typeof a&&(d.wrap=a);XE.checkboxToggleAll(b,d)}
function svc_folder_open(a){jQuery("#_folder_open_"+a).hide();jQuery("#_folder_close_"+a).show();jQuery("#_folder_"+a).show()}function svc_folder_close(a){jQuery("#_folder_open_"+a).show();jQuery("#_folder_close_"+a).hide();jQuery("#_folder_"+a).hide()}function open_calendar(a,b,d){"undefined"==typeof b&&(b="");var c="./common/tpl/calendar.php?";a&&(c+="fo_id="+a);b&&(c+="&day_str="+b);d&&(c+="&callback_func="+d);popopen(c,"Calendar")}var loaded_popup_menus=XE.loaded_popup_menus;
function createPopupMenu(){}function chkPopupMenu(){}function displayPopupMenu(a,b,d){XE.displayPopupMenu(a,b,d)}function GetObjLeft(a){return jQuery(a).offset().left}function GetObjTop(a){return jQuery(a).offset().top}function replaceOuterHTML(a,b){jQuery(a).replaceWith(b)}function getOuterHTML(a){return jQuery(a).html().trim()}function setCookie(a,b,d,c){a=a+"="+escape(b)+(!d?"":"; expires="+d.toGMTString())+"; path="+(!c?"/":c);document.cookie=a}
function getCookie(a){if(a=document.cookie.match(RegExp(a+"=(.*?)(?:;|$)")))return unescape(a[1])}function is_def(a){return"undefined"!=typeof a}function ucfirst(a){return a.charAt(0).toUpperCase()+a.slice(1)}function get_by_id(a){return document.getElementById(a)}
jQuery(function(a){a(".lang_code").each(function(){var b=a(this),d=b.attr("id");"undefined"==typeof d&&(d=b.attr("name"));"undefined"!=typeof d&&b.after("<a href='"+request_uri.setQuery("module","module").setQuery("act","dispModuleAdminLangcode").setQuery("target",d)+"' class='buttonSet buttonSetting' onclick='popopen(this.href);return false;'><span>find_langcode</span></a>")});a(document).click(function(b){var d=a("#popup_menu_area");d.length||(d=a('<div id="popup_menu_area" style="display:none;z-index:9999" />').appendTo(document.body));
d.hide();d=a(b.target).filter("a,div,span");d.length||(d=a(b.target).closest("a,div,span"));if(d.length){var d=d.attr("class"),c;d&&(c=d.match(/(?:^| )((document|comment|member)_([1-9]\d*))(?: |$)/));if(c){d="get"+ucfirst(c[2])+"Menu";c={mid:current_mid,cur_mid:current_mid,menu_id:c[1],target_srl:c[3],cur_act:current_url.getQuery("act"),page_x:b.pageX,page_y:b.pageY};var e=["error","message","menus"];b.preventDefault();b.stopPropagation();is_def(window.xeVid)&&(c.vid=xeVid);if(is_def(XE.loaded_popup_menus[c.menu_id]))return XE.displayPopupMenu(c,
e,c);show_waiting_message=!1;exec_xml("member",d,c,XE.displayPopupMenu,e,c);show_waiting_message=!0}}});a("a._xe_popup").click(function(){var b=a(this),d=b.attr("name"),b=b.attr("href");d||(d="_xe_popup_"+Math.floor(1E3*Math.random()));(d=window.open(b,d,"left=10,top=10,width=10,height=10,resizable=no,scrollbars=no,toolbars=no"))&&d.focus();return!1});a.datepicker&&a.datepicker.setDefaults({dateFormat:"yy-mm-dd"})});var show_waiting_message=!0;
function xml2json(a,b,d){var c={toObj:function(a){var b={};if(1==a.nodeType){if(d&&a.attributes.length)for(var e=0;e<a.attributes.length;e++)b["@"+a.attributes[e].nodeName]=(a.attributes[e].nodeValue||"").toString();if(a.firstChild){for(var l=e=0,m=!1,h=a.firstChild;h;h=h.nextSibling)1==h.nodeType?m=!0:3==h.nodeType&&h.nodeValue.match(/[^ \f\n\r\t\v]/)?e++:4==h.nodeType&&l++;if(m)if(2>e&&2>l){c.removeWhite(a);for(h=a.firstChild;h;h=h.nextSibling)3==h.nodeType?b=c.escape(h.nodeValue):4==h.nodeType?
b=c.escape(h.nodeValue):b[h.nodeName]?b[h.nodeName]instanceof Array?b[h.nodeName][b[h.nodeName].length]=c.toObj(h):b[h.nodeName]=[b[h.nodeName],c.toObj(h)]:b[h.nodeName]=c.toObj(h)}else a.attributes.length?b["#text"]=c.escape(c.innerXml(a)):b=c.escape(c.innerXml(a));else if(e)a.attributes.length?b["#text"]=c.escape(c.innerXml(a)):b=c.escape(c.innerXml(a));else if(l)if(1<l)b=c.escape(c.innerXml(a));else for(h=a.firstChild;h;h=h.nextSibling)b=c.escape(h.nodeValue)}!a.attributes.length&&!a.firstChild&&
(b=null)}else 9==a.nodeType?b=c.toObj(a.documentElement):alert("unhandled node type: "+a.nodeType);return b},toJson:function(a,b,d){var e=b?'"'+b+'"':"";if(a instanceof Array){for(var m=0,h=a.length;m<h;m++)a[m]=c.toJson(a[m],"",d+"\t");e+=(b?":[":"[")+(1<a.length?"\n"+d+"\t"+a.join(",\n"+d+"\t")+"\n"+d:a.join(""))+"]"}else if(null==a)e+=(b&&":")+"null";else if("object"==typeof a){m=[];for(h in a)m[m.length]=c.toJson(a[h],h,d+"\t");e+=(b?":{":"{")+(1<m.length?"\n"+d+"\t"+m.join(",\n"+d+"\t")+"\n"+
d:m.join(""))+"}"}else e="string"==typeof a?e+((b&&":")+'"'+a.toString()+'"'):e+((b&&":")+a.toString());return e},innerXml:function(a){var b="";if("innerHTML"in a)b=a.innerHTML;else for(var c=function(a){var b="";if(1==a.nodeType){for(var b=b+("<"+a.nodeName),d=0;d<a.attributes.length;d++)b+=" "+a.attributes[d].nodeName+'="'+(a.attributes[d].nodeValue||"").toString()+'"';if(a.firstChild){b+=">";for(d=a.firstChild;d;d=d.nextSibling)b+=c(d);b+="</"+a.nodeName+">"}else b+="/>"}else 3==a.nodeType?b+=
a.nodeValue:4==a.nodeType&&(b+="<![CDATA["+a.nodeValue+"]]\>");return b},a=a.firstChild;a;a=a.nextSibling)b+=c(a);return b},escape:function(a){return a.replace(/[\\]/g,"\\\\").replace(/[\"]/g,'\\"').replace(/[\n]/g,"\\n").replace(/[\r]/g,"\\r")},removeWhite:function(a){a.normalize();for(var b=a.firstChild;b;)if(3==b.nodeType)if(b.nodeValue.match(/[^ \f\n\r\t\v]/))b=b.nextSibling;else{var d=b.nextSibling;a.removeChild(b);b=d}else 1==b.nodeType&&c.removeWhite(b),b=b.nextSibling;return a}};9==a.nodeType&&
(a=a.documentElement);var e=c.toObj(c.removeWhite(a));"object"==typeof JSON&&jQuery.isFunction(JSON.stringify);a=c.toJson(e,a.nodeName,"");return"{"+(b?a.replace(/\t/g,b):a.replace(/\t|\n/g,""))+"}"}
(function(a){function b(){return""}a.exec_xml=window.exec_xml=function(b,c,e,g,j,i,l){function m(e){var e=a(e).find("response")[0],h,m="",n=[],k={};h="";s.css("display","none").trigger("cancel_confirm");if(!e)return alert(v.responseText),null;h=xml2json(e,!1,!1);h="object"==typeof JSON&&a.isFunction(JSON.parse)?JSON.parse(h):eval("("+h+")");h=h.response;if("undefined"==typeof h){n.error=-1;n.message="Unexpected error occured.";try{if("undefined"!=typeof(m=e.childNodes[0].firstChild.data))n.message+=
"\r\n"+m}catch(o){}return n}a.each(j,function(a,b){k[b]=!0});k.redirect_url=!0;k.act=!0;a.each(h,function(a,b){k[a]&&(n[a]=b)});if(0!=n.error){if(a.isFunction(a.exec_xml.onerror))return a.exec_xml.onerror(b,c,n,g,j,i,l);alert((n.message||"An unknown error occured while loading ["+b+"."+c+"]").replace(/\\n/g,"\n"));return null}if(n.redirect_url)return location.href=n.redirect_url.replace(/&/g,"&"),null;a.isFunction(g)&&g(n,j,i,l)}var h=request_uri+"index.php";e||(e={});if(a.isArray(e)){var n={},
k;for(k in e)e.hasOwnProperty(k)&&(n[k]=e[k]);e=n}e.module=b;e.act=c;"undefined"!=typeof xeVid&&(e.vid=xeVid);"undefined"==typeof j||1>j.length?j=["error","message"]:j.push("error","message");a.isArray(ssl_actions)&&(e.act&&0<=a.inArray(e.act,ssl_actions))&&(k=default_url||request_uri,h=window.https_port||443,k=a("<a>").attr("href",k)[0],n="https://"+k.hostname.replace(/:\d+$/,""),443!=h&&(n+=":"+h),"/"!=k.pathname[0]&&(n+="/"),n+=k.pathname,h=n.replace(/\/$/,"")+"/index.php");k=a("<a>").attr("href",
location.href)[0];n=a("<a>").attr("href",h)[0];if(k.protocol!=n.protocol||k.port!=n.port){a("#xeTmpIframe").length||a('<iframe name="%id%" id="%id%" style="position:absolute;left:-1px;top:1px;width:1px;height:1px"></iframe>'.replace(/%id%/g,"xeTmpIframe")).appendTo(document.body);a("#xeVirtualForm").remove();var z=a('<form id="%id%"></form>'.replace(/%id%/g,"xeVirtualForm")).attr({id:"xeVirtualForm",method:"post",action:h,target:"xeTmpIframe"});e.xeVirtualRequestMethod="xml";e.xeRequestURI=location.href.replace(/#(.*)$/i,
"");e.xeVirtualRequestUrl=request_uri;a.each(e,function(b,c){a('<input type="hidden">').attr("name",b).attr("value",c).appendTo(z)});z.appendTo(document.body).submit()}else{var w=[],o=0;w[o++]='<?xml version="1.0" encoding="utf-8" ?>';w[o++]="<methodCall>";w[o++]="<params>";a.each(e,function(a,b){w[o++]="<"+a+"><![CDATA["+b+"]]\></"+a+">"});w[o++]="</params>";w[o++]="</methodCall>";var v=null;v&&0!=v.readyState&&v.abort();try{a.ajax({url:h,type:"POST",dataType:"xml",data:w.join("\n"),contentType:"text/plain",
beforeSend:function(a){v=a},success:m,error:function(a,b){s.css("display","none");var c="";if(b=="parsererror"){if(a.responseText=="")return;c="The result is not valid XML :\n-------------------------------------\n"+a.responseText.replace(/<[^>]+>/g,"")}else c=b;try{console.log(c)}catch(d){}}})}catch(t){alert(t);return}var s=a(".wfsr");show_waiting_message&&s.length&&s.html(waiting_message).show()}};a.exec_json=function(b,c,e){"undefined"==typeof c&&(c={});b=b.split(".");2==b.length&&(show_waiting_message&&
a(".wfsr").html(waiting_message).show(),a.extend(c,{module:b[0],act:b[1]}),"undefined"!=typeof xeVid&&a.extend(c,{vid:xeVid}),a.ajax({type:"POST",dataType:"json",url:request_uri,contentType:"application/json",data:a.param(c),success:function(b){a(".wfsr").hide().trigger("cancel_confirm");0<b.error&&alert(b.message);a.isFunction(e)&&e(b)}}))};a.fn.exec_html=function(b,c,e,g,j){"undefined"==typeof c&&(c={});a.inArray(e,["html","append","prepend"])||(e="html");var i=a(this),b=b.split(".");2==b.length&&
(show_waiting_message&&a(".wfsr").html(waiting_message).show(),a.extend(c,{module:b[0],act:b[1]}),a.ajax({type:"POST",dataType:"html",url:request_uri,data:a.param(c),success:function(b){a(".wfsr").hide().trigger("cancel_confirm");i[e](b);a.isFunction(g)&&g(j)}}))};a(function(a){a(".wfsr").ajaxStart(function(){a(window).bind("beforeunload",b)}).bind("ajaxStop cancel_confirm",function(){a(window).unbind("beforeunload",b)})})})(jQuery);
(function(a){function b(a){var b=[];return a.is(":radio")?a.filter(":checked").val():a.is(":checkbox")?(a.filter(":checked").each(function(){b.push(this.value)}),b.join("|@|")):a.val()}var d=[],c=[],e={},g=[],j={},i=new (xe.createApp("Validator",{init:function(){var a=/^[\w-]+((?:\.|\+|\~)[\w-]+)*@[\w-]+(\.[\w-]+)+$/;this.cast("ADD_RULE",["email",a]);this.cast("ADD_RULE",["email_address",a]);a=/^[a-z]+[\w-]*[a-z0-9_]+$/i;this.cast("ADD_RULE",["userid",a]);this.cast("ADD_RULE",["user_id",a]);a=/^(https?|ftp|mms):\/\/[0-9a-z-]+(\.[_0-9a-z-]+)+(:\d+)?/;
this.cast("ADD_RULE",["url",a]);this.cast("ADD_RULE",["homepage",a]);this.cast("ADD_RULE",["korean",RegExp("^[\uac00-\ud7a3]*$")]);this.cast("ADD_RULE",["korean_number",RegExp("^[\uac00-\ud7a30-9]*$")]);this.cast("ADD_RULE",["alpha",/^[a-z]*$/i]);this.cast("ADD_RULE",["alpha_number",/^[a-z][a-z0-9_]*$/i]);this.cast("ADD_RULE",["number",/^[0-9]*$/])},run:function(a){var b="";a._filter&&(b=a._filter.value);a=this.cast("VALIDATE",[a,b]);"undefined"==typeof a&&(a=!1);return a},API_ONREADY:function(){var b=
this;a("form").each(function(){this.onsubmit&&(this["xe:onsubmit"]=this.onsubmit,this.onsubmit=null)}).submit(function(c){var d=this["xe:onsubmit"];(d=a.isFunction(d)?d.apply(this):b.run(this))||c.stopImmediatePropagation();return d})},API_VALIDATE:function(c,d){function n(a){return a.replace(/([\.\+\-\[\]\{\}\(\)\\])/g,"\\$1")}var k=!0,i=d[0],l=i.elements,o,v,t,s,q,p,u,r,x,y;l.ruleset?o=i.elements.ruleset.value:l._filter&&(o=i.elements._filter.value);if(!o)return!0;a.isFunction(g[o])&&(t=g[o]);o=
a.extend({},e[o.toLowerCase()]||{},j);s=[];p=0;for(r=i.elements.length;p<r;p++)k=l[p],(q=k.name)&&l[q]&&(!l[q].length||l[q][0]===k)&&s.push(q);s=s.join("\n");v={};for(q in o)if(o.hasOwnProperty(q)&&(k=[],"^"==q.substr(0,1))){(k=s.match(RegExp("^"+n(q.substr(1))+".*$","gm")))||(k=[]);p=0;for(r=k.length;p<r;p++)v[k[p]]=o[q];o[q]=null;delete o[q]}o=a.extend(o,v);for(q in o)if(o.hasOwnProperty(q)&&(f=o[q],(k=l[q])||(k=l[q+"[]"]),s=k?a.trim(b(a(k))):"",v=(f.modifier||"")+",",k&&!k.disabled)){if(f["if"]){a.isArray(f["if"])||
(f["if"]=[f["if"]]);for(p=0;p<f["if"].length;p++)r=f["if"][p],k=new Function("el","return !!("+r.test.replace(/\$(\w+)/g,"(jQuery('[name=$1]').is(':radio, :checkbox') ? jQuery('[name=$1]:checked').val() : jQuery('[name=$1]').val())")+")"),k(l)?f[r.attr]=r.value:delete f[r.attr]}if(s){k=parseInt(f.minlength)||0;r=parseInt(f.maxlength)||0;y=/b$/.test(f.minlength||"");x=/b$/.test(f.maxlength||"");p=s.length;if(y||x)if(u=s,u+="",u.length){u=encodeURI(u);var A=u.split("%").length-1;u=u.length-2*A}else u=
0;if(k&&k>(y?u:p)||r&&r<(x?u:p))return this.cast("ALERT",[i,q,"outofrange",k,r])&&!1;if(f.equalto&&(r=(p=l[f.equalto])?a.trim(b(a(p))):"",p&&r!==s))return this.cast("ALERT",[i,q,"equalto"])&&!1;x=(f.rule||"").split(",");p=0;for(r=x.length;p<r;p++)if(y=x[p])if(k=this.cast("APPLY_RULE",[y,s]),-1<v.indexOf("not,")&&(k=!k),!k)return this.cast("ALERT",[i,q,"invalid_"+y])&&!1}else if(f["default"]&&(s=f["default"]),f.required)return this.cast("ALERT",[i,q,"isnull"])&&!1}return a.isFunction(t)?t(i):!0},API_ADD_RULE:function(a,
b){var d=b[0].toLowerCase();c[d]=b[1]},API_DEL_RULE:function(a,b){var d=b[0].toLowerCase();delete c[d]},API_GET_RULE:function(a,b){var d=b[0].toLowerCase();return c[d]?c[d]:null},API_ADD_FILTER:function(a,b){var c=b[0].toLowerCase();e[c]=b[1]},API_DEL_FILTER:function(a,b){var c=b[0].toLowerCase();delete e[c]},API_GET_FILTER:function(a,b){var c=b[0].toLowerCase();return e[c]?e[c]:null},API_ADD_EXTRA_FIELD:function(a,b){var c=b[0].toLowerCase();j[c]=b[1]},API_GET_EXTRA_FIELD:function(a,b){var c=b[0].toLowerCase();
return j[c]},API_DEL_EXTRA_FIELD:function(a,b){var c=b[0].toLowerCase();delete j[c]},API_APPLY_RULE:function(b,d){var e=d[0],g=d[1];return"undefined"==typeof c[e]?!0:a.isFunction(c[e])?c[e](g):c[e]instanceof RegExp?c[e].test(g):a.isArray(c[e])?-1<a.inArray(g,c[e]):!0},API_ALERT:function(b,c){var d=c[0],e=c[1],g=c[2],i=c[3],j=c[4],l=this.cast("GET_MESSAGE",[e]),t=this.cast("GET_MESSAGE",[g]);t!=g&&(t=0>t.indexOf("%s")?l+t:t.replace("%s",l));if(i||j)t+="("+(i||"")+"~"+(j||"")+")";this.cast("SHOW_ALERT",
[t]);a(d.elements[e]).focus()},API_SHOW_ALERT:function(a,b){alert(b[0])},API_ADD_MESSAGE:function(a,b){d[b[0]]=b[1]},API_GET_MESSAGE:function(a,b){var c=b[0];return d[c]||c},API_ADD_CALLBACK:function(a,b){g[b[0]]=b[1]},API_REMOVE_CALLBACK:function(a,b){delete g[b[0]]}}));xe.registerApp(i);var l=xe.createPlugin("editor_stub",{API_BEFORE_VALIDATE:function(a,b){var c=b[0].getAttribute("editor_sequence");c&&"object"==typeof c&&(c=c.value);if(c)try{editorRelKeys[c].content.value=editorRelKeys[c].func(c)||
""}catch(d){}}});i.registerPlugin(new l)})(jQuery);function filterAlertMessage(a){var b=a.message,d=a.act,a=a.redirect_url,c=location.href;"undefined"!=typeof b&&(b&&"success"!=b)&&alert(b);"undefined"!=typeof d&&d?c=current_url.setQuery("act",d):"undefined"!=typeof a&&a&&(c=a);c==location.href&&(c=c.replace(/#(.*)$/,""));location.href=c}function procFilter(a,b){b(a);return!1}
function legacy_filter(a,b,d,c,e,g,j,i){var l=xe.getApp("Validator")[0],m=jQuery,h=[];if(!l)return!1;b.elements._filter||m(b).prepend('<input type="hidden" name="_filter" />');b.elements._filter.value=a;h[0]=a;h[1]=function(a){var h={},a=m(a).serializeArray();m.each(a,function(a,b){var c=m.trim(b.value),d=b.name;if(!c||!d)return!0;i[d]&&(d=i[d]);/\[\]$/.test(d)&&(d=d.replace(/\[\]$/,""));h[d]=h[d]?h[d]+("|@|"+c):b.value});if(j&&!confirm(j))return!1;exec_xml(d,c,h,e,g,h,b)};l.cast("ADD_CALLBACK",h);
l.cast("VALIDATE",[b,a]);return!1};
| zzamtiger/xe | common/js/xe.min.js | JavaScript | lgpl-2.1 | 30,691 |
/**
* Plain console sink
* Useful when we follow js console standard.
*/
// if node.js : use amdefine (add it with npm)
if (typeof define !== 'function') { var define = require('amdefine')(module); }
define([
'./utils',
'./enricher_console_affinity'
],
function(utils, ConsoleAffinityEnricher) {
'use strict';
var console_fn_by_level = utils.original_console;
var enrich_with_console_affinity = ConsoleAffinityEnricher.make_new();
function plain_console_sink(log_call) {
enrich_with_console_affinity(log_call);
var console_fn = console_fn_by_level[log_call.console_affinity];
if(!console_fn)
console_fn = console.error;
console_fn.apply(console, log_call.args);
}
return {
// objects are created via a factory, more future-proof
'make_new': function() { return plain_console_sink; }
};
});
| Offirmo/html_tests | tosort/2021/logator/lib/sink_plain_console.js | JavaScript | unlicense | 825 |
/***************************************************************************************
Require modules
**************************************************************************************/
var exec = require('child_process').exec;
var fs = require('fs');
var ts = require('tail-stream');
var chalk = require('chalk');
var sleepTime = require('sleep-time');
const execSync = require('child_process').execSync;
var http = require("http");
const spawn = require('child_process').spawn;
var Event = require('./Library/EventChecker');
const KeywordRecognition = require('./Library/Snowboy/Snowboy');
/***************************************************************************************
Load App config file
**************************************************************************************/
var constants = require(__dirname + "/constants.js");
/***************************************************************************************
App and environmental setting Init
**************************************************************************************/
console.log(chalk.blue("\n[------------------------------------ APP INIT -------------------------------------]"))
if (typeof constants.GOOGLE_APPLICATION_CREDENTIALS == 'undefined' ||
typeof constants.GCLOUD_PROJECT == 'undefined' ||
constants.GOOGLE_APPLICATION_CREDENTIALS.length<=0 ||
constants.GCLOUD_PROJECT.length<=0){
console.log(chalk.red("\n[ ERROR : Core Modules (Google Speech Service, Ivona) need to be configured before start]\n"));
console.log(chalk.red("\n[ Please set up GOOGLE_APPLICATION_CREDENTIALS, GCLOUD_PROJECT values in the constants.js file ]\n"));
console.log(chalk.red("\n[ See documnetation in the constants.js or on www.theadrianproject.com ]\n"));
var ModulExec = execSync('killall php nodejs node python cu cat mpg123 play' , {stdio:"ignore"}); //hide it with ignore
process.exit(1);
}
if (typeof constants.IVONA_ACCESSKEY == 'undefined'||
typeof constants.IVONA_SECRETKEY == 'undefined'||
constants.IVONA_ACCESSKEY.length<=0 ||
constants.IVONA_SECRETKEY.length<=0){
console.log(chalk.red("\n[ ERROR : Core Modules (Google Speech Service, Ivona) need to be configured before start ]\n"));
console.log(chalk.red("\n[ Please set up IVONA_ACCESSKEY, IVONA_SECRETKEY values in the constants.js file ]\n"));
console.log(chalk.red("\n[ See documnetation in the constants.js or on www.theadrianproject.com ]\n"));
var ModulExec = execSync('killall php nodejs node python cu cat mpg123 play' , {stdio:"ignore"}); //hide it with ignore
process.exit(1);
}
/***************************************************************************************
Truncate Log files
**************************************************************************************/
execSync('truncate -s 0 queue.json', {stdio:"ignore"} );
execSync('truncate -s 0 Modules/Listener/Log/lastSentense.json', {stdio:"ignore"} );
// get the base model
var baseModel = require(constants.BASE_MODULE);
/*
* Global Variables
*/
var queue = [];
var actions = [];
var BrainStatus = 0;
var file = constants.QUEUE;
var messageMode = "natural"; //or facebook
var messageThreadId; //for facebook messages
/***************************************************************************************
Set up Action Queue File Stream Handler
**************************************************************************************/
var tstream = ts.createReadStream(file, {
beginAt: 0,
onMove: 'follow',
detectTruncate: false,
//onTruncate: 'end',
//endOnError: false
});
/***************************************************************************************
File Tail-er
**************************************************************************************/
function startQueueTail(){
//console.log("tailing start")
tstream.on('data', function(data) {
data = ""+data
//console.log("got data: " + data);
arrayOfLines = data.match(/[^\r\n]+/g);
for (var i in arrayOfLines) {
val = arrayOfLines[i];
try {
var lineArray = JSON.parse(val);
} catch (e) {
console.log(i +" : not JSON");
break;
}
// all fine - put that is the queue
queue.push(lineArray);
// start fill up the action queuq
feedActionQueue(lineArray)
// start processing the action queue
processActions()
}
})
}
/***************************************************************************************
Feed the action queue from the new job queue entrie
**************************************************************************************/
function feedActionQueue(val){
//console.log("feedActionQueue")
console.log(val)
for (var i in val['actions']) {
actions.push(val['actions'][i])
}
console.log("actions")
console.log(actions);
}
/***************************************************************************************
Loop through action queue and take the first one
**************************************************************************************/
function processActions(){
if (BrainStatus == 1) {
return false;
}
console.log("Check for available actions");
if (actions.length === 0) {
console.log("No more action waiting");
if (messageMode === "natural") {
StartKeywordRecognition();
}
console.log("BRAINSTATUS : " + BrainStatus);
if (BrainStatus === 0) {
console.log(chalk.green("\n[ ADRIAN STAND BY ]"))
}
return true;
}
console.log(chalk.blue("\n[------------------------------------ MODULE START ------------------------------------]"))
console.log(actions[0])
//make sure it passes the message mode (natural/facebook)
if (typeof actions[0]["Params"]["mode"] == 'undefined') {
console.log("adding message mode : " + messageMode)
actions[0]["Params"]["mode"] = messageMode;
actions[0]["Params"]["threadId"] = messageThreadId;
}else{
messageMode = actions[0]["Params"]["mode"];
if (actions[0]["Params"]["mode"]=="facebook"){
messageThreadId = actions[0]["Params"]["threadId"];
}
}
//pass it for execution
executeModuel(actions[0])
actions.shift();
}
/***************************************************************************************
Start Snowboy keyword spotting
**************************************************************************************/
function StartKeywordRecognition()
{
KeywordRecognition.StartKeywordRecognition();
sendNeoReady();
}
/***************************************************************************************
Execute Action with calling the Module - passing all parameters
**************************************************************************************/
function executeModuel(ModuleSettings){
BrainStatus = 1;
//console.log("BRAINSTATUS : "+BrainStatus)
var moduleSettingsJson = JSON.stringify(ModuleSettings);
//load module
console.log(chalk.green("exec : "+ 'node Brain/Brain.js'+ ' \''+JSON.stringify(ModuleSettings)+'\'' ))
//moduleSettingsJson = moduleSettingsJson.replace(" ","[_]")
const ls = spawn('node', ['Brain/Brain.js',moduleSettingsJson ]);
// stdoutput of a module
ls.stdout.on('data', (data) => {
if (constants.DEBUG_LEVEL>1){
console.log(data.toString('utf8'));
}
});
// if error happens
ls.stderr.on('data', (data) => {
console.log("Brain died due to fatal error!");
});
// module finish
ls.on('close', (code) => {
//console.log(`child process exited with code ${code}`);
BrainStatus = 0;
processActions()
});
console.log(chalk.blue("\n[------------------------------------ MODULE COMPLETE -----------------------------------]"))
}
/***************************************************************************************
Send Ready messae to NoePixer Deamon - This is the light which comes up when you say Adrian
**************************************************************************************/
function sendNeoReady(){
http.get({
hostname: 'localhost',
port: 9150,
path: '/?ready',
agent: false // create a new agent just for this one request
}, (res) => {
});
}
/***************************************************************************************
FaceBook message handler
**************************************************************************************/
var login = require("facebook-chat-api");
if ( typeof constants.FACEBOOK_USERNAME !== 'undefined' &&
typeof constants.FACEBOOK_PASSWORD !== 'undefined' &&
constants.FACEBOOK_USERNAME !="" &&
constants.FACEBOOK_PASSWORD!="" ){
console.log("Facebook Login Attempt");
login({email: constants.FACEBOOK_USERNAME , password: constants.FACEBOOK_PASSWORD}, function callback (err, api) {
if(err) return console.error(err);
api.setOptions({listenEvents: true});
var stopListening = api.listen(function(err, event) {
if(err) return console.error(err);
switch(event.type) {
case "message":
api.markAsRead(event.threadID, function(err) {
if(err) console.log(err);
});
console.log(chalk.blue("\n[------------------------------------ Facebook Message -----------------------------------]"))
console.log(chalk.blue("\nThread ID : "+event.threadID))
console.log(chalk.blue("\n"+event.body))
console.log(chalk.blue("\n[------------------------------------------------------------------------------------------]"))
baseModel.LeaveQueueMsg("Interpreter","interpret", {"text":event.body,"mode":"facebook","threadId":event.threadID});
break;
case "event":
console.log(event);
break;
}
})
})
}
/***************************************************************************************
Usage Log
**************************************************************************************/
var http = require("http");
var SerialNum = exec("cat /proc/cpuinfo | grep Serial | cut -d ' ' -f 2", function(err, stdout, stderr){
if (serialNumber!="")
var serialNumber = stdout;
else
var serialNumber = "undefined";
var LogReq = exec("wget -qO- http://www.theadrianproject.com/check_in/check-in.php?serial="+serialNumber+" &> /dev/null ", function(err, stdout, stderr){
console.log(stdout);
})
});
/***************************************************************************************
Spotify module accoount setup on start
**************************************************************************************/
if (typeof constants.SPOTIFY_USERNAME !== 'undefined' &&
typeof constants.SPOTIFY_PASSWORD !== 'undefined' &&
constants.SPOTIFY_USERNAME.length>0 &&
constants.SPOTIFY_PASSWORD.length>0){
fs.readFile(constants.MOPIDY_CONFIG_FILE, 'utf8', function (err,data) {
if (err) {
console.log(chalk.red("\n[ ERROR : can't find Mopidy config file : "+ constants.MOPIDY_CONFIG_FILE +" ]\n"))
}
var result = data.replace(/username =.*/, 'username = '+constants.SPOTIFY_USERNAME);
var result = result.replace(/password =.*/, 'password = '+constants.SPOTIFY_PASSWORD)
fs.writeFile(constants.MOPIDY_CONFIG_FILE, result, 'utf8', function (err) {
if (err){
return console.log(chalk.red("\n[ ERROR : can't write Mopidy config file : "+ constants.MOPIDY_CONFIG_FILE +" ]"))
}else{
console.log(chalk.blue("\n[SERVICE : Restarting Mopidy for Spotify]"))
var ModulExec = execSync(' sudo service mopidy restart', {stdio:"ignore"} );
}
})
})
}
/***************************************************************************************
Start App functions
**************************************************************************************/
// start action queue tail
startQueueTail();
// set neofixel light ready
sendNeoReady();
// start snowBoy keyword spotting
StartKeywordRecognition();
// Start event checking
Event.getEventCheck()
| AdrianHome/AdrianSmartAssistant | index.js | JavaScript | apache-2.0 | 12,768 |
console.log("XXXXXXXXXXXXXXXxWidget seems to have loaded");
function hello() {
return "Hello world";
}
function init() {
console.log("XXXXXXXXXXXXXXXxInitializing");
Ozone.eventing.clientInitialize({
name: 'hello',
fn: hello
});
}
| ozoneplatform/owf-framework | web-app/js-doh/Ozone/kernel/tests/widget1.js | JavaScript | apache-2.0 | 261 |
import { ChartInternal } from './core';
import { isValue, isDefined, diffDomain, notEmpty } from './util';
ChartInternal.prototype.getYDomainMin = function (targets) {
var $$ = this, config = $$.config,
ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
j, k, baseId, idsInGroup, id, hasNegativeValue;
if (config.data_groups.length > 0) {
hasNegativeValue = $$.hasNegativeValueInTargets(targets);
for (j = 0; j < config.data_groups.length; j++) {
// Determine baseId
idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
if (idsInGroup.length === 0) { continue; }
baseId = idsInGroup[0];
// Consider negative values
if (hasNegativeValue && ys[baseId]) {
ys[baseId].forEach(function (v, i) {
ys[baseId][i] = v < 0 ? v : 0;
});
}
// Compute min
for (k = 1; k < idsInGroup.length; k++) {
id = idsInGroup[k];
if (! ys[id]) { continue; }
ys[id].forEach(function (v, i) {
if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0)) {
ys[baseId][i] += +v;
}
});
}
}
}
return $$.d3.min(Object.keys(ys).map(function (key) { return $$.d3.min(ys[key]); }));
};
ChartInternal.prototype.getYDomainMax = function (targets) {
var $$ = this, config = $$.config,
ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
j, k, baseId, idsInGroup, id, hasPositiveValue;
if (config.data_groups.length > 0) {
hasPositiveValue = $$.hasPositiveValueInTargets(targets);
for (j = 0; j < config.data_groups.length; j++) {
// Determine baseId
idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
if (idsInGroup.length === 0) { continue; }
baseId = idsInGroup[0];
// Consider positive values
if (hasPositiveValue && ys[baseId]) {
ys[baseId].forEach(function (v, i) {
ys[baseId][i] = v > 0 ? v : 0;
});
}
// Compute max
for (k = 1; k < idsInGroup.length; k++) {
id = idsInGroup[k];
if (! ys[id]) { continue; }
ys[id].forEach(function (v, i) {
if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0)) {
ys[baseId][i] += +v;
}
});
}
}
}
return $$.d3.max(Object.keys(ys).map(function (key) { return $$.d3.max(ys[key]); }));
};
ChartInternal.prototype.getYDomain = function (targets, axisId, xDomain) {
var $$ = this, config = $$.config;
if ($$.isAxisNormalized(axisId)) {
return [0, 100];
}
var targetsByAxisId = targets.filter(function (t) { return $$.axis.getId(t.id) === axisId; }),
yTargets = xDomain ? $$.filterByXDomain(targetsByAxisId, xDomain) : targetsByAxisId,
yMin = axisId === 'y2' ? config.axis_y2_min : config.axis_y_min,
yMax = axisId === 'y2' ? config.axis_y2_max : config.axis_y_max,
yDomainMin = $$.getYDomainMin(yTargets),
yDomainMax = $$.getYDomainMax(yTargets),
domain, domainLength, padding_top, padding_bottom,
center = axisId === 'y2' ? config.axis_y2_center : config.axis_y_center,
yDomainAbs, lengths, diff, ratio, isAllPositive, isAllNegative,
isZeroBased = ($$.hasType('bar', yTargets) && config.bar_zerobased) || ($$.hasType('area', yTargets) && config.area_zerobased),
isInverted = axisId === 'y2' ? config.axis_y2_inverted : config.axis_y_inverted,
showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated,
showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated;
// MEMO: avoid inverting domain unexpectedly
yDomainMin = isValue(yMin) ? yMin : isValue(yMax) ? (yDomainMin < yMax ? yDomainMin : yMax - 10) : yDomainMin;
yDomainMax = isValue(yMax) ? yMax : isValue(yMin) ? (yMin < yDomainMax ? yDomainMax : yMin + 10) : yDomainMax;
if (yTargets.length === 0) { // use current domain if target of axisId is none
return axisId === 'y2' ? $$.y2.domain() : $$.y.domain();
}
if (isNaN(yDomainMin)) { // set minimum to zero when not number
yDomainMin = 0;
}
if (isNaN(yDomainMax)) { // set maximum to have same value as yDomainMin
yDomainMax = yDomainMin;
}
if (yDomainMin === yDomainMax) {
yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0;
}
isAllPositive = yDomainMin >= 0 && yDomainMax >= 0;
isAllNegative = yDomainMin <= 0 && yDomainMax <= 0;
// Cancel zerobased if axis_*_min / axis_*_max specified
if ((isValue(yMin) && isAllPositive) || (isValue(yMax) && isAllNegative)) {
isZeroBased = false;
}
// Bar/Area chart should be 0-based if all positive|negative
if (isZeroBased) {
if (isAllPositive) { yDomainMin = 0; }
if (isAllNegative) { yDomainMax = 0; }
}
domainLength = Math.abs(yDomainMax - yDomainMin);
padding_top = padding_bottom = domainLength * 0.1;
if (typeof center !== 'undefined') {
yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax));
yDomainMax = center + yDomainAbs;
yDomainMin = center - yDomainAbs;
}
// add padding for data label
if (showHorizontalDataLabel) {
lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'width');
diff = diffDomain($$.y.range());
ratio = [lengths[0] / diff, lengths[1] / diff];
padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1]));
padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1]));
} else if (showVerticalDataLabel) {
lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'height');
const pixelsToAxisPadding = $$.getY(
config[`axis_${axisId}_type`],
// input domain as pixels
[0, config.axis_rotated ? $$.width : $$.height ],
// output range as axis padding
[ 0, domainLength ]
);
padding_top += pixelsToAxisPadding(lengths[1]);
padding_bottom += pixelsToAxisPadding(lengths[0]);
}
if (axisId === 'y' && notEmpty(config.axis_y_padding)) {
padding_top = $$.axis.getPadding(config.axis_y_padding, 'top', padding_top, domainLength);
padding_bottom = $$.axis.getPadding(config.axis_y_padding, 'bottom', padding_bottom, domainLength);
}
if (axisId === 'y2' && notEmpty(config.axis_y2_padding)) {
padding_top = $$.axis.getPadding(config.axis_y2_padding, 'top', padding_top, domainLength);
padding_bottom = $$.axis.getPadding(config.axis_y2_padding, 'bottom', padding_bottom, domainLength);
}
// Bar/Area chart should be 0-based if all positive|negative
if (isZeroBased) {
if (isAllPositive) { padding_bottom = yDomainMin; }
if (isAllNegative) { padding_top = -yDomainMax; }
}
domain = [yDomainMin - padding_bottom, yDomainMax + padding_top];
return isInverted ? domain.reverse() : domain;
};
ChartInternal.prototype.getXDomainMin = function (targets) {
var $$ = this, config = $$.config;
return isDefined(config.axis_x_min) ?
($$.isTimeSeries() ? this.parseDate(config.axis_x_min) : config.axis_x_min) :
$$.d3.min(targets, function (t) { return $$.d3.min(t.values, function (v) { return v.x; }); });
};
ChartInternal.prototype.getXDomainMax = function (targets) {
var $$ = this, config = $$.config;
return isDefined(config.axis_x_max) ?
($$.isTimeSeries() ? this.parseDate(config.axis_x_max) : config.axis_x_max) :
$$.d3.max(targets, function (t) { return $$.d3.max(t.values, function (v) { return v.x; }); });
};
ChartInternal.prototype.getXDomainPadding = function (domain) {
var $$ = this, config = $$.config,
diff = domain[1] - domain[0],
maxDataCount, padding, paddingLeft, paddingRight;
if ($$.isCategorized()) {
padding = 0;
} else if ($$.hasType('bar')) {
maxDataCount = $$.getMaxDataCount();
padding = maxDataCount > 1 ? (diff / (maxDataCount - 1)) / 2 : 0.5;
} else {
padding = diff * 0.01;
}
if (typeof config.axis_x_padding === 'object' && notEmpty(config.axis_x_padding)) {
paddingLeft = isValue(config.axis_x_padding.left) ? config.axis_x_padding.left : padding;
paddingRight = isValue(config.axis_x_padding.right) ? config.axis_x_padding.right : padding;
} else if (typeof config.axis_x_padding === 'number') {
paddingLeft = paddingRight = config.axis_x_padding;
} else {
paddingLeft = paddingRight = padding;
}
return {left: paddingLeft, right: paddingRight};
};
ChartInternal.prototype.getXDomain = function (targets) {
var $$ = this,
xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)],
firstX = xDomain[0], lastX = xDomain[1],
padding = $$.getXDomainPadding(xDomain),
min = 0, max = 0;
// show center of x domain if min and max are the same
if ((firstX - lastX) === 0 && !$$.isCategorized()) {
if ($$.isTimeSeries()) {
firstX = new Date(firstX.getTime() * 0.5);
lastX = new Date(lastX.getTime() * 1.5);
} else {
firstX = firstX === 0 ? 1 : (firstX * 0.5);
lastX = lastX === 0 ? -1 : (lastX * 1.5);
}
}
if (firstX || firstX === 0) {
min = $$.isTimeSeries() ? new Date(firstX.getTime() - padding.left) : firstX - padding.left;
}
if (lastX || lastX === 0) {
max = $$.isTimeSeries() ? new Date(lastX.getTime() + padding.right) : lastX + padding.right;
}
return [min, max];
};
ChartInternal.prototype.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) {
var $$ = this, config = $$.config;
if (withUpdateOrgXDomain) {
$$.x.domain(domain ? domain : $$.d3.extent($$.getXDomain(targets)));
$$.orgXDomain = $$.x.domain();
if (config.zoom_enabled) { $$.zoom.update(); }
$$.subX.domain($$.x.domain());
if ($$.brush) { $$.brush.updateScale($$.subX); }
}
if (withUpdateXDomain) {
$$.x.domain(domain ? domain : (!$$.brush || $$.brush.empty()) ? $$.orgXDomain : $$.brush.selectionAsValue());
}
// Trim domain when too big by zoom mousemove event
if (withTrim) { $$.x.domain($$.trimXDomain($$.x.orgDomain())); }
return $$.x.domain();
};
ChartInternal.prototype.trimXDomain = function (domain) {
var zoomDomain = this.getZoomDomain(),
min = zoomDomain[0], max = zoomDomain[1];
if (domain[0] <= min) {
domain[1] = +domain[1] + (min - domain[0]);
domain[0] = min;
}
if (max <= domain[1]) {
domain[0] = +domain[0] - (domain[1] - max);
domain[1] = max;
}
return domain;
};
| DavidS/community_management | web_libraries/c3-0.7.15/src/domain.js | JavaScript | apache-2.0 | 11,232 |
angular.module('data')
.service('iterationService', ['url', '$http', '$q', 'filterFilter', 'todoService', 'filterFilter',
'todolistService', 'iterationDataService', 'dataProxy', 'storyService', 'bugService',
function (url, $http, $q, filterFilter, todoService, filterFilter, todolistService, iterationDataService, dataProxy, storyService, bugService) {
var _iterationApi = function(){
return url.projectApiUrl() + "/iterations/";
};
/**
* 获取迭代列表
*/
this.getIterations = dataProxy(function(update, status, projectId, companyId){
return $http.get(_iterationApi(projectId, companyId) + "?status=" + status).then(function (response) {
var results = iterationDataService.registeriterations(response.data);
return results;
});
});
/**
* 获取项目下的未开始迭代
* @param update
* @returns {*}
*/
this.getCreatedIterations = function (update, projectId, companyId) {
return this.getIterations(update, "created", projectId, companyId);
};
/**
* 获取项目下的當前迭代
* @param update
* @returns {*}
*/
this.getActiveIterations = function (update, projectId, companyId) {
return this.getIterations(update, "active", projectId, companyId).then(function(iterations){
if(iterations.length > 0){
return iterations[0];
}else{
return {};
}
});
};
/**
* 获取项目下的已完成迭代
* @param update
* @returns {*}
*/
this.getCompletedIterations = function (update, projectId, companyId) {
return this.getIterations(update, "completed", projectId, companyId);
};
/**
* 根据id获取iteration
* @param id
* @param iterations
* @returns {*}
*/
this.getiterationById = dataProxy(function (update, id) {
return $http.get(_iterationApi() + id).then(function (response) {
var iterationDTOs = [response.data];
iterationDataService.registeriterations(iterationDTOs);
return iterationDTOs[0];
});
});
/**
* 获取新的iteration
* @param projectId
* @param companyId
* @returns {*}
*/
this.getNewiteration = function(projectId, companyId){
var newiteration = new iterationDataService.Iteration().init({
companyId: companyId,
name: null,
projectId: projectId,
status: "created",
startTime: this.startTime,
endTime: this.endTime
});
var deferred = $q.defer();
deferred.resolve(newiteration);
return deferred.promise;
};
/**
* 获取项目下的當前迭代的故事Tree
* @param update
* @returns {*}
*/
this.getActiveIterationStories = function (update, projectId, companyId) {
return this.getIterations(update, "active", projectId, companyId).then(function(iterations){
for(var i = 0; i < iterations[0].iterables.length; i++){
if(iterations[0].iterables[i].type === "story"){
iterations[0].iterables[i].choose = true;
}
}
return storyService.getOpenStories(update, projectId, companyId);
});
};
/**
* 获取项目下的當前迭代的bug列表
* @param update
* @returns {*}
*/
this.getActiveIterationBugs = function (update, projectId, companyId) {
return this.getIterations(update, "active", projectId, companyId).then(function(iterations){
if(iterations.length > 0){
return bugService.getOpenBugList(projectId, companyId).then( function(data) {
for (var i = 0; i < iterations[0].iterables.length; ++i)
for (var j = 0; j < data.length; ++j)
if (iterations[0].iterables[i].type == 'bug' && iterations[0].iterables[i].id == data[j].id)
data[j].choose = true;
return data;
});
}else{
return {};
}
});
};
}]); | idear1203/onboard | frontend/kernel/src/main/resources/static/js/ng-modules/data/iteration-service.js | JavaScript | apache-2.0 | 5,170 |
//// [w1.js]
define(["require", "exports"], function(require, exports) {
});
//// [exporter.js]
define(["require", "exports"], function(require, exports) {
});
//// [consumer.js]
define(["require", "exports"], function(require, exports) {
function w() {
return { name: 'value' };
}
exports.w = w;
});
////[w1.d.ts]
export = Widget1;
interface Widget1 {
name: string;
}
////[exporter.d.ts]
export import w = require('./w1');
////[consumer.d.ts]
import e = require('./exporter');
export declare function w(): e.w;
| hippich/typescript | tests/baselines/reference/exportImportNonInstantiatedModule2.js | JavaScript | apache-2.0 | 569 |
'use strict';
// Load modules
// Declare internals
const internals = {};
exports = module.exports = function (options) {
return {
protocol: 'oauth2',
useParamsAuth: true,
auth: 'https://www.dropbox.com/1/oauth2/authorize',
token: 'https://api.dropbox.com/1/oauth2/token',
profile: async function (credentials, params, get) {
const profile = await get('https://api.dropbox.com/1/account/info');
credentials.profile = profile;
}
};
};
| logsearch/logsearch-for-cloudfoundry | src/kibana-cf_authentication/node_modules/bell/lib/providers/dropbox.js | JavaScript | apache-2.0 | 521 |
define( [
'dojo/_base/declare',
'dojo/_base/lang',
'./RequestWorker'
],
function( declare, lang, RequestWorker ) {
var dlog = function(){ console.log.apply(console, arguments); };
return declare( null,
/**
* @lends JBrowse.Store.BigWig.Window.prototype
*/
{
/**
* View into a subset of the data in a BigWig file.
*
* Adapted by Robert Buels from bigwig.js in the Dalliance Genome
* Explorer by Thomas Down.
* @constructs
*/
constructor: function(bwg, cirTreeOffset, cirTreeLength, isSummary) {
this.bwg = bwg;
this.cirTreeOffset = cirTreeOffset;
this.cirTreeLength = cirTreeLength;
this.isSummary = isSummary;
},
BED_COLOR_REGEXP: /^[0-9]+,[0-9]+,[0-9]+/,
readWigData: function(chrName, min, max, callback, errorCallback ) {
// console.log( 'reading wig data from '+chrName+':'+min+'..'+max);
var chr = this.bwg.refsByName[chrName];
if ( ! chr ) {
// Not an error because some .bwgs won't have data for all chromosomes.
// dlog("Couldn't find chr " + chrName);
// dlog('Chroms=' + miniJSONify(this.bwg.refsByName));
callback([]);
} else {
this.readWigDataById( chr.id, min, max, callback, errorCallback );
}
},
readWigDataById: function(chr, min, max, callback, errorCallback ) {
if( !this.cirHeader ) {
var readCallback = lang.hitch( this, 'readWigDataById', chr, min, max, callback );
if( this.cirHeaderLoading ) {
this.cirHeaderLoading.push( readCallback );
}
else {
this.cirHeaderLoading = [ readCallback ];
// dlog('No CIR yet, fetching');
this.bwg.data
.slice(this.cirTreeOffset, 48)
.fetch( lang.hitch( this, function(result) {
this.cirHeader = result;
var la = new Int32Array( this.cirHeader, 0, 2 );
this.cirBlockSize = la[1];
dojo.forEach( this.cirHeaderLoading, function(c) { c(); });
delete this.cirHeaderLoading;
}), errorCallback );
}
return;
}
//dlog('_readWigDataById', chr, min, max, callback);
var worker = new RequestWorker( this, chr, min, max, callback, errorCallback );
worker.cirFobRecur([this.cirTreeOffset + 48], 1);
}
});
});
| wurmlab/afra | www/JBrowse/Store/SeqFeature/BigWig/Window.js | JavaScript | apache-2.0 | 2,617 |
/// Copyright (c) 2009 Microsoft Corporation
///
/// 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 Microsoft 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.
ES5Harness.registerTest({
id: "15.2.3.7-5-b-181",
path: "TestCases/chapter15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-181.js",
description: "Object.defineProperties - value of 'writable' property of 'descObj' is the Math object (8.10.5 step 6.b)",
test: function testcase() {
var obj = {};
Object.defineProperties(obj, {
property: {
writable: Math
}
});
obj.property = "isWritable";
return obj.property === "isWritable";
},
precondition: function prereq() {
return fnExists(Object.defineProperties);
}
});
| hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-181.js | JavaScript | apache-2.0 | 2,182 |
'use strict';
var express = require('express');
var router = express.Router();
require('./local/passport');
router.use('/local', require('./local'));
module.exports = router;
| malixsys/AppDirectBlog | server/auth/index.js | JavaScript | apache-2.0 | 179 |
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
(function () {
"use strict";
var util = require("util"),
domain = require("domain"),
ConnectionManager = require("./ConnectionManager");
/**
* @constructor
* DomainManager is a module/class that handles the loading, registration,
* and execution of all commands and events. It is a singleton, and is passed
* to a domain in its init() method.
*/
var self = exports;
/**
* @private
* @type {object}
* Map of all the registered domains
*/
var _domains = {};
/**
* @private
* @type {Array.<Module>}
* Array of all modules we have loaded. Used for avoiding duplicate loading.
*/
var _initializedDomainModules = [];
/**
* @private
* @type {number}
* Used for generating unique IDs for events.
*/
var _eventCount = 1;
/**
* @private
* @type {Array}
* JSON.stringify-able Array of the current API. In the format of
* Inspector.json. This is a cache that we invalidate every time the
* API changes.
*/
var _cachedDomainDescriptions = null;
/**
* Returns whether a domain with the specified name exists or not.
* @param {string} domainName The domain name.
* @return {boolean} Whether the domain exists
*/
function hasDomain(domainName) {
return !!_domains[domainName];
}
/**
* Returns a new empty domain. Throws error if the domain already exists.
* @param {string} domainName The domain name.
* @param {{major: number, minor: number}} version The domain version.
* The version has a format like {major: 1, minor: 2}. It is reported
* in the API spec, but serves no other purpose on the server. The client
* can make use of this.
*/
function registerDomain(domainName, version) {
if (!hasDomain(domainName)) {
// invalidate the cache
_cachedDomainDescriptions = null;
_domains[domainName] = {version: version, commands: {}, events: {}};
} else {
console.error("[DomainManager] Domain " + domainName + " already registered");
}
}
/**
* Registers a new command with the specified domain. If the domain does
* not yet exist, it registers the domain with a null version.
* @param {string} domainName The domain name.
* @param {string} commandName The command name.
* @param {Function} commandFunction The callback handler for the function.
* The function is called with the arguments specified by the client in the
* command message. Additionally, if the command is asynchronous (isAsync
* parameter is true), the function is called with an automatically-
* constructed callback function of the form cb(err, result). The function
* can then use this to send a response to the client asynchronously.
* @param {boolean} isAsync See explanation for commandFunction param
* @param {?string} description Used in the API documentation
* @param {?Array.<{name: string, type: string, description:string}>} parameters
* Used in the API documentation.
* @param {?Array.<{name: string, type: string, description:string}>} returns
* Used in the API documentation.
*/
function registerCommand(domainName, commandName, commandFunction, isAsync, description, parameters, returns) {
// invalidate the cache
_cachedDomainDescriptions = null;
if (!hasDomain(domainName)) {
registerDomain(domainName, null);
}
if (!_domains[domainName].commands[commandName]) {
_domains[domainName].commands[commandName] = {
commandFunction: commandFunction,
isAsync: isAsync,
description: description,
parameters: parameters,
returns: returns
};
} else {
throw new Error("Command " + domainName + "." +
commandName + " already registered");
}
}
/**
* Executes a command by domain name and command name. Called by a connection's
* message parser. Sends response or error (possibly asynchronously) to the
* connection.
* @param {Connection} connection The requesting connection object.
* @param {number} id The unique command ID.
* @param {string} domainName The domain name.
* @param {string} commandName The command name.
* @param {Array} parameters The parameters to pass to the command function. If
* the command is asynchronous, will be augmented with a callback function.
* (see description in registerCommand documentation)
*/
function executeCommand(connection, id, domainName, commandName, parameters) {
var el, i;
for (i = 0; i < parameters.length; i++) {
el = parameters[i];
if (typeof el === "string") {
if (el.startsWith("/projects/")) {
parameters[i] = exports.projectsDir + el.substr("/projects".length);
} else if (el.startsWith("/samples/")) {
parameters[i] = exports.samplesDir + el.substr("/samples".length);
}
}
}
if (_domains[domainName] &&
_domains[domainName].commands[commandName]) {
var command = _domains[domainName].commands[commandName];
if (command.isAsync) {
var execDom = domain.create(),
callback = function (err, result) {
if (err) {
connection.sendCommandError(id, err);
} else {
connection.sendCommandResponse(id, result);
}
};
parameters.push(callback);
execDom.on("error", function(err) {
connection.sendCommandError(id, err.message);
execDom.dispose();
});
execDom.bind(command.commandFunction).apply(connection, parameters);
} else { // synchronous command
try {
connection.sendCommandResponse(
id,
command.commandFunction.apply(connection, parameters)
);
} catch (e) {
connection.sendCommandError(id, e.message);
}
}
} else {
connection.sendCommandError(id, "no such command: " +
domainName + "." + commandName);
}
}
/**
* Registers an event domain and name.
* @param {string} domainName The domain name.
* @param {string} eventName The event name.
* @param {?Array.<{name: string, type: string, description:string}>} parameters
* Used in the API documentation.
*/
function registerEvent(domainName, eventName, parameters) {
// invalidate the cache
_cachedDomainDescriptions = null;
if (!hasDomain(domainName)) {
registerDomain(domainName, null);
}
if (!_domains[domainName].events[eventName]) {
_domains[domainName].events[eventName] = {
parameters: parameters
};
} else {
console.error("[DomainManager] Event " + domainName + "." +
eventName + " already registered");
}
}
/**
* Emits an event with the specified name and parameters to all connections.
*
* TODO: Future: Potentially allow individual connections to register
* for which events they want to receive. Right now, we have so few events
* that it's fine to just send all events to everyone and decide on the
* client side if the client wants to handle them.
*
* @param {string} domainName The domain name.
* @param {string} eventName The event name.
* @param {?Array} parameters The parameters. Must be JSON.stringify-able
*/
function emitEvent(domainName, eventName, parameters) {
if (_domains[domainName] && _domains[domainName].events[eventName]) {
ConnectionManager.sendEventToAllConnections(
_eventCount++,
domainName,
eventName,
parameters
);
} else {
console.error("[DomainManager] No such event: " + domainName +
"." + eventName);
}
}
/**
* Loads and initializes domain modules using the specified paths. Checks to
* make sure that a module is not loaded/initialized more than once.
*
* @param {Array.<string>} paths The paths to load. The paths can be relative
* to the DomainManager or absolute. However, modules that aren't in core
* won't know where the DomainManager module is, so in general, all paths
* should be absolute.
* @return {boolean} Whether loading succeded. (Failure will throw an exception).
*/
function loadDomainModulesFromPaths(paths) {
var pathArray = paths;
if (!util.isArray(paths)) {
pathArray = [paths];
}
pathArray.forEach(function (path) {
if (path.startsWith("/brackets/")) {
path = "../../brackets-srv/" + path.substr("/brackets/".length);
} else if (path.startsWith("/support/extensions/user/")) {
if (exports.allowUserDomains) {
path = exports.supportDir + path.substr("/support".length);
} else {
console.error("ERROR: User domains are not allowed: " + path);
return false;
}
} else if (path !== "./BaseDomain") {
console.error("ERROR: Invalid domain path: " + path);
return false;
}
try {
var m = require(path);
if (m && m.init && _initializedDomainModules.indexOf(m) < 0) {
m.init(self);
_initializedDomainModules.push(m); // don't init more than once
}
} catch (err) {
console.error(err);
return false;
}
});
return true; // if we fail, an exception will be thrown
}
/**
* Returns a description of all registered domains in the format of WebKit's
* Inspector.json. Used for sending API documentation to clients.
*
* @return {Array} Array describing all domains.
*/
function getDomainDescriptions() {
if (!_cachedDomainDescriptions) {
_cachedDomainDescriptions = [];
var domainNames = Object.keys(_domains);
domainNames.forEach(function (domainName) {
var d = {
domain: domainName,
version: _domains[domainName].version,
commands: [],
events: []
};
var commandNames = Object.keys(_domains[domainName].commands);
commandNames.forEach(function (commandName) {
var c = _domains[domainName].commands[commandName];
d.commands.push({
name: commandName,
description: c.description,
parameters: c.parameters,
returns: c.returns
});
});
var eventNames = Object.keys(_domains[domainName].events);
eventNames.forEach(function (eventName) {
d.events.push({
name: eventName,
parameters: _domains[domainName].events[eventName].parameters
});
});
_cachedDomainDescriptions.push(d);
});
}
return _cachedDomainDescriptions;
}
exports.hasDomain = hasDomain;
exports.registerDomain = registerDomain;
exports.registerCommand = registerCommand;
exports.executeCommand = executeCommand;
exports.registerEvent = registerEvent;
exports.emitEvent = emitEvent;
exports.loadDomainModulesFromPaths = loadDomainModulesFromPaths;
exports.getDomainDescriptions = getDomainDescriptions;
}());
| Jw00/WATT | libs/brackets-server/lib/domains/DomainManager.js | JavaScript | apache-2.0 | 13,746 |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
var HAS_SEARCH_PAGE = false;
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
//27 = esc
if (e.keyCode == 27) {
gSelectedIndex = -1;
gSelectedID = -1;
gMatches.length = 0;
gLastText = "";
document.getElementById("search_filtered_div").className = "no-display";
search.value = "";
return false;
}
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
if (HAS_SEARCH_PAGE) {
return true;
} else {
sync_selection_table(toroot);
return false;
}
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
if (HAS_SEARCH_PAGE) {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
}
return false;
}
| kwf2030/doclava | src/main/resources/assets/templates/assets/search_autocomplete.js | JavaScript | apache-2.0 | 8,967 |
// @flow
import { _SET_APP_STATE_LISTENER, APP_STATE_CHANGED } from './actionTypes';
/**
* Sets the listener to be used with React Native's AppState API.
*
* @param {Function} listener - Function to be set as the change event listener.
* @protected
* @returns {{
* type: _SET_APP_STATE_LISTENER,
* listener: Function
* }}
*/
export function _setAppStateListener(listener: ?Function) {
return {
type: _SET_APP_STATE_LISTENER,
listener
};
}
/**
* Signals that the App state has changed (in terms of execution state). The
* application can be in 3 states: 'active', 'inactive' and 'background'.
*
* @param {string} appState - The new App state.
* @public
* @returns {{
* type: APP_STATE_CHANGED,
* appState: string
* }}
* @see {@link https://facebook.github.io/react-native/docs/appstate.html}
*/
export function appStateChanged(appState: string) {
return {
type: APP_STATE_CHANGED,
appState
};
}
| jitsi/jitsi-meet | react/features/mobile/background/actions.js | JavaScript | apache-2.0 | 981 |
// Copyright 2014 Samsung Electronics Co., Ltd.
//
// 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.
assert(1/Math.ceil(-0.3) === -Infinity);
| LeeHayun/jerryscript | tests/jerry-test-suite/15/15.08/15.08.02/15.08.02.06/15.08.02.06-006.js | JavaScript | apache-2.0 | 647 |
/**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.session',
name: 'LocalSetting',
properties: [
{
name: 'id',
class: 'String'
},
{
name: 'value',
class: 'String'
}
]
}); | jacksonic/vjlofvhjfgm | src/foam/nanos/session/LocalSetting.js | JavaScript | apache-2.0 | 325 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
module.exports = [
{
"category": "ZOOKEEPER_SERVER",
"filename": "zoo.cfg.xml",
"index": 1,
"name": "dataDir",
"serviceName": "ZOOKEEPER"
},
{
"category": "ZOOKEEPER_SERVER",
"filename": "zoo.cfg.xml",
"index": 2,
"name": "tickTime",
"serviceName": "ZOOKEEPER"
},
{
"category": "ZOOKEEPER_SERVER",
"filename": "zoo.cfg.xml",
"index": 3,
"name": "initLimit",
"serviceName": "ZOOKEEPER"
},
{
"category": "ZOOKEEPER_SERVER",
"filename": "zoo.cfg.xml",
"index": 4,
"name": "syncLimit",
"serviceName": "ZOOKEEPER"
},
{
"category": "ZOOKEEPER_SERVER",
"filename": "zoo.cfg.xml",
"index": 5,
"name": "clientPort",
"serviceName": "ZOOKEEPER"
},
{
"filename": "zookeeper-env.xml",
"index": 0,
"name": "zk_log_dir",
"serviceName": "ZOOKEEPER"
},
{
"filename": "zookeeper-env.xml",
"index": 1,
"name": "zk_pid_dir",
"serviceName": "ZOOKEEPER"
}
]; | radicalbit/ambari | ambari-web/app/data/configs/services/zookeeper_properties.js | JavaScript | apache-2.0 | 1,804 |
'use strict';
exports.SpriteSpeed = {
VERY_SLOW: 2,
SLOW: 3,
LITTLE_SLOW: 4,
NORMAL: 5,
LITTLE_FAST: 6,
FAST: 8,
VERY_FAST: 12,
};
exports.SpriteSize = {
VERY_SMALL: 0.5,
SMALL: 0.75,
NORMAL: 1,
LARGE: 1.5,
VERY_LARGE: 2
};
exports.Direction = {
NONE: 0,
NORTH: 1,
EAST: 2,
SOUTH: 4,
WEST: 8,
NORTHEAST: 3,
SOUTHEAST: 6,
SOUTHWEST: 12,
NORTHWEST: 9
};
var Dir = exports.Direction;
/**
* Mapping number of steps away from north to direction enum.
* @type {Direction[]}
*/
exports.ClockwiseDirectionsFromNorth = [
Dir.NORTH,
Dir.NORTHEAST,
Dir.EAST,
Dir.SOUTHEAST,
Dir.SOUTH,
Dir.SOUTHWEST,
Dir.WEST,
Dir.NORTHWEST
];
/**
* Given a 2D vector (x and y) provides the closest animation direction
* given in our Direction enum.
* @param {number} x
* @param {number} y
* @returns {Direction}
*/
exports.getClosestDirection = function (x, y) {
// Y is inverted between our playlab coordinate space and what atan2 expects.
var radiansFromNorth = Math.atan2(x, -y);
var stepRadians = Math.PI / 4;
// Snap positive index of nearest 45° where 0 is North, 1 is NE, etc...
var stepsFromNorth = (Math.round(radiansFromNorth / stepRadians) + 8) % 8;
// At this point we should have an int between 0 and 7
return exports.ClockwiseDirectionsFromNorth[stepsFromNorth];
};
var frameDirTable = {};
frameDirTable[Dir.SOUTHEAST] = 0;
frameDirTable[Dir.EAST] = 1;
frameDirTable[Dir.NORTHEAST] = 2;
frameDirTable[Dir.NORTH] = 3;
frameDirTable[Dir.NORTHWEST] = 4;
frameDirTable[Dir.WEST] = 5;
frameDirTable[Dir.SOUTHWEST] = 6;
exports.frameDirTable = frameDirTable;
var frameDirTableWalking = {};
frameDirTableWalking[Dir.NONE] = 0;
frameDirTableWalking[Dir.SOUTH] = 0;
frameDirTableWalking[Dir.SOUTHEAST] = 1;
frameDirTableWalking[Dir.EAST] = 2;
frameDirTableWalking[Dir.NORTHEAST] = 3;
frameDirTableWalking[Dir.NORTH] = 4;
frameDirTableWalking[Dir.NORTHWEST] = 5;
frameDirTableWalking[Dir.WEST] = 6;
frameDirTableWalking[Dir.SOUTHWEST] = 7;
exports.frameDirTableWalking = frameDirTableWalking;
// Forward-to-left (clockwise)
var frameDirTableWalkingWithIdleClockwise = {};
frameDirTableWalkingWithIdleClockwise[Dir.NONE] = 8;
frameDirTableWalkingWithIdleClockwise[Dir.SOUTH] = 0;
frameDirTableWalkingWithIdleClockwise[Dir.SOUTHEAST] = 1;
frameDirTableWalkingWithIdleClockwise[Dir.EAST] = 2;
frameDirTableWalkingWithIdleClockwise[Dir.NORTHEAST] = 3;
frameDirTableWalkingWithIdleClockwise[Dir.NORTH] = 4;
frameDirTableWalkingWithIdleClockwise[Dir.NORTHWEST] = 5;
frameDirTableWalkingWithIdleClockwise[Dir.WEST] = 6;
frameDirTableWalkingWithIdleClockwise[Dir.SOUTHWEST] = 7;
exports.frameDirTableWalkingWithIdleClockwise = frameDirTableWalkingWithIdleClockwise;
// Forward-to-right (counter-clockwise)
var frameDirTableWalkingWithIdleCounterclockwise = {};
frameDirTableWalkingWithIdleCounterclockwise[Dir.NONE] = 8;
frameDirTableWalkingWithIdleCounterclockwise[Dir.SOUTH] = 0;
frameDirTableWalkingWithIdleCounterclockwise[Dir.SOUTHEAST] = 7;
frameDirTableWalkingWithIdleCounterclockwise[Dir.EAST] = 6;
frameDirTableWalkingWithIdleCounterclockwise[Dir.NORTHEAST] = 5;
frameDirTableWalkingWithIdleCounterclockwise[Dir.NORTH] = 4;
frameDirTableWalkingWithIdleCounterclockwise[Dir.NORTHWEST] = 3;
frameDirTableWalkingWithIdleCounterclockwise[Dir.WEST] = 2;
frameDirTableWalkingWithIdleCounterclockwise[Dir.SOUTHWEST] = 1;
exports.frameDirTableWalkingWithIdleCounterclockwise = frameDirTableWalkingWithIdleCounterclockwise;
/**
* Given a direction, returns the unit vector for it.
*/
var UNIT_VECTOR = {};
UNIT_VECTOR[Dir.NONE] = { x: 0, y: 0};
UNIT_VECTOR[Dir.NORTH] = { x: 0, y:-1};
UNIT_VECTOR[Dir.EAST] = { x: 1, y: 0};
UNIT_VECTOR[Dir.SOUTH] = { x: 0, y: 1};
UNIT_VECTOR[Dir.WEST] = { x:-1, y: 0};
UNIT_VECTOR[Dir.NORTHEAST] = { x: 1, y:-1};
UNIT_VECTOR[Dir.SOUTHEAST] = { x: 1, y: 1};
UNIT_VECTOR[Dir.SOUTHWEST] = { x:-1, y: 1};
UNIT_VECTOR[Dir.NORTHWEST] = { x:-1, y:-1};
exports.Direction.getUnitVector = function (dir) {
return UNIT_VECTOR[dir];
};
exports.Position = {
OUTTOPOUTLEFT: 1,
OUTTOPLEFT: 2,
OUTTOPCENTER: 3,
OUTTOPRIGHT: 4,
OUTTOPOUTRIGHT: 5,
TOPOUTLEFT: 6,
TOPLEFT: 7,
TOPCENTER: 8,
TOPRIGHT: 9,
TOPOUTRIGHT: 10,
MIDDLEOUTLEFT: 11,
MIDDLELEFT: 12,
MIDDLECENTER: 13,
MIDDLERIGHT: 14,
MIDDLEOUTRIGHT: 15,
BOTTOMOUTLEFT: 16,
BOTTOMLEFT: 17,
BOTTOMCENTER: 18,
BOTTOMRIGHT: 19,
BOTTOMOUTRIGHT: 20,
OUTBOTTOMOUTLEFT: 21,
OUTBOTTOMLEFT: 22,
OUTBOTTOMCENTER: 23,
OUTBOTTOMRIGHT: 24,
OUTBOTTOMOUTRIGHT:25
};
//
// Turn state machine, use as NextTurn[fromDir][toDir]
//
exports.NextTurn = {};
exports.NextTurn[Dir.NORTH] = {};
exports.NextTurn[Dir.NORTH][Dir.NORTH] = Dir.NORTH;
exports.NextTurn[Dir.NORTH][Dir.EAST] = Dir.NORTHEAST;
exports.NextTurn[Dir.NORTH][Dir.SOUTH] = Dir.NORTHEAST;
exports.NextTurn[Dir.NORTH][Dir.NONE] = Dir.NORTHEAST;
exports.NextTurn[Dir.NORTH][Dir.WEST] = Dir.NORTHWEST;
exports.NextTurn[Dir.NORTH][Dir.NORTHEAST] = Dir.NORTHEAST;
exports.NextTurn[Dir.NORTH][Dir.SOUTHEAST] = Dir.NORTHEAST;
exports.NextTurn[Dir.NORTH][Dir.SOUTHWEST] = Dir.NORTHWEST;
exports.NextTurn[Dir.NORTH][Dir.NORTHWEST] = Dir.NORTHWEST;
exports.NextTurn[Dir.EAST] = {};
exports.NextTurn[Dir.EAST][Dir.NORTH] = Dir.NORTHEAST;
exports.NextTurn[Dir.EAST][Dir.EAST] = Dir.EAST;
exports.NextTurn[Dir.EAST][Dir.SOUTH] = Dir.SOUTHEAST;
exports.NextTurn[Dir.EAST][Dir.NONE] = Dir.SOUTHEAST;
exports.NextTurn[Dir.EAST][Dir.WEST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.EAST][Dir.NORTHEAST] = Dir.NORTHEAST;
exports.NextTurn[Dir.EAST][Dir.SOUTHEAST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.EAST][Dir.SOUTHWEST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.EAST][Dir.NORTHWEST] = Dir.NORTHEAST;
exports.NextTurn[Dir.SOUTH] = {};
exports.NextTurn[Dir.SOUTH][Dir.NORTH] = Dir.SOUTHEAST;
exports.NextTurn[Dir.SOUTH][Dir.EAST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.SOUTH][Dir.SOUTH] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTH][Dir.NONE] = Dir.NONE;
exports.NextTurn[Dir.SOUTH][Dir.WEST] = Dir.SOUTHWEST;
exports.NextTurn[Dir.SOUTH][Dir.NORTHEAST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.SOUTH][Dir.SOUTHEAST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.SOUTH][Dir.SOUTHWEST] = Dir.SOUTHWEST;
exports.NextTurn[Dir.SOUTH][Dir.NORTHWEST] = Dir.SOUTHWEST;
exports.NextTurn[Dir.WEST] = {};
exports.NextTurn[Dir.WEST][Dir.NORTH] = Dir.NORTHWEST;
exports.NextTurn[Dir.WEST][Dir.EAST] = Dir.SOUTHWEST;
exports.NextTurn[Dir.WEST][Dir.SOUTH] = Dir.SOUTHWEST;
exports.NextTurn[Dir.WEST][Dir.NONE] = Dir.SOUTHWEST;
exports.NextTurn[Dir.WEST][Dir.WEST] = Dir.WEST;
exports.NextTurn[Dir.WEST][Dir.NORTHEAST] = Dir.NORTHWEST;
exports.NextTurn[Dir.WEST][Dir.SOUTHEAST] = Dir.SOUTHWEST;
exports.NextTurn[Dir.WEST][Dir.SOUTHWEST] = Dir.SOUTHWEST;
exports.NextTurn[Dir.WEST][Dir.NORTHWEST] = Dir.NORTHWEST;
exports.NextTurn[Dir.NORTHEAST] = {};
exports.NextTurn[Dir.NORTHEAST][Dir.NORTH] = Dir.NORTH;
exports.NextTurn[Dir.NORTHEAST][Dir.EAST] = Dir.EAST;
exports.NextTurn[Dir.NORTHEAST][Dir.SOUTH] = Dir.EAST;
exports.NextTurn[Dir.NORTHEAST][Dir.NONE] = Dir.EAST;
exports.NextTurn[Dir.NORTHEAST][Dir.WEST] = Dir.NORTH;
exports.NextTurn[Dir.NORTHEAST][Dir.NORTHEAST] = Dir.NORTHEAST;
exports.NextTurn[Dir.NORTHEAST][Dir.SOUTHEAST] = Dir.EAST;
exports.NextTurn[Dir.NORTHEAST][Dir.SOUTHWEST] = Dir.EAST;
exports.NextTurn[Dir.NORTHEAST][Dir.NORTHWEST] = Dir.NORTH;
exports.NextTurn[Dir.SOUTHEAST] = {};
exports.NextTurn[Dir.SOUTHEAST][Dir.NORTH] = Dir.EAST;
exports.NextTurn[Dir.SOUTHEAST][Dir.EAST] = Dir.EAST;
exports.NextTurn[Dir.SOUTHEAST][Dir.SOUTH] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHEAST][Dir.NONE] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHEAST][Dir.WEST] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHEAST][Dir.NORTHEAST] = Dir.EAST;
exports.NextTurn[Dir.SOUTHEAST][Dir.SOUTHEAST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.SOUTHEAST][Dir.SOUTHWEST] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHEAST][Dir.NORTHWEST] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHWEST] = {};
exports.NextTurn[Dir.SOUTHWEST][Dir.NORTH] = Dir.WEST;
exports.NextTurn[Dir.SOUTHWEST][Dir.EAST] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHWEST][Dir.SOUTH] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHWEST][Dir.NONE] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHWEST][Dir.WEST] = Dir.WEST;
exports.NextTurn[Dir.SOUTHWEST][Dir.NORTHEAST] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHWEST][Dir.SOUTHEAST] = Dir.SOUTH;
exports.NextTurn[Dir.SOUTHWEST][Dir.SOUTHWEST] = Dir.SOUTHWEST;
exports.NextTurn[Dir.SOUTHWEST][Dir.NORTHWEST] = Dir.WEST;
exports.NextTurn[Dir.NORTHWEST] = {};
exports.NextTurn[Dir.NORTHWEST][Dir.NORTH] = Dir.NORTH;
exports.NextTurn[Dir.NORTHWEST][Dir.EAST] = Dir.NORTH;
exports.NextTurn[Dir.NORTHWEST][Dir.SOUTH] = Dir.WEST;
exports.NextTurn[Dir.NORTHWEST][Dir.NONE] = Dir.WEST;
exports.NextTurn[Dir.NORTHWEST][Dir.WEST] = Dir.WEST;
exports.NextTurn[Dir.NORTHWEST][Dir.NORTHEAST] = Dir.NORTH;
exports.NextTurn[Dir.NORTHWEST][Dir.SOUTHEAST] = Dir.WEST;
exports.NextTurn[Dir.NORTHWEST][Dir.SOUTHWEST] = Dir.WEST;
exports.NextTurn[Dir.NORTHWEST][Dir.NORTHWEST] = Dir.NORTHWEST;
exports.NextTurn[Dir.NONE] = {};
exports.NextTurn[Dir.NONE][Dir.NORTH] = Dir.SOUTHEAST;
exports.NextTurn[Dir.NONE][Dir.EAST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.NONE][Dir.SOUTH] = Dir.SOUTH;
exports.NextTurn[Dir.NONE][Dir.NONE] = Dir.NONE;
exports.NextTurn[Dir.NONE][Dir.WEST] = Dir.SOUTHWEST;
exports.NextTurn[Dir.NONE][Dir.NORTHEAST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.NONE][Dir.SOUTHEAST] = Dir.SOUTHEAST;
exports.NextTurn[Dir.NONE][Dir.SOUTHWEST] = Dir.SOUTHWEST;
exports.NextTurn[Dir.NONE][Dir.NORTHWEST] = Dir.SOUTHWEST;
exports.Emotions = {
NORMAL: 0,
HAPPY: 1,
ANGRY: 2,
SAD: 3
};
// scale the collision bounding box to make it so they need to overlap a touch:
exports.FINISH_COLLIDE_DISTANCE_SCALING = 0.75;
exports.SPRITE_COLLIDE_DISTANCE_SCALING = 0.9;
exports.DEFAULT_SPRITE_SPEED = exports.SpriteSpeed.NORMAL;
exports.DEFAULT_SPRITE_SIZE = 1;
exports.DEFAULT_SPRITE_ANIMATION_FRAME_DURATION = 6;
exports.DEFAULT_PROJECTILE_SPEED = exports.SpriteSpeed.SLOW;
exports.DEFAULT_PROJECTILE_ANIMATION_FRAME_DURATION = 1.5;
exports.DEFAULT_ITEM_SPEED = exports.SpriteSpeed.SLOW;
exports.DEFAULT_ITEM_ANIMATION_FRAME_DURATION = 1.5;
/**
* The types of squares in the maze, which is represented
* as a 2D array of SquareType values.
* @enum {number}
*/
exports.SquareType = {
OPEN: 0,
SPRITEFINISH: 1,
NOT_USED_2: 2,
WALL: 4, // random wall tile
NOT_USED_8: 8,
SPRITESTART: 16,
ITEM_CLASS_0: 32, // Must stay in sync with SquareItemClassShift below
ITEM_CLASS_1: 64,
ITEM_CLASS_2: 128,
ITEM_CLASS_3: 256,
ITEM_CLASS_4: 512,
ITEM_CLASS_5: 1024,
ITEM_CLASS_6: 2048,
ITEM_CLASS_7: 4096,
NOT_USED_8K: 8192,
NOT_USED_16K: 16384,
NOT_USED_32K: 32768
// Walls specifically retrieved from an 16x16 grid are stored in bits 16-27.
};
exports.SquareItemClassMask =
exports.SquareType.ITEM_CLASS_0 |
exports.SquareType.ITEM_CLASS_1 |
exports.SquareType.ITEM_CLASS_2 |
exports.SquareType.ITEM_CLASS_3 |
exports.SquareType.ITEM_CLASS_4 |
exports.SquareType.ITEM_CLASS_5 |
exports.SquareType.ITEM_CLASS_6 |
exports.SquareType.ITEM_CLASS_7;
exports.SquareItemClassShift = 5;
exports.squareHasItemClass = function (itemClassIndex, squareValue) {
var classesEnabled =
(squareValue & exports.SquareItemClassMask) >>> exports.SquareItemClassShift;
return Math.pow(2, itemClassIndex) & classesEnabled;
};
/**
* The types of walls in the maze.
* @enum {number}
*/
exports.WallType = {
NORMAL_SIZE: 0,
DOUBLE_SIZE: 1,
JUMBO_SIZE: 2
};
exports.WallTypeMask = 0x0F000000;
exports.WallCoordRowMask = 0x00F00000;
exports.WallCoordColMask = 0x000F0000;
exports.WallCoordsMask =
exports.WallTypeMask | exports.WallCoordRowMask | exports.WallCoordColMask;
exports.WallCoordsShift = 16;
exports.WallCoordColShift = exports.WallCoordsShift;
exports.WallCoordRowShift = exports.WallCoordsShift + 4;
exports.WallTypeShift = exports.WallCoordsShift + 8;
exports.WallCoordMax = 16; // indicates a 16x16 grid, which requires 8 bits
exports.WallRandomCoordMax = 2; // how many rows/cols we randomly select tiles from
exports.WallAnyMask = exports.WallCoordsMask | exports.SquareType.WALL;
// Floating score: change opacity and Y coordinate by these values each tick.
exports.floatingScoreChangeOpacity = -0.025;
exports.floatingScoreChangeY = -1;
exports.RANDOM_VALUE = 'random';
exports.HIDDEN_VALUE = '"hidden"';
exports.CLICK_VALUE = '"click"';
exports.VISIBLE_VALUE = '"visible"';
// Number of extra ticks between the last time the sprite moved and when we
// reset them to face south.
exports.IDLE_TICKS_BEFORE_FACE_SOUTH = 4;
/** @type {number} animation rate in frames per second. */
exports.DEFAULT_ANIMATION_RATE = 20;
// Fade durations (in milliseconds)
exports.GOAL_FADE_TIME = 200;
exports.ITEM_FADE_TIME = 200;
exports.DEFAULT_ACTOR_FADE_TIME = 1000;
exports.TOUCH_HAZARD_EFFECT_TIME = 1500;
// Other defaults for actions
exports.SHAKE_DEFAULT_DURATION = 1000;
exports.SHAKE_DEFAULT_CYCLES = 6;
exports.SHAKE_DEFAULT_DISTANCE = 5;
// Maximum number of clouds that can be displayed.
exports.MAX_NUM_CLOUDS = 2;
// Width & height of a cloud.
exports.CLOUD_SIZE = 300;
// The opacity of a cloud.
exports.CLOUD_OPACITY = 0.7;
// How many milliseconds to throttle between playing sounds.
exports.SOUND_THROTTLE_TIME = 200;
// How many milliseconds to throttle between whenTouchObstacle events when
// blockMovingIntoWalls is enabled.
exports.TOUCH_OBSTACLE_THROTTLE_TIME = 330;
| rvarshney/code-dot-org | apps/src/studio/constants.js | JavaScript | apache-2.0 | 13,739 |
/*
* Copyright 2014 Space Dynamics Laboratory - Utah State University Research Foundation.
*
* 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.
*/
'use strict';
app.controller('AdminSystemCtrl', ['$scope', 'business', '$rootScope', '$uiModal', '$timeout', 'FileUploader',
function ($scope, Business, $rootScope, $uiModal, $timeout, FileUploader) {
$scope.recentChangesForm = {};
$scope.recentChangesForm.lastRunDts = "";
$scope.recentChangesForm.emailAddress = "";
$scope.recentChangesStatus = {};
$scope.errorTickets = {};
$scope.maxPageNumber = 1;
$scope.pageNumber = 1;
$scope.EMAIL_REGEXP = utils.EMAIL_REGEXP;
$scope.queryFilter = angular.copy(utils.queryFilter);
$scope.queryFilter.max = 100;
$scope.untilDate = new Date();
$scope.appProperties = [];
$scope.configProperties = [];
$scope.loggers = [];
$scope.appStatus = {};
$scope.threads = [];
$scope.predicate = [];
$scope.reverse = [];
$scope.tabs = {};
$scope.tabs.general = true;
$scope.flags = {};
$scope.flags.showPluginUpload = false;
$scope.plugins = [];
$scope.selectTab = function(tab){
_.forIn($scope.tabs, function(value, key){
$scope.tabs[key] = false;
});
$scope.tabs[tab] = true;
};
$scope.pagination = {};
$scope.pagination.control;
$scope.pagination.features = {'dates': false, 'max': true};
$scope.refreshTickets = function(){
$scope.$emit('$TRIGGERLOAD', 'ticketLoader');
if ($scope.pagination.control && $scope.pagination.control.refresh) {
$scope.pagination.control.refresh().then(function(){
$scope.$emit('$TRIGGERUNLOAD', 'ticketLoader');
});
} else {
$scope.$emit('$TRIGGERUNLOAD', 'ticketLoader');
}
};
$scope.getPercent = function(value,max) {
return Math.round((value / max) * 100);
};
$scope.getPercentColor = function(value) {
if (value < 65) {
return 'success';
} else if (value >= 65 && value <= 80) {
return 'warning';
} else {
return 'danger';
}
};
$scope.firstPage = function(){
$scope.pageNumber=1;
$scope.refreshTickets();
};
$scope.lastPage = function(){
$scope.pageNumber=$scope.maxPageNumber;
$scope.refreshTickets();
};
$scope.prevPage = function(){
$scope.pageNumber=$scope.pageNumber-1;
if ($scope.pageNumber < 1) {
$scope.pageNumber = 1;
}
$scope.refreshTickets();
};
$scope.nextPage = function(){
$scope.pageNumber=$scope.pageNumber+1;
if ($scope.pageNumber > $scope.maxPageNumber) {
$scope.pageNumber = $scope.maxPageNumber;
}
$scope.refreshTickets();
};
$scope.setPageSize = function(){
$scope.pageNumber = 1;
$scope.refreshTickets();
};
$scope.jumpPage = function(){
if ($scope.pageNumber > $scope.maxPageNumber) {
$scope.pageNumber = $scope.maxPageNumber;
}
$scope.refreshTickets();
};
$scope.setPredicate = function(predicate, table){
if ($scope.predicate[table] === predicate){
$scope.reverse[table] = !$scope.reverse[table];
} else {
$scope.predicate[table] = predicate;
$scope.reverse[table] = false;
}
if (table === 'error') {
$scope.pagination.control.changeSortOrder(predicate);
}
};
var stickThatTable = function(){
var offset = $('.top').outerHeight() + $('#errorTicketToolbar').outerHeight();
$(".stickytable").stickyTableHeaders({
fixedOffset: offset + 30
});
};
$(window).resize(stickThatTable);
$timeout(stickThatTable, 100);
$scope.showErrorDetails = function(ticket){
// var ticket = _.find($scope.errorTickets.errorTickets, {'errorTicketId': ticketId});
if (ticket.details && ticket.details === true){
ticket.details = false;
ticket.detailText = "View Details";
} else {
ticket.details = true;
ticket.detailText = "Hide Details";
}
if (!ticket.loadedDetails) {
Business.systemservice.getErrorTicketInfo(ticket.errorTicketId).then(function (results) {
ticket.loadedDetails = results;
});
}
};
$scope.wrapString = function(data){
if (data !== undefined && data !== null) {
var newString = "";
for (var i=0; i<data.length; i++){
newString += data.charAt(i);
if (newString.length % 40 === 0) {
newString += " ";
}
}
return newString;
}
return data;
};
$scope.reindexListings = function(){
var response = window.confirm("Are you sure you want to reset Indexer?");
if (response){
Business.systemservice.resetIndexer().then(function (results) {
triggerAlert('Re-Index task submitted see jobs -> tasks for status', 'reIndexMessage', '', 5000, true);
});
}
};
$scope.recentChangeStatus = function(){
Business.systemservice.getRecentChangeStatus().then(function (result){
$scope.recentChangesStatus = result;
});
};
$scope.recentChangeStatus();
$scope.sendRecentChangesEmail = function(){
var response = window.confirm("Are you sure you want to email recent changes?");
if (response){
Business.systemservice.sendRecentChangesEmail($scope.recentChangesForm.lastRunDts, $scope.recentChangesForm.emailAddress).then(function (result){
triggerAlert('Emailing recent changes, see jobs -> tasks for status', 'recentChangesEmailMessage', '', 5000, true);
});
}
};
$scope.refreshAppProperties = function(){
$scope.$emit('$TRIGGERLOAD', 'appPropLoader');
Business.systemservice.getAppProperties().then(function (results) {
if (results) {
$scope.appProperties = results;
}
$scope.$emit('$TRIGGERUNLOAD', 'appPropLoader');
});
};
$scope.refreshAppProperties();
$scope.refreshConfigProps = function(){
$scope.$emit('$TRIGGERLOAD', 'configPropLoader');
Business.systemservice.getConfigProperties().then(function (results) {
if (results) {
$scope.configProperties = results;
}
$scope.$emit('$TRIGGERUNLOAD', 'configPropLoader');
});
};
$scope.refreshConfigProps();
$scope.refreshLoggers = function(){
$scope.$emit('$TRIGGERLOAD', 'loggingLoader');
Business.systemservice.getLoggers().then(function (results) {
if (results) {
$scope.loggers = results;
}
$scope.$emit('$TRIGGERUNLOAD', 'loggingLoader');
});
};
$scope.refreshLoggers();
$scope.refreshAppStatus = function(){
$scope.$emit('$TRIGGERLOAD', 'loggingLoader');
Business.systemservice.getAppStatus().then(function (results) {
if (results) {
$scope.appStatus = results;
}
$scope.$emit('$TRIGGERUNLOAD', 'loggingLoader');
});
};
$scope.refreshAppStatus();
$scope.refreshThreads = function(){
$scope.$emit('$TRIGGERLOAD', 'loggingLoader');
Business.systemservice.getThreads().then(function (results) {
if (results) {
$scope.threads = results;
}
$scope.$emit('$TRIGGERUNLOAD', 'loggingLoader');
});
};
$scope.refreshThreads();
$scope.editAppProperty = function(property){
var modalInstance = $uiModal.open({
templateUrl: 'views/admin/application_management/editAppProperty.html',
controller: 'adminEditAppPropertyCtrl',
size: 'lg',
resolve: {
property: function () {
return property;
}
}
});
};
$scope.$on('$REFRESH_APP_PROPS', function(){
triggerAlert('Saved successfully', 'editAppProperty', 'body', 3000);
$scope.refreshAppProperties();
});
$scope.editLogger = function(logger){
var modalInstance = $uiModal.open({
templateUrl: 'views/admin/application_management/editLogger.html',
controller: 'adminEditLoggingCtrl',
size: 'lg',
resolve: {
logger: function () {
return logger;
}
}
});
};
$scope.$on('$REFRESH_LOGGERS', function(){
triggerAlert('Saved successfully', 'editLogger', 'body', 3000);
$scope.refreshLoggers();
});
$scope.viewLog =function(){
var modalInstance = $uiModal.open({
templateUrl: 'views/admin/application_management/viewLog.html',
controller: 'adminViewLogCtrl',
size: 'lg',
resolve: {
}
});
};
//plugin controls
$scope.refreshPlugins = function(){
$scope.$emit('$TRIGGERLOAD', 'pluginsLoader');
Business.systemservice.getPlugins().then(function (results) {
if (results) {
$scope.plugins = results;
}
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
}, function(failed) {
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
});
};
$scope.refreshPlugins();
$scope.startPlugin = function(pluginId){
$scope.$emit('$TRIGGERLOAD', 'pluginsLoader');
Business.systemservice.startPlugin(pluginId).then(function (results) {
$scope.refreshPlugins();
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
triggerAlert('Started plugin', 'plugin', 'body', 3000);
}, function(failed){
triggerAlert('Failed to start plugin. See log for details.', 'plugin', 'body', 3000);
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
});
};
$scope.stopPlugin = function(pluginId){
Business.systemservice.stopPlugin(pluginId).then(function (results) {
$scope.refreshPlugins();
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
triggerAlert('Stopped plugin', 'plugin', 'body', 3000);
}, function(failed){
triggerAlert('Failed to stop plugin. See log for details.', 'plugin', 'body', 3000);
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
});
};
$scope.uninstallPlugin = function(pluginId){
var response = window.confirm("Are you sure you want to uninstall plugin? (It's recommended to download the plugin first for an easy re-install.)");
if (response) {
Business.systemservice.uninstallPlugin(pluginId).then(function (results) {
$scope.refreshPlugins();
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
triggerAlert('Uninstalled plugin', 'plugin', 'body', 3000);
}, function (failed) {
triggerAlert('Failed to uninstall plugin. See log for details.', 'plugin', 'body', 3000);
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
});
}
};
$scope.addPlugin = function(){
if ($scope.flags.showPluginUpload) {
$scope.flags.showPluginUpload = false;
} else {
$scope.flags.showPluginUpload = true;
}
};
$scope.uploadPlugin = function(){
$scope.uploader.uploadAll();
};
$scope.downloadPlugin = function(pluginId){
window.location.href = "api/v1/resource/plugins/" + pluginId + "/download";
};
$scope.uploader = new FileUploader({
url: 'Upload.action?UploadPlugin',
alias: 'uploadFile',
queueLimit: 1,
onBeforeUploadItem: function(item) {
$scope.$emit('$TRIGGERLOAD', 'pluginsLoader');
},
onSuccessItem: function (item, response, status, headers) {
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
$scope.uploader.clearQueue();
//check response for a fail ticket or a error model
if (response.success) {
triggerAlert('Uploaded successfully; Waiting for deployment job to install. Please refresh to confirm deployment.', 'plugin', 'body', 3000);
$scope.flags.showPluginUpload = false;
$scope.refreshPlugins();
} else {
if (response.errors) {
var uploadError = response.errors.uploadFile;
var enityError = response.errors.entityName;
var errorMessage = uploadError !== undefined ? uploadError : ' ' + enityError !== undefined ? enityError : '';
triggerAlert('Unable to upload plugin. Message: <br> ' + errorMessage, 'plugin', 'body', 6000);
} else {
triggerAlert('Unable to upload plugin. ', 'plugin', 'body', 6000);
}
}
},
onErrorItem: function (item, response, status, headers) {
$scope.$emit('$TRIGGERUNLOAD', 'pluginsLoader');
triggerAlert('Unable to upload plugin. Failure communicating with server. ', 'plugin', 'body', 6000);
$scope.uploader.clearQueue();
},
onCompleteAll: function(){
document.getElementById('uploadFile').value = null;
$scope.uploader.queue = [];
}
});
}]);
app.controller('adminEditAppPropertyCtrl', ['$scope', '$uiModalInstance', 'property', 'business', function ($scope, $uiModalInstance, property, Business) {
$scope.propetyForm = angular.copy(property);
$scope.cancel = function(){
$uiModalInstance.dismiss('cancel');
};
$scope.save = function(){
$scope.$emit('$TRIGGERLOAD', 'formLoader');
Business.systemservice.updateAppProperty($scope.propetyForm.key, $scope.propetyForm.value).then(function (results) {
$scope.$emit('$TRIGGERUNLOAD', 'formLoader');
$scope.$emit('$TRIGGEREVENT', '$REFRESH_APP_PROPS');
$uiModalInstance.dismiss('success');
}, function(){
triggerAlert('Unable to save. ', 'editLogger', 'body', 3000);
$scope.$emit('$TRIGGERUNLOAD', 'formLoader');
});
};
}]);
app.controller('adminEditLoggingCtrl', ['$scope', '$uiModalInstance', 'logger', 'business', function ($scope, $uiModalInstance, logger, Business) {
$scope.logger = angular.copy(logger);
$scope.logLevels = [];
$scope.loadLevels = function(){
$scope.$emit('$TRIGGERLOAD', 'formLoader');
Business.systemservice.getLogLevels().then(function (results) {
if (results) {
$scope.logLevels = results;
$scope.logger.levelSelect = _.find($scope.logLevels, {'code': $scope.logger.level});
if ($scope.logger.levelSelect === undefined) {
$scope.logger.useParentLevel=true;
}
}
$scope.$emit('$TRIGGERUNLOAD', 'formLoader');
});
};
$scope.loadLevels();
$scope.cancel = function(){
$uiModalInstance.dismiss('cancel');
};
$scope.save = function(){
$scope.$emit('$TRIGGERLOAD', 'formLoader');
if ($scope.logger.useParentLevel) {
$scope.logger.level = null;
} else {
$scope.logger.level = $scope.logger.levelSelect.code;
}
Business.systemservice.updateLogLevel($scope.logger.name, $scope.logger.level).then(function (results) {
$scope.$emit('$TRIGGERUNLOAD', 'formLoader');
$scope.$emit('$TRIGGEREVENT', '$REFRESH_LOGGERS');
$uiModalInstance.dismiss('success');
}, function(){
triggerAlert('Unable to save. ', 'editLogger', 'body', 3000);
$scope.$emit('$TRIGGERUNLOAD', 'formLoader');
});
};
}]);
app.controller('adminViewLogCtrl', ['$scope', '$uiModalInstance', 'business', '$sce', function ($scope, $uiModalInstance, Business, $sce) {
$scope.logRecords = [];
$scope.predicate = [];
$scope.reverse = [];
$scope.pagination = {};
$scope.pagination.control;
$scope.pagination.features = {'dates': true, 'max': true};
$scope.setPredicate = function (predicate, table) {
if ($scope.predicate[table] === predicate) {
$scope.reverse[table] = !$scope.reverse[table];
} else {
$scope.predicate[table] = predicate;
$scope.reverse[table] = false;
}
if (table === 'logs') {
$scope.pagination.control.changeSortOrder(predicate);
}
};
$scope.refreshData = function() {
$scope.$emit('$TRIGGERLOAD', 'logLoader');
if ($scope.pagination.control && $scope.pagination.control.refresh) {
$scope.pagination.control.refresh().then(function(){
$scope.$emit('$TRIGGERUNLOAD', 'logLoader');
});
} else {
$scope.$emit('$TRIGGERUNLOAD', 'logLoader');
}
};
$scope.showDetails = function(record){
if (record.details) {
record.details = !record.details;
} else {
record.details = true;
}
};
$scope.clearAll = function () {
var response = window.confirm("Clear all DB log records?");
if (response) {
Business.systemservice.clearAllLogRecords().then(function (result) {
$scope.refreshData();
});
}
};
$scope.getLogContent = function(record) {
return $sce.trustAsHtml(record.stackTrace);
};
$scope.cancel = function(){
$uiModalInstance.dismiss('cancel');
};
}]); | tyler-travis/openstorefront | client/openstorefront/app/scripts/controllers/admin/application_management/system.js | JavaScript | apache-2.0 | 17,477 |
var AWS = require('../core');
var EventEmitter = require('events').EventEmitter;
require('../http');
/**
* @api private
*/
AWS.XHRClient = AWS.util.inherit({
handleRequest: function handleRequest(httpRequest, httpOptions, callback, errCallback) {
var self = this;
var endpoint = httpRequest.endpoint;
var emitter = new EventEmitter();
var href = endpoint.protocol + '//' + endpoint.hostname;
if (endpoint.port !== 80 && endpoint.port !== 443) {
href += ':' + endpoint.port;
}
href += httpRequest.path;
var xhr = new XMLHttpRequest(), headersEmitted = false;
httpRequest.stream = xhr;
xhr.addEventListener('readystatechange', function() {
try {
if (xhr.status === 0) return; // 0 code is invalid
} catch (e) { return; }
if (this.readyState >= this.HEADERS_RECEIVED && !headersEmitted) {
try { xhr.responseType = 'arraybuffer'; } catch (e) {}
emitter.statusCode = xhr.status;
emitter.headers = self.parseHeaders(xhr.getAllResponseHeaders());
emitter.emit(
'headers',
emitter.statusCode,
emitter.headers,
xhr.statusText
);
headersEmitted = true;
}
if (this.readyState === this.DONE) {
self.finishRequest(xhr, emitter);
}
}, false);
xhr.upload.addEventListener('progress', function (evt) {
emitter.emit('sendProgress', evt);
});
xhr.addEventListener('progress', function (evt) {
emitter.emit('receiveProgress', evt);
}, false);
xhr.addEventListener('timeout', function () {
errCallback(AWS.util.error(new Error('Timeout'), {code: 'TimeoutError'}));
}, false);
xhr.addEventListener('error', function () {
errCallback(AWS.util.error(new Error('Network Failure'), {
code: 'NetworkingError'
}));
}, false);
xhr.addEventListener('abort', function () {
errCallback(AWS.util.error(new Error('Request aborted'), {
code: 'RequestAbortedError'
}));
}, false);
callback(emitter);
xhr.open(httpRequest.method, href, httpOptions.xhrAsync !== false);
AWS.util.each(httpRequest.headers, function (key, value) {
if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') {
xhr.setRequestHeader(key, value);
}
});
if (httpOptions.timeout && httpOptions.xhrAsync !== false) {
xhr.timeout = httpOptions.timeout;
}
if (httpOptions.xhrWithCredentials) {
xhr.withCredentials = true;
}
try {
if (httpRequest.body) {
xhr.send(httpRequest.body);
} else {
xhr.send();
}
} catch (err) {
if (httpRequest.body && typeof httpRequest.body.buffer === 'object') {
xhr.send(httpRequest.body.buffer); // send ArrayBuffer directly
} else {
throw err;
}
}
return emitter;
},
parseHeaders: function parseHeaders(rawHeaders) {
var headers = {};
AWS.util.arrayEach(rawHeaders.split(/\r?\n/), function (line) {
var key = line.split(':', 1)[0];
var value = line.substring(key.length + 2);
if (key.length > 0) headers[key.toLowerCase()] = value;
});
return headers;
},
finishRequest: function finishRequest(xhr, emitter) {
var buffer;
if (xhr.responseType === 'arraybuffer' && xhr.response) {
var ab = xhr.response;
buffer = new AWS.util.Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
}
try {
if (!buffer && typeof xhr.responseText === 'string') {
buffer = new AWS.util.Buffer(xhr.responseText);
}
} catch (e) {}
if (buffer) emitter.emit('data', buffer);
emitter.emit('end');
}
});
/**
* @api private
*/
AWS.HttpClient.prototype = AWS.XHRClient.prototype;
/**
* @api private
*/
AWS.HttpClient.streamsApiVersion = 1;
| justinrains/dukestrivia | src/node_modules/aws-sdk/lib/http/xhr.js | JavaScript | apache-2.0 | 3,943 |
// Note: Captcha is verified client-side
$.register({
rule: {
host: /^(www\.)?boxcash\.net$/,
path: /^\/\w+$/,
},
ready: function () {
'use strict';
// JSON.parse() is not used because their JSON is malformed
var m = $.searchScripts(/\'\/ajax_link\.php\',\{key:'(\w+)',url:'(\d+)',t:'(\d+)',r:'(\w*)'\}/);
$.post('/ajax_link.php', {
key: m[1],
url: m[2],
t: m[3],
r: m[4],
}).then(function (response) {
var l = response.match(/window(?:.top.window)\.location="([^"]+)"/);
$.openLink(l[1]);
});
},
});
$.register({
rule: {
host: /^(www\.)?boxcash\.net$/,
path: /^\/redirect\.html$/,
query: /url=(.+)$/,
},
start: function (m) {
'use strict';
var l = decodeURIComponent(m.query[1]);
$.openLink(l);
},
});
// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
| tosunkaya/adsbypasser | src/sites/link/boxcash.net.js | JavaScript | bsd-2-clause | 986 |
/*
* Copyright 2012-present, Polis Technology 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 for non-commercial use can be found in the PATENTS file
* in the same directory.
*/
export const colors = {
agree: "#2ecc71"
};
| filiperibeiro77/polisClientAdmin | src/components/framework/colors.js | JavaScript | bsd-3-clause | 384 |
/**
* Copyright (c) 2013-present, 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.
*
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* 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 NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK 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.
*
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
AsyncStorage,
PickerIOS,
Text,
View
} = ReactNative;
var PickerItemIOS = PickerIOS.Item;
var STORAGE_KEY = '@AsyncStorageExample:key';
var COLORS = ['red', 'orange', 'yellow', 'green', 'blue'];
var BasicStorageExample = React.createClass({
componentDidMount() {
this._loadInitialState().done();
},
async _loadInitialState() {
try {
var value = await AsyncStorage.getItem(STORAGE_KEY);
if (value !== null){
this.setState({selectedValue: value});
this._appendMessage('Recovered selection from disk: ' + value);
} else {
this._appendMessage('Initialized with no selection on disk.');
}
} catch (error) {
this._appendMessage('AsyncStorage error: ' + error.message);
}
},
getInitialState() {
return {
selectedValue: COLORS[0],
messages: [],
};
},
render() {
var color = this.state.selectedValue;
return (
<View>
<PickerIOS
selectedValue={color}
onValueChange={this._onValueChange}>
{COLORS.map((value) => (
<PickerItemIOS
key={value}
value={value}
label={value}
/>
))}
</PickerIOS>
<Text>
{'Selected: '}
<Text style={{color}}>
{this.state.selectedValue}
</Text>
</Text>
<Text>{' '}</Text>
<Text onPress={this._removeStorage}>
Press here to remove from storage.
</Text>
<Text>{' '}</Text>
<Text>Messages:</Text>
{this.state.messages.map((m) => <Text key={m}>{m}</Text>)}
</View>
);
},
async _onValueChange(selectedValue) {
this.setState({selectedValue});
try {
await AsyncStorage.setItem(STORAGE_KEY, selectedValue);
this._appendMessage('Saved selection to disk: ' + selectedValue);
} catch (error) {
this._appendMessage('AsyncStorage error: ' + error.message);
}
},
async _removeStorage() {
try {
await AsyncStorage.removeItem(STORAGE_KEY);
this._appendMessage('Selection removed from disk.');
} catch (error) {
this._appendMessage('AsyncStorage error: ' + error.message);
}
},
_appendMessage(message) {
this.setState({messages: this.state.messages.concat(message)});
},
});
exports.title = 'AsyncStorage';
exports.description = 'Asynchronous local disk storage.';
exports.examples = [
{
title: 'Basics - getItem, setItem, removeItem',
render(): ReactElement<any> { return <BasicStorageExample />; }
},
];
| mrspeaker/react-native | Examples/UIExplorer/js/AsyncStorageExample.js | JavaScript | bsd-3-clause | 3,614 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = require.requireActual('base62');
| cpojer/fbjs | packages/fbjs/src/crypto/__mocks__/base62.js | JavaScript | bsd-3-clause | 249 |
/*
* Copyright 2012-present, Polis Technology 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 for non-commercial use can be found in the PATENTS file
* in the same directory.
*/
import React from "react";
import Radium from "radium";
// import _ from "lodash";
import Flex from "../framework/flex";
// import { connect } from "react-redux";
// import { FOO } from "../actions";
import Comment from "./summary-comment";
import Awesome from "react-fontawesome";
// @connect(state => {
// return state.FOO;
// })
@Radium
class SummaryGroup extends React.Component {
constructor(props) {
super(props);
this.state = {
pagination: 0,
showHowOtherGroupsFelt: false
};
}
static propTypes = {
/* react */
// dispatch: React.PropTypes.func,
params: React.PropTypes.object,
routes: React.PropTypes.array,
/* component api */
style: React.PropTypes.object,
// foo: React.PropTypes.string
}
static defaultProps = {
// foo: "bar"
}
getStyles() {
return {
numberBadge: {
backgroundColor: "rgb(140,140,140)",
padding: "3px 6px",
borderRadius: 3,
color: "white",
fontWeight: 300
}
};
}
groupComments() {
const comments = this.props.comments.comments;
const math = this.props.math.math;
return this.props.groupComments.map((comment, i) => {
const groupVotes = math["group-votes"][this.props.repnessIndex].votes[comment.tid];
const isBestAgree = comment["best-agree"] && (groupVotes && groupVotes.A > 0);
const agree = isBestAgree || comment["repful-for"] === "agree";
const percent = agree ?
Math.floor(groupVotes.A / groupVotes.S * 100) :
Math.floor(groupVotes.D / groupVotes.S * 100);
// if (this.state.pagination === i) {
return (
<Comment
key={i}
showHowOtherGroupsFelt={this.props.showHowOtherGroupsFelt}
majority={false}
agree={agree}
percent={percent}
{...comment}
{...comments[comment.tid]}/>
)
// }
})
}
render() {
const styles = this.getStyles();
const math = this.props.math.math;
return (
<div
style={{
marginBottom: 70
}}>
<p>
<span style={{fontSize: 18, fontWeight: 100}}>
{`GROUP ${+this.props.repnessIndex + 1} `}
</span>
<span style={{fontSize: 18, fontWeight: 500}}>
{` • ${math["group-votes"][this.props.repnessIndex]["n-members"]} participants`}
</span>
</p>
{this.groupComments()}
</div>
);
}
}
export default SummaryGroup;
// <Awesome name="users"/>
// {` `}
// {`Group `}
// {``}
// {": "}
// {` participants`}
| filiperibeiro77/polisClientAdmin | src/components/conversation-admin/summary-group.js | JavaScript | bsd-3-clause | 2,960 |
// ==========================================================================
// Project: SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
// Portions ©2008-2011 Apple Inc. All rights reserved.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
/*global module test equals context ok */
var context = null;
module("SC.RenderContext#element", {
setup: function() {
context = SC.RenderContext() ;
},
teardown: function() {
context = null;
}
});
test("converts context to a DOM element and returns root element if there is one", function() {
context.id('foo');
var elem = context.element();
ok(elem, 'elem not null');
equals(elem.tagName.toString().toLowerCase(), 'div', 'is div');
equals(elem.id.toString(), 'foo', 'is id=foo');
elem = null ;
});
test("returns null if context does not generate valid element", function() {
context = SC.RenderContext(null);
var elem = context.element();
equals(elem, null, 'should be null');
elem = null;
});
test("returns first element if context renders multiple element", function() {
context.tag('div').tag('span');
var elem = context.element();
ok(elem, 'elem not null');
equals(elem.tagName.toString().toLowerCase(), 'div', 'is div');
elem = null;
});
| darkrsw/safe | tests/clone_detector_tests/sproutcore/frameworks/core_foundation/tests/system/render_context/element.js | JavaScript | bsd-3-clause | 1,397 |
/*
* Copyright (C) 2008 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 INC. 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.
*/
/**
* @constructor
* @extends {WebInspector.Object}
* @param {!Array.<!WebInspector.DataGrid.ColumnDescriptor>} columnsArray
* @param {function(!WebInspector.DataGridNode, string, string, string)=} editCallback
* @param {function(!WebInspector.DataGridNode)=} deleteCallback
* @param {function()=} refreshCallback
* @param {function(!WebInspector.ContextMenu, !WebInspector.DataGridNode)=} contextMenuCallback
*/
WebInspector.DataGrid = function(columnsArray, editCallback, deleteCallback, refreshCallback, contextMenuCallback)
{
this.element = createElementWithClass("div", "data-grid");
WebInspector.appendStyle(this.element, "ui_lazy/dataGrid.css");
this.element.tabIndex = 0;
this.element.addEventListener("keydown", this._keyDown.bind(this), false);
var headerContainer = createElementWithClass("div", "header-container");
/** @type {!Element} */
this._headerTable = headerContainer.createChild("table", "header");
/** @type {!Object.<string, !Element>} */
this._headerTableHeaders = {};
/** @type {!Element} */
this._scrollContainer = createElementWithClass("div", "data-container");
/** @type {!Element} */
this._dataTable = this._scrollContainer.createChild("table", "data");
this._dataTable.addEventListener("mousedown", this._mouseDownInDataTable.bind(this));
this._dataTable.addEventListener("click", this._clickInDataTable.bind(this), true);
this._dataTable.addEventListener("contextmenu", this._contextMenuInDataTable.bind(this), true);
// FIXME: Add a createCallback which is different from editCallback and has different
// behavior when creating a new node.
if (editCallback)
this._dataTable.addEventListener("dblclick", this._ondblclick.bind(this), false);
/** @type {function(!WebInspector.DataGridNode, string, string, string)|undefined} */
this._editCallback = editCallback;
/** @type {function(!WebInspector.DataGridNode)|undefined} */
this._deleteCallback = deleteCallback;
/** @type {function()|undefined} */
this._refreshCallback = refreshCallback;
/** @type {function(!WebInspector.ContextMenu, !WebInspector.DataGridNode)|undefined} */
this._contextMenuCallback = contextMenuCallback;
this.element.appendChild(headerContainer);
this.element.appendChild(this._scrollContainer);
/** @type {!Element} */
this._headerRow = createElement("tr");
/** @type {!Element} */
this._headerTableColumnGroup = createElement("colgroup");
/** @type {!Element} */
this._dataTableColumnGroup = createElement("colgroup");
/** @type {!Element} */
this._topFillerRow = createElementWithClass("tr", "data-grid-filler-row revealed");
/** @type {!Element} */
this._bottomFillerRow = createElementWithClass("tr", "data-grid-filler-row revealed");
this.setVerticalPadding(0, 0);
/** @type {boolean} */
this._inline = false;
/** @type {!Array.<!WebInspector.DataGrid.ColumnDescriptor>} */
this._columnsArray = columnsArray;
/** @type {!Array.<!WebInspector.DataGrid.ColumnDescriptor>} */
this._visibleColumnsArray = columnsArray;
/** @type {!Object.<string, !WebInspector.DataGrid.ColumnDescriptor>} */
this._columns = {};
/** @type {?string} */
this._cellClass = null;
for (var i = 0; i < columnsArray.length; ++i) {
var column = columnsArray[i];
var columnIdentifier = column.identifier = column.id || String(i);
this._columns[columnIdentifier] = column;
if (column.disclosure)
this.disclosureColumnIdentifier = columnIdentifier;
var cell = createElement("th");
cell.className = columnIdentifier + "-column";
cell.columnIdentifier = String(columnIdentifier);
this._headerTableHeaders[columnIdentifier] = cell;
var div = createElement("div");
if (column.titleDOMFragment)
div.appendChild(column.titleDOMFragment);
else
div.textContent = column.title;
cell.appendChild(div);
if (column.sort) {
cell.classList.add(column.sort);
this._sortColumnCell = cell;
}
if (column.sortable) {
cell.addEventListener("click", this._clickInHeaderCell.bind(this), false);
cell.classList.add("sortable");
cell.createChild("div", "sort-order-icon-container").createChild("div", "sort-order-icon");
}
}
this._headerTable.appendChild(this._headerTableColumnGroup);
this.headerTableBody.appendChild(this._headerRow);
this._dataTable.appendChild(this._dataTableColumnGroup);
this.dataTableBody.appendChild(this._topFillerRow);
this.dataTableBody.appendChild(this._bottomFillerRow);
this._refreshHeader();
/** @type {boolean} */
this._editing = false;
/** @type {?WebInspector.DataGridNode} */
this.selectedNode = null;
/** @type {boolean} */
this.expandNodesWhenArrowing = false;
this.setRootNode(new WebInspector.DataGridNode());
/** @type {number} */
this.indentWidth = 15;
/** @type {!Array.<!Element|{__index: number, __position: number}>} */
this._resizers = [];
/** @type {boolean} */
this._columnWidthsInitialized = false;
/** @type {number} */
this._cornerWidth = WebInspector.DataGrid.CornerWidth;
/** @type {!WebInspector.DataGrid.ResizeMethod} */
this._resizeMethod = WebInspector.DataGrid.ResizeMethod.Nearest;
}
// Keep in sync with .data-grid col.corner style rule.
WebInspector.DataGrid.CornerWidth = 14;
/**
* @typedef {{
* id: string,
* title: string,
* sortable: boolean,
* sort: (?WebInspector.DataGrid.Order|undefined),
* align: (?WebInspector.DataGrid.Align|undefined),
* fixedWidth: (boolean|undefined),
* editable: (boolean|undefined),
* nonSelectable: (boolean|undefined),
* longText: (boolean|undefined),
* disclosure: (boolean|undefined),
* identifier: (string|undefined),
* weight: (number|undefined)
* }}
*/
WebInspector.DataGrid.ColumnDescriptor;
WebInspector.DataGrid.Events = {
SelectedNode: "SelectedNode",
DeselectedNode: "DeselectedNode",
SortingChanged: "SortingChanged",
ColumnsResized: "ColumnsResized"
}
/** @enum {string} */
WebInspector.DataGrid.Order = {
Ascending: "sort-ascending",
Descending: "sort-descending"
}
/** @enum {string} */
WebInspector.DataGrid.Align = {
Center: "center",
Right: "right"
}
WebInspector.DataGrid._preferredWidthSymbol = Symbol("preferredWidth");
WebInspector.DataGrid.prototype = {
/**
* @param {string} cellClass
*/
setCellClass: function(cellClass)
{
this._cellClass = cellClass;
},
_refreshHeader: function()
{
this._headerTableColumnGroup.removeChildren();
this._dataTableColumnGroup.removeChildren();
this._headerRow.removeChildren();
this._topFillerRow.removeChildren();
this._bottomFillerRow.removeChildren();
for (var i = 0; i < this._visibleColumnsArray.length; ++i) {
var column = this._visibleColumnsArray[i];
var columnIdentifier = column.identifier || String(i);
var headerColumn = this._headerTableColumnGroup.createChild("col");
var dataColumn = this._dataTableColumnGroup.createChild("col");
if (column.width) {
headerColumn.style.width = column.width;
dataColumn.style.width = column.width;
}
this._headerRow.appendChild(this._headerTableHeaders[columnIdentifier]);
this._topFillerRow.createChild("td", "top-filler-td");
this._bottomFillerRow.createChild("td", "bottom-filler-td").columnIdentifier_ = columnIdentifier;
}
this._headerRow.createChild("th", "corner");
this._topFillerRow.createChild("td", "corner").classList.add("top-filler-td");
this._bottomFillerRow.createChild("td", "corner").classList.add("bottom-filler-td");
this._headerTableColumnGroup.createChild("col", "corner");
this._dataTableColumnGroup.createChild("col", "corner");
},
/**
* @param {number} top
* @param {number} bottom
* @protected
*/
setVerticalPadding: function(top, bottom)
{
this._topFillerRow.style.height = top + "px";
if (top || bottom)
this._bottomFillerRow.style.height = bottom + "px";
else
this._bottomFillerRow.style.height = "auto";
},
/**
* @param {!WebInspector.DataGridNode} rootNode
* @protected
*/
setRootNode: function(rootNode)
{
if (this._rootNode) {
this._rootNode.removeChildren();
this._rootNode.dataGrid = null;
this._rootNode._isRoot = false;
}
/** @type {!WebInspector.DataGridNode} */
this._rootNode = rootNode;
rootNode._isRoot = true;
rootNode.hasChildren = false;
rootNode._expanded = true;
rootNode._revealed = true;
rootNode.selectable = false;
rootNode.dataGrid = this;
},
/**
* @return {!WebInspector.DataGridNode}
*/
rootNode: function()
{
return this._rootNode;
},
_ondblclick: function(event)
{
if (this._editing || this._editingNode)
return;
var columnIdentifier = this.columnIdentifierFromNode(event.target);
if (!columnIdentifier || !this._columns[columnIdentifier].editable)
return;
this._startEditing(event.target);
},
/**
* @param {!WebInspector.DataGridNode} node
* @param {number} cellIndex
*/
_startEditingColumnOfDataGridNode: function(node, cellIndex)
{
this._editing = true;
/** @type {?WebInspector.DataGridNode} */
this._editingNode = node;
this._editingNode.select();
var element = this._editingNode._element.children[cellIndex];
WebInspector.InplaceEditor.startEditing(element, this._startEditingConfig(element));
element.getComponentSelection().setBaseAndExtent(element, 0, element, 1);
},
_startEditing: function(target)
{
var element = target.enclosingNodeOrSelfWithNodeName("td");
if (!element)
return;
this._editingNode = this.dataGridNodeFromNode(target);
if (!this._editingNode) {
if (!this.creationNode)
return;
this._editingNode = this.creationNode;
}
// Force editing the 1st column when editing the creation node
if (this._editingNode.isCreationNode)
return this._startEditingColumnOfDataGridNode(this._editingNode, this._nextEditableColumn(-1));
this._editing = true;
WebInspector.InplaceEditor.startEditing(element, this._startEditingConfig(element));
element.getComponentSelection().setBaseAndExtent(element, 0, element, 1);
},
renderInline: function()
{
this.element.classList.add("inline");
this._cornerWidth = 0;
this._inline = true;
this.updateWidths();
},
_startEditingConfig: function(element)
{
return new WebInspector.InplaceEditor.Config(this._editingCommitted.bind(this), this._editingCancelled.bind(this), element.textContent);
},
_editingCommitted: function(element, newText, oldText, context, moveDirection)
{
var columnIdentifier = this.columnIdentifierFromNode(element);
if (!columnIdentifier) {
this._editingCancelled(element);
return;
}
var column = this._columns[columnIdentifier];
var cellIndex = this._visibleColumnsArray.indexOf(column);
var textBeforeEditing = this._editingNode.data[columnIdentifier];
var currentEditingNode = this._editingNode;
/**
* @param {boolean} wasChange
* @this {WebInspector.DataGrid}
*/
function moveToNextIfNeeded(wasChange)
{
if (!moveDirection)
return;
if (moveDirection === "forward") {
var firstEditableColumn = this._nextEditableColumn(-1);
if (currentEditingNode.isCreationNode && cellIndex === firstEditableColumn && !wasChange)
return;
var nextEditableColumn = this._nextEditableColumn(cellIndex);
if (nextEditableColumn !== -1)
return this._startEditingColumnOfDataGridNode(currentEditingNode, nextEditableColumn);
var nextDataGridNode = currentEditingNode.traverseNextNode(true, null, true);
if (nextDataGridNode)
return this._startEditingColumnOfDataGridNode(nextDataGridNode, firstEditableColumn);
if (currentEditingNode.isCreationNode && wasChange) {
this.addCreationNode(false);
return this._startEditingColumnOfDataGridNode(this.creationNode, firstEditableColumn);
}
return;
}
if (moveDirection === "backward") {
var prevEditableColumn = this._nextEditableColumn(cellIndex, true);
if (prevEditableColumn !== -1)
return this._startEditingColumnOfDataGridNode(currentEditingNode, prevEditableColumn);
var lastEditableColumn = this._nextEditableColumn(this._visibleColumnsArray.length, true);
var nextDataGridNode = currentEditingNode.traversePreviousNode(true, true);
if (nextDataGridNode)
return this._startEditingColumnOfDataGridNode(nextDataGridNode, lastEditableColumn);
return;
}
}
if (textBeforeEditing == newText) {
this._editingCancelled(element);
moveToNextIfNeeded.call(this, false);
return;
}
// Update the text in the datagrid that we typed
this._editingNode.data[columnIdentifier] = newText;
// Make the callback - expects an editing node (table row), the column number that is being edited,
// the text that used to be there, and the new text.
this._editCallback(this._editingNode, columnIdentifier, textBeforeEditing, newText);
if (this._editingNode.isCreationNode)
this.addCreationNode(false);
this._editingCancelled(element);
moveToNextIfNeeded.call(this, true);
},
_editingCancelled: function(element)
{
this._editing = false;
this._editingNode = null;
},
/**
* @param {number} cellIndex
* @param {boolean=} moveBackward
* @return {number}
*/
_nextEditableColumn: function(cellIndex, moveBackward)
{
var increment = moveBackward ? -1 : 1;
var columns = this._visibleColumnsArray;
for (var i = cellIndex + increment; (i >= 0) && (i < columns.length); i += increment) {
if (columns[i].editable)
return i;
}
return -1;
},
/**
* @return {?string}
*/
sortColumnIdentifier: function()
{
if (!this._sortColumnCell)
return null;
return this._sortColumnCell.columnIdentifier;
},
/**
* @return {?string}
*/
sortOrder: function()
{
if (!this._sortColumnCell || this._sortColumnCell.classList.contains(WebInspector.DataGrid.Order.Ascending))
return WebInspector.DataGrid.Order.Ascending;
if (this._sortColumnCell.classList.contains(WebInspector.DataGrid.Order.Descending))
return WebInspector.DataGrid.Order.Descending;
return null;
},
/**
* @return {boolean}
*/
isSortOrderAscending: function()
{
return !this._sortColumnCell || this._sortColumnCell.classList.contains(WebInspector.DataGrid.Order.Ascending);
},
get headerTableBody()
{
if ("_headerTableBody" in this)
return this._headerTableBody;
this._headerTableBody = this._headerTable.getElementsByTagName("tbody")[0];
if (!this._headerTableBody) {
this._headerTableBody = this.element.ownerDocument.createElement("tbody");
this._headerTable.insertBefore(this._headerTableBody, this._headerTable.tFoot);
}
return this._headerTableBody;
},
get dataTableBody()
{
if ("_dataTableBody" in this)
return this._dataTableBody;
this._dataTableBody = this._dataTable.getElementsByTagName("tbody")[0];
if (!this._dataTableBody) {
this._dataTableBody = this.element.ownerDocument.createElement("tbody");
this._dataTable.insertBefore(this._dataTableBody, this._dataTable.tFoot);
}
return this._dataTableBody;
},
/**
* @param {!Array.<number>} widths
* @param {number} minPercent
* @param {number=} maxPercent
* @return {!Array.<number>}
*/
_autoSizeWidths: function(widths, minPercent, maxPercent)
{
if (minPercent)
minPercent = Math.min(minPercent, Math.floor(100 / widths.length));
var totalWidth = 0;
for (var i = 0; i < widths.length; ++i)
totalWidth += widths[i];
var totalPercentWidth = 0;
for (var i = 0; i < widths.length; ++i) {
var width = Math.round(100 * widths[i] / totalWidth);
if (minPercent && width < minPercent)
width = minPercent;
else if (maxPercent && width > maxPercent)
width = maxPercent;
totalPercentWidth += width;
widths[i] = width;
}
var recoupPercent = totalPercentWidth - 100;
while (minPercent && recoupPercent > 0) {
for (var i = 0; i < widths.length; ++i) {
if (widths[i] > minPercent) {
--widths[i];
--recoupPercent;
if (!recoupPercent)
break;
}
}
}
while (maxPercent && recoupPercent < 0) {
for (var i = 0; i < widths.length; ++i) {
if (widths[i] < maxPercent) {
++widths[i];
++recoupPercent;
if (!recoupPercent)
break;
}
}
}
return widths;
},
/**
* @param {number} minPercent
* @param {number=} maxPercent
* @param {number=} maxDescentLevel
*/
autoSizeColumns: function(minPercent, maxPercent, maxDescentLevel)
{
var widths = [];
for (var i = 0; i < this._columnsArray.length; ++i)
widths.push((this._columnsArray[i].title || "").length);
maxDescentLevel = maxDescentLevel || 0;
var children = this._enumerateChildren(this._rootNode, [], maxDescentLevel + 1);
for (var i = 0; i < children.length; ++i) {
var node = children[i];
for (var j = 0; j < this._columnsArray.length; ++j) {
var text = node.data[this._columnsArray[j].identifier] || "";
if (text.length > widths[j])
widths[j] = text.length;
}
}
widths = this._autoSizeWidths(widths, minPercent, maxPercent);
for (var i = 0; i < this._columnsArray.length; ++i)
this._columnsArray[i].weight = widths[i];
this._columnWidthsInitialized = false;
this.updateWidths();
},
_enumerateChildren: function(rootNode, result, maxLevel)
{
if (!rootNode._isRoot)
result.push(rootNode);
if (!maxLevel)
return;
for (var i = 0; i < rootNode.children.length; ++i)
this._enumerateChildren(rootNode.children[i], result, maxLevel - 1);
return result;
},
onResize: function()
{
this.updateWidths();
},
// Updates the widths of the table, including the positions of the column
// resizers.
//
// IMPORTANT: This function MUST be called once after the element of the
// DataGrid is attached to its parent element and every subsequent time the
// width of the parent element is changed in order to make it possible to
// resize the columns.
//
// If this function is not called after the DataGrid is attached to its
// parent element, then the DataGrid's columns will not be resizable.
updateWidths: function()
{
var headerTableColumns = this._headerTableColumnGroup.children;
// Use container size to avoid changes of table width caused by change of column widths.
var tableWidth = this.element.offsetWidth - this._cornerWidth;
var numColumns = headerTableColumns.length - 1; // Do not process corner column.
// Do not attempt to use offsetes if we're not attached to the document tree yet.
if (!this._columnWidthsInitialized && this.element.offsetWidth) {
// Give all the columns initial widths now so that during a resize,
// when the two columns that get resized get a percent value for
// their widths, all the other columns already have percent values
// for their widths.
for (var i = 0; i < numColumns; i++) {
var columnWidth = this.headerTableBody.rows[0].cells[i].offsetWidth;
var column = this._visibleColumnsArray[i];
if (!column.weight)
column.weight = 100 * columnWidth / tableWidth;
}
this._columnWidthsInitialized = true;
}
this._applyColumnWeights();
},
/**
* @param {string} name
*/
setName: function(name)
{
this._columnWeightsSetting = WebInspector.settings.createSetting("dataGrid-" + name + "-columnWeights", {});
this._loadColumnWeights();
},
_loadColumnWeights: function()
{
if (!this._columnWeightsSetting)
return;
var weights = this._columnWeightsSetting.get();
for (var i = 0; i < this._columnsArray.length; ++i) {
var column = this._columnsArray[i];
var weight = weights[column.identifier];
if (weight)
column.weight = weight;
}
this._applyColumnWeights();
},
_saveColumnWeights: function()
{
if (!this._columnWeightsSetting)
return;
var weights = {};
for (var i = 0; i < this._columnsArray.length; ++i) {
var column = this._columnsArray[i];
weights[column.identifier] = column.weight;
}
this._columnWeightsSetting.set(weights);
},
wasShown: function()
{
this._loadColumnWeights();
},
willHide: function()
{
},
_applyColumnWeights: function()
{
var tableWidth = this.element.offsetWidth - this._cornerWidth;
if (tableWidth <= 0)
return;
var sumOfWeights = 0.0;
var fixedColumnWidths = [];
for (var i = 0; i < this._visibleColumnsArray.length; ++i) {
var column = this._visibleColumnsArray[i];
if (column.fixedWidth) {
var width = this._headerTableColumnGroup.children[i][WebInspector.DataGrid._preferredWidthSymbol] || this.headerTableBody.rows[0].cells[i].offsetWidth;
fixedColumnWidths[i] = width;
tableWidth -= width;
} else {
sumOfWeights += this._visibleColumnsArray[i].weight;
}
}
var sum = 0;
var lastOffset = 0;
for (var i = 0; i < this._visibleColumnsArray.length; ++i) {
var column = this._visibleColumnsArray[i];
var width;
if (column.fixedWidth) {
width = fixedColumnWidths[i];
} else {
sum += column.weight;
var offset = (sum * tableWidth / sumOfWeights) | 0;
width = offset - lastOffset;
lastOffset = offset;
}
this._setPreferredWidth(i, width);
}
this._positionResizers();
this.dispatchEventToListeners(WebInspector.DataGrid.Events.ColumnsResized);
},
/**
* @param {!Object.<string, boolean>} columnsVisibility
*/
setColumnsVisiblity: function(columnsVisibility)
{
this._visibleColumnsArray = [];
for (var i = 0; i < this._columnsArray.length; ++i) {
var column = this._columnsArray[i];
if (columnsVisibility[column.identifier || String(i)])
this._visibleColumnsArray.push(column);
}
this._refreshHeader();
this._applyColumnWeights();
var nodes = this._enumerateChildren(this.rootNode(), [], -1);
for (var i = 0; i < nodes.length; ++i)
nodes[i].refresh();
},
get scrollContainer()
{
return this._scrollContainer;
},
_positionResizers: function()
{
var headerTableColumns = this._headerTableColumnGroup.children;
var numColumns = headerTableColumns.length - 1; // Do not process corner column.
var left = [];
var resizers = this._resizers;
while (resizers.length > numColumns - 1)
resizers.pop().remove();
for (var i = 0; i < numColumns - 1; i++) {
// Get the width of the cell in the first (and only) row of the
// header table in order to determine the width of the column, since
// it is not possible to query a column for its width.
left[i] = (left[i-1] || 0) + this.headerTableBody.rows[0].cells[i].offsetWidth;
}
// Make n - 1 resizers for n columns.
for (var i = 0; i < numColumns - 1; i++) {
var resizer = resizers[i];
if (!resizer) {
// This is the first call to updateWidth, so the resizers need
// to be created.
resizer = createElement("div");
resizer.__index = i;
resizer.classList.add("data-grid-resizer");
// This resizer is associated with the column to its right.
WebInspector.installDragHandle(resizer, this._startResizerDragging.bind(this), this._resizerDragging.bind(this), this._endResizerDragging.bind(this), "col-resize");
this.element.appendChild(resizer);
resizers.push(resizer);
}
if (resizer.__position !== left[i]) {
resizer.__position = left[i];
resizer.style.left = left[i] + "px";
}
}
},
addCreationNode: function(hasChildren)
{
if (this.creationNode)
this.creationNode.makeNormal();
var emptyData = {};
for (var column in this._columns)
emptyData[column] = null;
this.creationNode = new WebInspector.CreationDataGridNode(emptyData, hasChildren);
this.rootNode().appendChild(this.creationNode);
},
_keyDown: function(event)
{
if (!this.selectedNode || event.shiftKey || event.metaKey || event.ctrlKey || this._editing)
return;
var handled = false;
var nextSelectedNode;
if (event.keyIdentifier === "Up" && !event.altKey) {
nextSelectedNode = this.selectedNode.traversePreviousNode(true);
while (nextSelectedNode && !nextSelectedNode.selectable)
nextSelectedNode = nextSelectedNode.traversePreviousNode(true);
handled = nextSelectedNode ? true : false;
} else if (event.keyIdentifier === "Down" && !event.altKey) {
nextSelectedNode = this.selectedNode.traverseNextNode(true);
while (nextSelectedNode && !nextSelectedNode.selectable)
nextSelectedNode = nextSelectedNode.traverseNextNode(true);
handled = nextSelectedNode ? true : false;
} else if (event.keyIdentifier === "Left") {
if (this.selectedNode.expanded) {
if (event.altKey)
this.selectedNode.collapseRecursively();
else
this.selectedNode.collapse();
handled = true;
} else if (this.selectedNode.parent && !this.selectedNode.parent._isRoot) {
handled = true;
if (this.selectedNode.parent.selectable) {
nextSelectedNode = this.selectedNode.parent;
handled = nextSelectedNode ? true : false;
} else if (this.selectedNode.parent)
this.selectedNode.parent.collapse();
}
} else if (event.keyIdentifier === "Right") {
if (!this.selectedNode.revealed) {
this.selectedNode.reveal();
handled = true;
} else if (this.selectedNode.hasChildren) {
handled = true;
if (this.selectedNode.expanded) {
nextSelectedNode = this.selectedNode.children[0];
handled = nextSelectedNode ? true : false;
} else {
if (event.altKey)
this.selectedNode.expandRecursively();
else
this.selectedNode.expand();
}
}
} else if (event.keyCode === 8 || event.keyCode === 46) {
if (this._deleteCallback) {
handled = true;
this._deleteCallback(this.selectedNode);
}
} else if (isEnterKey(event)) {
if (this._editCallback) {
handled = true;
this._startEditing(this.selectedNode._element.children[this._nextEditableColumn(-1)]);
}
}
if (nextSelectedNode) {
nextSelectedNode.reveal();
nextSelectedNode.select();
}
if (handled)
event.consume(true);
},
/**
* @param {?WebInspector.DataGridNode} root
* @param {boolean} onlyAffectsSubtree
*/
updateSelectionBeforeRemoval: function(root, onlyAffectsSubtree)
{
var ancestor = this.selectedNode;
while (ancestor && ancestor !== root)
ancestor = ancestor.parent;
// Selection is not in the subtree being deleted.
if (!ancestor)
return;
var nextSelectedNode;
// Skip subtree being deleted when looking for the next selectable node.
for (ancestor = root; ancestor && !ancestor.nextSibling; ancestor = ancestor.parent) { }
if (ancestor)
nextSelectedNode = ancestor.nextSibling;
while (nextSelectedNode && !nextSelectedNode.selectable)
nextSelectedNode = nextSelectedNode.traverseNextNode(true);
if (!nextSelectedNode || nextSelectedNode.isCreationNode) {
nextSelectedNode = root.traversePreviousNode(true);
while (nextSelectedNode && !nextSelectedNode.selectable)
nextSelectedNode = nextSelectedNode.traversePreviousNode(true);
}
if (nextSelectedNode) {
nextSelectedNode.reveal();
nextSelectedNode.select();
} else {
this.selectedNode.deselect();
}
},
/**
* @param {!Node} target
* @return {?WebInspector.DataGridNode}
*/
dataGridNodeFromNode: function(target)
{
var rowElement = target.enclosingNodeOrSelfWithNodeName("tr");
return rowElement && rowElement._dataGridNode;
},
/**
* @param {!Node} target
* @return {?string}
*/
columnIdentifierFromNode: function(target)
{
var cellElement = target.enclosingNodeOrSelfWithNodeName("td");
return cellElement && cellElement.columnIdentifier_;
},
_clickInHeaderCell: function(event)
{
var cell = event.target.enclosingNodeOrSelfWithNodeName("th");
if (!cell || (cell.columnIdentifier === undefined) || !cell.classList.contains("sortable"))
return;
var sortOrder = WebInspector.DataGrid.Order.Ascending;
if ((cell === this._sortColumnCell) && this.isSortOrderAscending())
sortOrder = WebInspector.DataGrid.Order.Descending;
if (this._sortColumnCell)
this._sortColumnCell.classList.remove(WebInspector.DataGrid.Order.Ascending, WebInspector.DataGrid.Order.Descending);
this._sortColumnCell = cell;
cell.classList.add(sortOrder);
this.dispatchEventToListeners(WebInspector.DataGrid.Events.SortingChanged);
},
/**
* @param {string} columnIdentifier
* @param {!WebInspector.DataGrid.Order} sortOrder
*/
markColumnAsSortedBy: function(columnIdentifier, sortOrder)
{
if (this._sortColumnCell)
this._sortColumnCell.classList.remove(WebInspector.DataGrid.Order.Ascending, WebInspector.DataGrid.Order.Descending);
this._sortColumnCell = this._headerTableHeaders[columnIdentifier];
this._sortColumnCell.classList.add(sortOrder);
},
/**
* @param {string} columnIdentifier
* @return {!Element}
*/
headerTableHeader: function(columnIdentifier)
{
return this._headerTableHeaders[columnIdentifier];
},
_mouseDownInDataTable: function(event)
{
var gridNode = this.dataGridNodeFromNode(event.target);
if (!gridNode || !gridNode.selectable)
return;
if (gridNode.isEventWithinDisclosureTriangle(event))
return;
var columnIdentifier = this.columnIdentifierFromNode(event.target);
if (columnIdentifier && this._columns[columnIdentifier].nonSelectable)
return;
if (event.metaKey) {
if (gridNode.selected)
gridNode.deselect();
else
gridNode.select();
} else
gridNode.select();
},
_contextMenuInDataTable: function(event)
{
var contextMenu = new WebInspector.ContextMenu(event);
var gridNode = this.dataGridNodeFromNode(event.target);
if (this._refreshCallback && (!gridNode || gridNode !== this.creationNode))
contextMenu.appendItem(WebInspector.UIString("Refresh"), this._refreshCallback.bind(this));
if (gridNode && gridNode.selectable && !gridNode.isEventWithinDisclosureTriangle(event)) {
if (this._editCallback) {
if (gridNode === this.creationNode)
contextMenu.appendItem(WebInspector.UIString.capitalize("Add ^new"), this._startEditing.bind(this, event.target));
else {
var columnIdentifier = this.columnIdentifierFromNode(event.target);
if (columnIdentifier && this._columns[columnIdentifier].editable)
contextMenu.appendItem(WebInspector.UIString("Edit \"%s\"", this._columns[columnIdentifier].title), this._startEditing.bind(this, event.target));
}
}
if (this._deleteCallback && gridNode !== this.creationNode)
contextMenu.appendItem(WebInspector.UIString.capitalize("Delete"), this._deleteCallback.bind(this, gridNode));
if (this._contextMenuCallback)
this._contextMenuCallback(contextMenu, gridNode);
}
contextMenu.show();
},
_clickInDataTable: function(event)
{
var gridNode = this.dataGridNodeFromNode(event.target);
if (!gridNode || !gridNode.hasChildren)
return;
if (!gridNode.isEventWithinDisclosureTriangle(event))
return;
if (gridNode.expanded) {
if (event.altKey)
gridNode.collapseRecursively();
else
gridNode.collapse();
} else {
if (event.altKey)
gridNode.expandRecursively();
else
gridNode.expand();
}
},
/**
* @param {!WebInspector.DataGrid.ResizeMethod} method
*/
setResizeMethod: function(method)
{
this._resizeMethod = method;
},
/**
* @return {boolean}
*/
_startResizerDragging: function(event)
{
this._currentResizer = event.target;
return true;
},
_resizerDragging: function(event)
{
var resizer = this._currentResizer;
if (!resizer)
return;
// Constrain the dragpoint to be within the containing div of the
// datagrid.
var dragPoint = event.clientX - this.element.totalOffsetLeft();
var firstRowCells = this.headerTableBody.rows[0].cells;
var leftEdgeOfPreviousColumn = 0;
// Constrain the dragpoint to be within the space made up by the
// column directly to the left and the column directly to the right.
var leftCellIndex = resizer.__index;
var rightCellIndex = leftCellIndex + 1;
for (var i = 0; i < leftCellIndex; i++)
leftEdgeOfPreviousColumn += firstRowCells[i].offsetWidth;
// Differences for other resize methods
if (this._resizeMethod === WebInspector.DataGrid.ResizeMethod.Last) {
rightCellIndex = this._resizers.length;
} else if (this._resizeMethod === WebInspector.DataGrid.ResizeMethod.First) {
leftEdgeOfPreviousColumn += firstRowCells[leftCellIndex].offsetWidth - firstRowCells[0].offsetWidth;
leftCellIndex = 0;
}
var rightEdgeOfNextColumn = leftEdgeOfPreviousColumn + firstRowCells[leftCellIndex].offsetWidth + firstRowCells[rightCellIndex].offsetWidth;
// Give each column some padding so that they don't disappear.
var leftMinimum = leftEdgeOfPreviousColumn + this.ColumnResizePadding;
var rightMaximum = rightEdgeOfNextColumn - this.ColumnResizePadding;
if (leftMinimum > rightMaximum)
return;
dragPoint = Number.constrain(dragPoint, leftMinimum, rightMaximum);
var position = (dragPoint - this.CenterResizerOverBorderAdjustment);
resizer.__position = position;
resizer.style.left = position + "px";
this._setPreferredWidth(leftCellIndex, dragPoint - leftEdgeOfPreviousColumn);
this._setPreferredWidth(rightCellIndex, rightEdgeOfNextColumn - dragPoint);
var leftColumn = this._visibleColumnsArray[leftCellIndex];
var rightColumn = this._visibleColumnsArray[rightCellIndex];
if (leftColumn.weight || rightColumn.weight) {
var sumOfWeights = leftColumn.weight + rightColumn.weight;
var delta = rightEdgeOfNextColumn - leftEdgeOfPreviousColumn;
leftColumn.weight = (dragPoint - leftEdgeOfPreviousColumn) * sumOfWeights / delta;
rightColumn.weight = (rightEdgeOfNextColumn - dragPoint) * sumOfWeights / delta;
}
this._positionResizers();
event.preventDefault();
this.dispatchEventToListeners(WebInspector.DataGrid.Events.ColumnsResized);
},
/**
* @param {number} columnIndex
* @param {number} width
*/
_setPreferredWidth: function(columnIndex, width)
{
var pxWidth = width + "px";
this._headerTableColumnGroup.children[columnIndex][WebInspector.DataGrid._preferredWidthSymbol] = width;
this._headerTableColumnGroup.children[columnIndex].style.width = pxWidth;
this._dataTableColumnGroup.children[columnIndex].style.width = pxWidth;
},
/**
* @param {string} columnId
* @return {number}
*/
columnOffset: function(columnId)
{
if (!this.element.offsetWidth)
return 0;
for (var i = 1; i < this._visibleColumnsArray.length; ++i) {
if (columnId === this._visibleColumnsArray[i].identifier) {
if (this._resizers[i - 1])
return this._resizers[i - 1].__position;
}
}
return 0;
},
_endResizerDragging: function(event)
{
this._currentResizer = null;
this._saveColumnWeights();
this.dispatchEventToListeners(WebInspector.DataGrid.Events.ColumnsResized);
},
/**
* @return {!WebInspector.DataGridWidget}
*/
asWidget: function()
{
if (!this._dataGridWidget)
this._dataGridWidget = new WebInspector.DataGridWidget(this);
return this._dataGridWidget;
},
ColumnResizePadding: 24,
CenterResizerOverBorderAdjustment: 3,
__proto__: WebInspector.Object.prototype
}
/** @enum {string} */
WebInspector.DataGrid.ResizeMethod = {
Nearest: "nearest",
First: "first",
Last: "last"
}
/**
* @constructor
* @extends {WebInspector.Object}
* @param {?Object.<string, *>=} data
* @param {boolean=} hasChildren
*/
WebInspector.DataGridNode = function(data, hasChildren)
{
/** @type {?Element} */
this._element = null;
/** @type {boolean} */
this._expanded = false;
/** @type {boolean} */
this._selected = false;
/** @type {number|undefined} */
this._depth;
/** @type {boolean|undefined} */
this._revealed;
/** @type {boolean} */
this._attached = false;
/** @type {?{parent: !WebInspector.DataGridNode, index: number}} */
this._savedPosition = null;
/** @type {boolean} */
this._shouldRefreshChildren = true;
/** @type {!Object.<string, *>} */
this._data = data || {};
/** @type {boolean} */
this.hasChildren = hasChildren || false;
/** @type {!Array.<!WebInspector.DataGridNode>} */
this.children = [];
/** @type {?WebInspector.DataGrid} */
this.dataGrid = null;
/** @type {?WebInspector.DataGridNode} */
this.parent = null;
/** @type {?WebInspector.DataGridNode} */
this.previousSibling = null;
/** @type {?WebInspector.DataGridNode} */
this.nextSibling = null;
/** @type {number} */
this.disclosureToggleWidth = 10;
}
WebInspector.DataGridNode.prototype = {
/** @type {boolean} */
selectable: true,
/** @type {boolean} */
_isRoot: false,
/**
* @return {!Element}
*/
element: function()
{
if (!this._element) {
this.createElement();
this.createCells();
}
return /** @type {!Element} */ (this._element);
},
/**
* @protected
*/
createElement: function()
{
this._element = createElement("tr");
this._element._dataGridNode = this;
if (this.hasChildren)
this._element.classList.add("parent");
if (this.expanded)
this._element.classList.add("expanded");
if (this.selected)
this._element.classList.add("selected");
if (this.revealed)
this._element.classList.add("revealed");
},
/**
* @protected
*/
createCells: function()
{
this._element.removeChildren();
var columnsArray = this.dataGrid._visibleColumnsArray;
for (var i = 0; i < columnsArray.length; ++i)
this._element.appendChild(this.createCell(columnsArray[i].identifier || String(i)));
this._element.appendChild(this._createTDWithClass("corner"));
},
get data()
{
return this._data;
},
set data(x)
{
this._data = x || {};
this.refresh();
},
get revealed()
{
if (this._revealed !== undefined)
return this._revealed;
var currentAncestor = this.parent;
while (currentAncestor && !currentAncestor._isRoot) {
if (!currentAncestor.expanded) {
this._revealed = false;
return false;
}
currentAncestor = currentAncestor.parent;
}
this._revealed = true;
return true;
},
set hasChildren(x)
{
if (this._hasChildren === x)
return;
this._hasChildren = x;
if (!this._element)
return;
this._element.classList.toggle("parent", this._hasChildren);
this._element.classList.toggle("expanded", this._hasChildren && this.expanded);
},
get hasChildren()
{
return this._hasChildren;
},
set revealed(x)
{
if (this._revealed === x)
return;
this._revealed = x;
if (this._element)
this._element.classList.toggle("revealed", this._revealed);
for (var i = 0; i < this.children.length; ++i)
this.children[i].revealed = x && this.expanded;
},
/**
* @return {number}
*/
get depth()
{
if (this._depth !== undefined)
return this._depth;
if (this.parent && !this.parent._isRoot)
this._depth = this.parent.depth + 1;
else
this._depth = 0;
return this._depth;
},
get leftPadding()
{
return this.depth * this.dataGrid.indentWidth;
},
get shouldRefreshChildren()
{
return this._shouldRefreshChildren;
},
set shouldRefreshChildren(x)
{
this._shouldRefreshChildren = x;
if (x && this.expanded)
this.expand();
},
get selected()
{
return this._selected;
},
set selected(x)
{
if (x)
this.select();
else
this.deselect();
},
get expanded()
{
return this._expanded;
},
/**
* @param {boolean} x
*/
set expanded(x)
{
if (x)
this.expand();
else
this.collapse();
},
refresh: function()
{
if (!this.dataGrid)
this._element = null;
if (!this._element)
return;
this.createCells();
},
/**
* @param {string} className
* @return {!Element}
*/
_createTDWithClass: function(className)
{
var cell = createElementWithClass("td", className);
var cellClass = this.dataGrid._cellClass;
if (cellClass)
cell.classList.add(cellClass);
return cell;
},
/**
* @param {string} columnIdentifier
* @return {!Element}
*/
createTD: function(columnIdentifier)
{
var cell = this._createTDWithClass(columnIdentifier + "-column");
cell.columnIdentifier_ = columnIdentifier;
var alignment = this.dataGrid._columns[columnIdentifier].align;
if (alignment)
cell.classList.add(alignment);
if (columnIdentifier === this.dataGrid.disclosureColumnIdentifier) {
cell.classList.add("disclosure");
if (this.leftPadding)
cell.style.setProperty("padding-left", this.leftPadding + "px");
}
return cell;
},
/**
* @param {string} columnIdentifier
* @return {!Element}
*/
createCell: function(columnIdentifier)
{
var cell = this.createTD(columnIdentifier);
var data = this.data[columnIdentifier];
if (data instanceof Node) {
cell.appendChild(data);
} else {
cell.textContent = data;
if (this.dataGrid._columns[columnIdentifier].longText)
cell.title = data;
}
return cell;
},
/**
* @return {number}
*/
nodeSelfHeight: function()
{
return 16;
},
/**
* @param {!WebInspector.DataGridNode} child
*/
appendChild: function(child)
{
this.insertChild(child, this.children.length);
},
/**
* @param {!WebInspector.DataGridNode} child
* @param {number} index
*/
insertChild: function(child, index)
{
if (!child)
throw("insertChild: Node can't be undefined or null.");
if (child.parent === this) {
var currentIndex = this.children.indexOf(child);
if (currentIndex < 0)
console.assert(false, "Inconsistent DataGrid state");
if (currentIndex === index)
return;
if (currentIndex < index)
--index;
}
child.remove();
this.children.splice(index, 0, child);
this.hasChildren = true;
child.parent = this;
child.dataGrid = this.dataGrid;
child.recalculateSiblings(index);
child._depth = undefined;
child._revealed = undefined;
child._attached = false;
child._shouldRefreshChildren = true;
var current = child.children[0];
while (current) {
current.dataGrid = this.dataGrid;
current._depth = undefined;
current._revealed = undefined;
current._attached = false;
current._shouldRefreshChildren = true;
current = current.traverseNextNode(false, child, true);
}
if (this.expanded)
child._attach();
if (!this.revealed)
child.revealed = false;
},
remove: function()
{
if (this.parent)
this.parent.removeChild(this);
},
/**
* @param {!WebInspector.DataGridNode} child
*/
removeChild: function(child)
{
if (!child)
throw("removeChild: Node can't be undefined or null.");
if (child.parent !== this)
throw("removeChild: Node is not a child of this node.");
if (this.dataGrid)
this.dataGrid.updateSelectionBeforeRemoval(child, false);
child._detach();
this.children.remove(child, true);
if (child.previousSibling)
child.previousSibling.nextSibling = child.nextSibling;
if (child.nextSibling)
child.nextSibling.previousSibling = child.previousSibling;
child.dataGrid = null;
child.parent = null;
child.nextSibling = null;
child.previousSibling = null;
if (this.children.length <= 0)
this.hasChildren = false;
},
removeChildren: function()
{
if (this.dataGrid)
this.dataGrid.updateSelectionBeforeRemoval(this, true);
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i];
child._detach();
child.dataGrid = null;
child.parent = null;
child.nextSibling = null;
child.previousSibling = null;
}
this.children = [];
this.hasChildren = false;
},
/**
* @param {number} myIndex
*/
recalculateSiblings: function(myIndex)
{
if (!this.parent)
return;
var previousChild = this.parent.children[myIndex - 1] || null;
if (previousChild)
previousChild.nextSibling = this;
this.previousSibling = previousChild;
var nextChild = this.parent.children[myIndex + 1] || null;
if (nextChild)
nextChild.previousSibling = this;
this.nextSibling = nextChild;
},
collapse: function()
{
if (this._isRoot)
return;
if (this._element)
this._element.classList.remove("expanded");
this._expanded = false;
for (var i = 0; i < this.children.length; ++i)
this.children[i].revealed = false;
},
collapseRecursively: function()
{
var item = this;
while (item) {
if (item.expanded)
item.collapse();
item = item.traverseNextNode(false, this, true);
}
},
populate: function() { },
expand: function()
{
if (!this.hasChildren || this.expanded)
return;
if (this._isRoot)
return;
if (this.revealed && !this._shouldRefreshChildren)
for (var i = 0; i < this.children.length; ++i)
this.children[i].revealed = true;
if (this._shouldRefreshChildren) {
for (var i = 0; i < this.children.length; ++i)
this.children[i]._detach();
this.populate();
if (this._attached) {
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i];
if (this.revealed)
child.revealed = true;
child._attach();
}
}
this._shouldRefreshChildren = false;
}
if (this._element)
this._element.classList.add("expanded");
this._expanded = true;
},
expandRecursively: function()
{
var item = this;
while (item) {
item.expand();
item = item.traverseNextNode(false, this);
}
},
reveal: function()
{
if (this._isRoot)
return;
var currentAncestor = this.parent;
while (currentAncestor && !currentAncestor._isRoot) {
if (!currentAncestor.expanded)
currentAncestor.expand();
currentAncestor = currentAncestor.parent;
}
this.element().scrollIntoViewIfNeeded(false);
},
/**
* @param {boolean=} supressSelectedEvent
*/
select: function(supressSelectedEvent)
{
if (!this.dataGrid || !this.selectable || this.selected)
return;
if (this.dataGrid.selectedNode)
this.dataGrid.selectedNode.deselect();
this._selected = true;
this.dataGrid.selectedNode = this;
if (this._element)
this._element.classList.add("selected");
if (!supressSelectedEvent)
this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Events.SelectedNode);
},
revealAndSelect: function()
{
if (this._isRoot)
return;
this.reveal();
this.select();
},
/**
* @param {boolean=} supressDeselectedEvent
*/
deselect: function(supressDeselectedEvent)
{
if (!this.dataGrid || this.dataGrid.selectedNode !== this || !this.selected)
return;
this._selected = false;
this.dataGrid.selectedNode = null;
if (this._element)
this._element.classList.remove("selected");
if (!supressDeselectedEvent)
this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Events.DeselectedNode);
},
/**
* @param {boolean} skipHidden
* @param {?WebInspector.DataGridNode=} stayWithin
* @param {boolean=} dontPopulate
* @param {!Object=} info
* @return {?WebInspector.DataGridNode}
*/
traverseNextNode: function(skipHidden, stayWithin, dontPopulate, info)
{
if (!dontPopulate && this.hasChildren)
this.populate();
if (info)
info.depthChange = 0;
var node = (!skipHidden || this.revealed) ? this.children[0] : null;
if (node && (!skipHidden || this.expanded)) {
if (info)
info.depthChange = 1;
return node;
}
if (this === stayWithin)
return null;
node = (!skipHidden || this.revealed) ? this.nextSibling : null;
if (node)
return node;
node = this;
while (node && !node._isRoot && !((!skipHidden || node.revealed) ? node.nextSibling : null) && node.parent !== stayWithin) {
if (info)
info.depthChange -= 1;
node = node.parent;
}
if (!node)
return null;
return (!skipHidden || node.revealed) ? node.nextSibling : null;
},
/**
* @param {boolean} skipHidden
* @param {boolean=} dontPopulate
* @return {?WebInspector.DataGridNode}
*/
traversePreviousNode: function(skipHidden, dontPopulate)
{
var node = (!skipHidden || this.revealed) ? this.previousSibling : null;
if (!dontPopulate && node && node.hasChildren)
node.populate();
while (node && ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null)) {
if (!dontPopulate && node.hasChildren)
node.populate();
node = ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null);
}
if (node)
return node;
if (!this.parent || this.parent._isRoot)
return null;
return this.parent;
},
/**
* @return {boolean}
*/
isEventWithinDisclosureTriangle: function(event)
{
if (!this.hasChildren)
return false;
var cell = event.target.enclosingNodeOrSelfWithNodeName("td");
if (!cell || !cell.classList.contains("disclosure"))
return false;
var left = cell.totalOffsetLeft() + this.leftPadding;
return event.pageX >= left && event.pageX <= left + this.disclosureToggleWidth;
},
_attach: function()
{
if (!this.dataGrid || this._attached)
return;
this._attached = true;
var previousNode = this.traversePreviousNode(true, true);
var previousElement = previousNode ? previousNode.element() : this.dataGrid._topFillerRow;
this.dataGrid.dataTableBody.insertBefore(this.element(), previousElement.nextSibling);
if (this.expanded)
for (var i = 0; i < this.children.length; ++i)
this.children[i]._attach();
},
_detach: function()
{
if (!this._attached)
return;
this._attached = false;
if (this._element)
this._element.remove();
for (var i = 0; i < this.children.length; ++i)
this.children[i]._detach();
this.wasDetached();
},
wasDetached: function()
{
},
savePosition: function()
{
if (this._savedPosition)
return;
if (!this.parent)
throw("savePosition: Node must have a parent.");
this._savedPosition = {
parent: this.parent,
index: this.parent.children.indexOf(this)
};
},
restorePosition: function()
{
if (!this._savedPosition)
return;
if (this.parent !== this._savedPosition.parent)
this._savedPosition.parent.insertChild(this, this._savedPosition.index);
this._savedPosition = null;
},
__proto__: WebInspector.Object.prototype
}
/**
* @constructor
* @extends {WebInspector.DataGridNode}
*/
WebInspector.CreationDataGridNode = function(data, hasChildren)
{
WebInspector.DataGridNode.call(this, data, hasChildren);
/** @type {boolean} */
this.isCreationNode = true;
}
WebInspector.CreationDataGridNode.prototype = {
makeNormal: function()
{
this.isCreationNode = false;
},
__proto__: WebInspector.DataGridNode.prototype
}
/**
* @constructor
* @extends {WebInspector.VBox}
* @param {!WebInspector.DataGrid} dataGrid
*/
WebInspector.DataGridWidget = function(dataGrid)
{
WebInspector.VBox.call(this);
this._dataGrid = dataGrid;
this.element.appendChild(dataGrid.element);
}
WebInspector.DataGridWidget.prototype = {
/**
* @override
*/
wasShown: function()
{
this._dataGrid.wasShown();
},
/**
* @override
*/
willHide: function()
{
this._dataGrid.willHide();
},
/**
* @override
*/
onResize: function()
{
this._dataGrid.onResize();
},
/**
* @override
* @return {!Array.<!Element>}
*/
elementsToRestoreScrollPositionsFor: function()
{
return [ this._dataGrid._scrollContainer ];
},
/**
* @override
*/
detachChildWidgets: function()
{
WebInspector.Widget.prototype.detachChildWidgets.call(this);
for (var dataGrid of this._dataGrids)
this.element.removeChild(dataGrid.element);
this._dataGrids = [];
},
__proto__: WebInspector.VBox.prototype
}
| highweb-project/highweb-webcl-html5spec | third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js | JavaScript | bsd-3-clause | 61,392 |
function Processor(options) {
options = options || {};
this.processor = {};
this.persistent = options.persist;
}
Processor.prototype.setStrategy = function(stringProcessor) {
this.processor = stringProcessor;
};
Processor.prototype.init = function(ctx) {
this.processor.init(ctx);
};
Processor.prototype.processString = function(ctx, contents, relativePath) {
return this.processor.processString(ctx, contents, relativePath);
};
module.exports = Processor;
| jordansmith42/ember-widgets-addon | node_modules/ember-cli-qunit/node_modules/broccoli-jshint/node_modules/broccoli-persistent-filter/lib/processor.js | JavaScript | mit | 473 |
YUI.add('datatable-datasource', function (Y, NAME) {
/**
* Plugs DataTable with DataSource integration.
*
* @module datatable
* @submodule datatable-datasource
*/
/**
* Adds DataSource integration to DataTable.
* @class Plugin.DataTableDataSource
* @extends Plugin.Base
*/
function DataTableDataSource() {
DataTableDataSource.superclass.constructor.apply(this, arguments);
}
/////////////////////////////////////////////////////////////////////////////
//
// STATIC PROPERTIES
//
/////////////////////////////////////////////////////////////////////////////
Y.mix(DataTableDataSource, {
/**
* The namespace for the plugin. This will be the property on the host which
* references the plugin instance.
*
* @property NS
* @type String
* @static
* @final
* @value "datasource"
*/
NS: "datasource",
/**
* Class name.
*
* @property NAME
* @type String
* @static
* @final
* @value "dataTableDataSource"
*/
NAME: "dataTableDataSource",
/////////////////////////////////////////////////////////////////////////////
//
// ATTRIBUTES
//
/////////////////////////////////////////////////////////////////////////////
ATTRS: {
/**
* @attribute datasource
* @description Pointer to DataSource instance.
* @type {DataSource}
*/
datasource: {
setter: "_setDataSource"
},
/**
* @attribute initialRequest
* @description Request sent to DataSource immediately upon initialization.
* @type Object
*/
initialRequest: {
setter: "_setInitialRequest"
}
}
});
/////////////////////////////////////////////////////////////////////////////
//
// PROTOTYPE
//
/////////////////////////////////////////////////////////////////////////////
Y.extend(DataTableDataSource, Y.Plugin.Base, {
/////////////////////////////////////////////////////////////////////////////
//
// ATTRIBUTE HELPERS
//
/////////////////////////////////////////////////////////////////////////////
/**
* @method _setDataSource
* @description Creates new DataSource instance if one is not provided.
* @param ds {Object|DataSource}
* @return {DataSource}
* @private
*/
_setDataSource: function(ds) {
return ds || new Y.DataSource.Local(ds);
},
/**
* @method _setInitialRequest
* @description Sends request to DataSource.
* @param request {Object} DataSource request.
* @private
*/
_setInitialRequest: function(/* request */) {
},
/////////////////////////////////////////////////////////////////////////////
//
// METHODS
//
/////////////////////////////////////////////////////////////////////////////
/**
* Initializer.
*
* @method initializer
* @param config {Object} Config object.
* @private
*/
initializer: function(config) {
if(!Y.Lang.isUndefined(config.initialRequest)) {
this.load({request:config.initialRequest});
}
},
////////////////////////////////////////////////////////////////////////////
//
// DATA
//
////////////////////////////////////////////////////////////////////////////
/**
* Load data by calling DataSource's sendRequest() method under the hood.
*
* @method load
* @param config {object} Optional configuration parameters:
*
* <dl>
* <dt>request</dt><dd>Pass in a new request, or initialRequest is used.</dd>
* <dt>callback</dt><dd>Pass in DataSource callback object, or the following default is used:
* <dl>
* <dt>success</dt><dd>datatable.onDataReturnInitializeTable</dd>
* <dt>failure</dt><dd>datatable.onDataReturnInitializeTable</dd>
* <dt>scope</dt><dd>datatable</dd>
* <dt>argument</dt><dd>datatable.getState()</dd>
* </dl>
* </dd>
* <dt>datasource</dt><dd>Pass in a new DataSource instance to override the current DataSource for this transaction.</dd>
* </dl>
*/
load: function(config) {
config = config || {};
config.request = config.request || this.get("initialRequest");
config.callback = config.callback || {
success: Y.bind(this.onDataReturnInitializeTable, this),
failure: Y.bind(this.onDataReturnInitializeTable, this),
argument: this.get("host").get("state") //TODO
};
var ds = (config.datasource || this.get("datasource"));
if(ds) {
ds.sendRequest(config);
}
},
/**
* Callback function passed to DataSource's sendRequest() method populates
* an entire DataTable with new data, clearing previous data, if any.
*
* @method onDataReturnInitializeTable
* @param e {EventFacade} DataSource Event Facade object.
*/
onDataReturnInitializeTable : function(e) {
var records = (e.response && e.response.results) || [];
this.get("host").set("data", records);
}
});
Y.namespace("Plugin").DataTableDataSource = DataTableDataSource;
}, 'patched-v3.16.0', {"requires": ["datatable-base", "plugin", "datasource-local"]});
| marclundgren/marclundgren.github.io | node-checkpoints/build/datatable-datasource/datatable-datasource.js | JavaScript | mit | 5,257 |
"use strict";
/*global alert: true, ODSA */
(function ($) {
function randomGraphGen(graph, numberOfNodes, numberOfEdges) {
var one, two;
var nodes =[];
//var g = jsav.ds.graph({width: 600, height: 400, directed: true});
for(var i = 0; i < numberOfNodes; i++) {
graph.addNode(i);
console.log("node " + i);
}
nodes = graph.nodes();
console.log("size " + nodes.length);
console.log("array nodes " + nodes[3].value());
for(var i = 0; i < numberOfEdges;) {
one = JSAV.utils.rand.numKey(0, numberOfNodes);
two = JSAV.utils.rand.numKey(0, numberOfNodes);
//one = randomNumber(0, numberOfNodes);
//two = randomNumber(0, numberOfNodes);
if(one !== two) {
if(!(graph.hasEdge(nodes[one], nodes[two]))) {
graph.addEdge(nodes[one], nodes[two]);
i++;
console.log("Edge " + one + " to " + two);
}
}
}
return graph;
//graph.layout();
//graph.recorded();
}
ODSA.AV.randomGraphGen = randomGraphGen;
}(jQuery));
| hosamshahin/OpenDSA | AV/graphUtils.js | JavaScript | mit | 1,004 |
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>group: exclude
define([
"require",
"./widgets/loader",
"./events/navigate",
"./navigation/path",
"./navigation/history",
"./navigation/navigator",
"./navigation/method",
"./transitions/handlers",
"./transitions/visuals",
"./jquery.mobile.navigation",
"./jquery.mobile.degradeInputs",
"./widgets/page.dialog",
"./widgets/dialog",
"./widgets/collapsible",
"./widgets/collapsibleSet",
"./jquery.mobile.fieldContain",
"./jquery.mobile.grid",
"./widgets/navbar",
"./widgets/listview",
"./widgets/listview.autodividers",
"./widgets/listview.hidedividers",
"./jquery.mobile.nojs",
"./widgets/forms/checkboxradio",
"./widgets/forms/button",
"./widgets/forms/slider",
"./widgets/forms/slider.tooltip",
"./widgets/forms/flipswitch",
"./widgets/forms/rangeslider",
"./widgets/forms/textinput",
"./widgets/forms/clearButton",
"./widgets/forms/autogrow",
"./widgets/forms/select.custom",
"./widgets/forms/select",
"./jquery.mobile.buttonMarkup",
"./widgets/controlgroup",
"./jquery.mobile.links",
"./widgets/toolbar",
"./widgets/fixedToolbar",
"./widgets/fixedToolbar.workarounds",
"./widgets/popup",
"./widgets/popup.arrow",
"./widgets/panel",
"./widgets/table",
"./widgets/table.columntoggle",
"./widgets/table.reflow",
"./widgets/filterable",
"./widgets/filterable.backcompat",
"./widgets/jquery.ui.tabs",
"./widgets/tabs",
"./jquery.mobile.zoom",
"./jquery.mobile.zoom.iosorientationfix"
], function( require ) {
require( [ "./jquery.mobile.init" ], function() {} );
});
//>>excludeEnd("jqmBuildExclude");
| ericsteele/retrospec.js | test/input/projects/jquery-mobile/rev-1.4.0.x-143bdae/js/jquery.mobile.js | JavaScript | mit | 1,616 |
/*! algoliasearch 3.32.1 | © 2014, 2015 Algolia SAS | github.com/algolia/algoliasearch-client-js */
(function(f){var g;if(typeof window!=='undefined'){g=window}else if(typeof self!=='undefined'){g=self}g.ALGOLIA_MIGRATION_LAYER=f()})(function(){var define,module,exports;return (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){
module.exports = function load (src, opts, cb) {
var head = document.head || document.getElementsByTagName('head')[0]
var script = document.createElement('script')
if (typeof opts === 'function') {
cb = opts
opts = {}
}
opts = opts || {}
cb = cb || function() {}
script.type = opts.type || 'text/javascript'
script.charset = opts.charset || 'utf8';
script.async = 'async' in opts ? !!opts.async : true
script.src = src
if (opts.attrs) {
setAttributes(script, opts.attrs)
}
if (opts.text) {
script.text = '' + opts.text
}
var onend = 'onload' in script ? stdOnEnd : ieOnEnd
onend(script, cb)
// some good legacy browsers (firefox) fail the 'in' detection above
// so as a fallback we always set onload
// old IE will ignore this and new IE will set onload
if (!script.onload) {
stdOnEnd(script, cb);
}
head.appendChild(script)
}
function setAttributes(script, attrs) {
for (var attr in attrs) {
script.setAttribute(attr, attrs[attr]);
}
}
function stdOnEnd (script, cb) {
script.onload = function () {
this.onerror = this.onload = null
cb(null, script)
}
script.onerror = function () {
// this.onload = null here is necessary
// because even IE9 works not like others
this.onerror = this.onload = null
cb(new Error('Failed to load ' + this.src), script)
}
}
function ieOnEnd (script, cb) {
script.onreadystatechange = function () {
if (this.readyState != 'complete' && this.readyState != 'loaded') return
this.onreadystatechange = null
cb(null, script) // there is no way to catch loading errors in IE8
}
}
},{}],2:[function(require,module,exports){
'use strict';
// this module helps finding if the current page is using
// the cdn.jsdelivr.net/algoliasearch/latest/$BUILDNAME.min.js version
module.exports = isUsingLatest;
function isUsingLatest(buildName) {
var toFind = new RegExp('cdn\\.jsdelivr\\.net/algoliasearch/latest/' +
buildName.replace('.', '\\.') + // algoliasearch, algoliasearch.angular
'(?:\\.min)?\\.js$'); // [.min].js
var scripts = document.getElementsByTagName('script');
var found = false;
for (var currentScript = 0, nbScripts = scripts.length; currentScript < nbScripts; currentScript++) {
if (scripts[currentScript].src && toFind.test(scripts[currentScript].src)) {
found = true;
break;
}
}
return found;
}
},{}],3:[function(require,module,exports){
'use strict';
module.exports = loadV2;
function loadV2(buildName) {
var loadScript = require(1);
var v2ScriptUrl = '//cdn.jsdelivr.net/algoliasearch/2/' + buildName + '.min.js';
var message = '-- AlgoliaSearch `latest` warning --\n' +
'Warning, you are using the `latest` version string from jsDelivr to load the AlgoliaSearch library.\n' +
'Using `latest` is no more recommended, you should load //cdn.jsdelivr.net/algoliasearch/2/algoliasearch.min.js\n\n' +
'Also, we updated the AlgoliaSearch JavaScript client to V3. If you want to upgrade,\n' +
'please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n' +
'-- /AlgoliaSearch `latest` warning --';
if (window.console) {
if (window.console.warn) {
window.console.warn(message);
} else if (window.console.log) {
window.console.log(message);
}
}
// If current script loaded asynchronously,
// it will load the script with DOMElement
// otherwise, it will load the script with document.write
try {
// why \x3c? http://stackoverflow.com/a/236106/147079
document.write('\x3Cscript>window.ALGOLIA_SUPPORTS_DOCWRITE = true\x3C/script>');
if (window.ALGOLIA_SUPPORTS_DOCWRITE === true) {
document.write('\x3Cscript src="' + v2ScriptUrl + '">\x3C/script>');
scriptLoaded('document.write')();
} else {
loadScript(v2ScriptUrl, scriptLoaded('DOMElement'));
}
} catch (e) {
loadScript(v2ScriptUrl, scriptLoaded('DOMElement'));
}
}
function scriptLoaded(method) {
return function log() {
var message = 'AlgoliaSearch: loaded V2 script using ' + method;
if (window.console && window.console.log) {
window.console.log(message);
}
};
}
},{"1":1}],4:[function(require,module,exports){
'use strict';
/* eslint no-unused-vars: [2, {"vars": "local"}] */
module.exports = oldGlobals;
// put old window.AlgoliaSearch.. into window. again so that
// users upgrading to V3 without changing their code, will be warned
function oldGlobals() {
var message = '-- AlgoliaSearch V2 => V3 error --\n' +
'You are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\n' +
'Please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n' +
'-- /AlgoliaSearch V2 => V3 error --';
window.AlgoliaSearch = function() {
throw new Error(message);
};
window.AlgoliaSearchHelper = function() {
throw new Error(message);
};
window.AlgoliaExplainResults = function() {
throw new Error(message);
};
}
},{}],5:[function(require,module,exports){
'use strict';
// This script will be browserified and prepended to the normal build
// directly in window, not wrapped in any module definition
// To avoid cases where we are loaded with /latest/ along with
migrationLayer("algoliasearch.angular");
// Now onto the V2 related code:
// If the client is using /latest/$BUILDNAME.min.js, load V2 of the library
//
// Otherwise, setup a migration layer that will throw on old constructors like
// new AlgoliaSearch().
// So that users upgrading from v2 to v3 will have a clear information
// message on what to do if they did not read the migration guide
function migrationLayer(buildName) {
var isUsingLatest = require(2);
var loadV2 = require(3);
var oldGlobals = require(4);
if (isUsingLatest(buildName)) {
loadV2(buildName);
} else {
oldGlobals();
}
}
},{"2":2,"3":3,"4":4}]},{},[5])(5)
});(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){
(function (process){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require(2);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
}).call(this,require(12))
},{"12":12,"2":2}],2:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require(9);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"9":9}],3:[function(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version 4.1.1
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ES6Promise = factory());
}(this, (function () { 'use strict';
function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = undefined;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
var isArray = _isArray;
var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = require;
var vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var _arguments = arguments;
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
(function () {
var callback = _arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
})();
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$1(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
try {
then$$1.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then$$1) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then$$1, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return resolve(promise, value);
}, function (reason) {
return reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$1 === GET_THEN_ERROR) {
reject(promise, GET_THEN_ERROR.error);
GET_THEN_ERROR.error = null;
} else if (then$$1 === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$1)) {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = undefined,
callback = undefined,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = undefined,
error = undefined,
succeeded = undefined,
failed = undefined;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value.error = null;
} else {
succeeded = true;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
resolve(promise, value);
}, function rejectPromise(reason) {
reject(promise, reason);
});
} catch (e) {
reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function Enumerator$1(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
}
Enumerator$1.prototype._enumerate = function (input) {
for (var i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
};
Enumerator$1.prototype._eachEntry = function (entry, i) {
var c = this._instanceConstructor;
var resolve$$1 = c.resolve;
if (resolve$$1 === resolve$1) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise$2) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$1) {
return resolve$$1(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$1(entry), i);
}
};
Enumerator$1.prototype._settledAt = function (state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator$1.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all$1(entries) {
return new Enumerator$1(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race$1(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise$2(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
}
}
Promise$2.all = all$1;
Promise$2.race = race$1;
Promise$2.resolve = resolve$1;
Promise$2.reject = reject$1;
Promise$2._setScheduler = setScheduler;
Promise$2._setAsap = setAsap;
Promise$2._asap = asap;
Promise$2.prototype = {
constructor: Promise$2,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function _catch(onRejection) {
return this.then(null, onRejection);
}
};
/*global self*/
function polyfill$1() {
var local = undefined;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise$2;
}
// Strange compat..
Promise$2.polyfill = polyfill$1;
Promise$2.Promise = Promise$2;
return Promise$2;
})));
}).call(this,require(12),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"12":12}],4:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],5:[function(require,module,exports){
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
},{}],6:[function(require,module,exports){
(function (global){
var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof global !== "undefined") {
win = global;
} else if (typeof self !== "undefined"){
win = self;
} else {
win = {};
}
module.exports = win;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],7:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],8:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],9:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],10:[function(require,module,exports){
'use strict';
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = require(11);
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
},{"11":11}],11:[function(require,module,exports){
'use strict';
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
},{}],12:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],13:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],14:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],15:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require(13);
exports.encode = exports.stringify = require(14);
},{"13":13,"14":14}],16:[function(require,module,exports){
module.exports = AlgoliaSearch;
var Index = require(18);
var deprecate = require(29);
var deprecatedMessage = require(30);
var AlgoliaSearchCore = require(17);
var inherits = require(7);
var errors = require(31);
function AlgoliaSearch() {
AlgoliaSearchCore.apply(this, arguments);
}
inherits(AlgoliaSearch, AlgoliaSearchCore);
/*
* Delete an index
*
* @param indexName the name of index to delete
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.deleteIndex = function(indexName, callback) {
return this._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexName),
hostType: 'write',
callback: callback
});
};
/**
* Move an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of
* srcIndexName (destination will be overriten if it already exist).
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.moveIndex = function(srcIndexName, dstIndexName, callback) {
var postObj = {
operation: 'move', destination: dstIndexName
};
return this._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Copy an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy
* of srcIndexName (destination will be overriten if it already exist).
* @param scope an array of scopes to copy: ['settings', 'synonyms', 'rules']
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.copyIndex = function(srcIndexName, dstIndexName, scopeOrCallback, _callback) {
var postObj = {
operation: 'copy',
destination: dstIndexName
};
var callback = _callback;
if (typeof scopeOrCallback === 'function') {
// oops, old behaviour of third argument being a function
callback = scopeOrCallback;
} else if (Array.isArray(scopeOrCallback) && scopeOrCallback.length > 0) {
postObj.scope = scopeOrCallback;
} else if (typeof scopeOrCallback !== 'undefined') {
throw new Error('the scope given to `copyIndex` was not an array with settings, synonyms or rules');
}
return this._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* Return last log entries.
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting
* at offset. Maximum allowed value: 1000.
* @param type Specify the maximum number of entries to retrieve starting
* at offset. Maximum allowed value: 1000.
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer that contains the task ID
*/
AlgoliaSearch.prototype.getLogs = function(offset, length, callback) {
var clone = require(27);
var params = {};
if (typeof offset === 'object') {
// getLogs(params)
params = clone(offset);
callback = length;
} else if (arguments.length === 0 || typeof offset === 'function') {
// getLogs([cb])
callback = offset;
} else if (arguments.length === 1 || typeof length === 'function') {
// getLogs(1, [cb)]
callback = length;
params.offset = offset;
} else {
// getLogs(1, 2, [cb])
params.offset = offset;
params.length = length;
}
if (params.offset === undefined) params.offset = 0;
if (params.length === undefined) params.length = 10;
return this._jsonRequest({
method: 'GET',
url: '/1/logs?' + this._getSearchParams(params, ''),
hostType: 'read',
callback: callback
});
};
/*
* List all existing indexes (paginated)
*
* @param page The page to retrieve, starting at 0.
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with index list
*/
AlgoliaSearch.prototype.listIndexes = function(page, callback) {
var params = '';
if (page === undefined || typeof page === 'function') {
callback = page;
} else {
params = '?page=' + page;
}
return this._jsonRequest({
method: 'GET',
url: '/1/indexes' + params,
hostType: 'read',
callback: callback
});
};
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearch.prototype.initIndex = function(indexName) {
return new Index(this, indexName);
};
AlgoliaSearch.prototype.initAnalytics = function(opts) {
// the actual require must be inside the function, when put outside then you have a cyclic dependency
// not well resolved that ends up making the main "./index.js" (main module, the agloliasearch function)
// export an object instead of a function
// Other workarounds:
// - rewrite the lib in ES6, cyclic dependencies may be better supported
// - move initAnalytics to a property on the main module (algoliasearch.initAnalytics),
// same as places.
// The current API was made mostly to mimic the one made in PHP
var createAnalyticsClient = require(28);
return createAnalyticsClient(this.applicationID, this.apiKey, opts);
};
/*
* @deprecated use client.listApiKeys
*/
AlgoliaSearch.prototype.listUserKeys = deprecate(function(callback) {
return this.listApiKeys(callback);
}, deprecatedMessage('client.listUserKeys()', 'client.listApiKeys()'));
/*
* List all existing api keys with their associated ACLs
*
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with api keys list
*/
AlgoliaSearch.prototype.listApiKeys = function(callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/keys',
hostType: 'read',
callback: callback
});
};
/*
* @deprecated see client.getApiKey
*/
AlgoliaSearch.prototype.getUserKeyACL = deprecate(function(key, callback) {
return this.getApiKey(key, callback);
}, deprecatedMessage('client.getUserKeyACL()', 'client.getApiKey()'));
/*
* Get an API key
*
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the right API key
*/
AlgoliaSearch.prototype.getApiKey = function(key, callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/keys/' + key,
hostType: 'read',
callback: callback
});
};
/*
* @deprecated see client.deleteApiKey
*/
AlgoliaSearch.prototype.deleteUserKey = deprecate(function(key, callback) {
return this.deleteApiKey(key, callback);
}, deprecatedMessage('client.deleteUserKey()', 'client.deleteApiKey()'));
/*
* Delete an existing API key
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the date of deletion
*/
AlgoliaSearch.prototype.deleteApiKey = function(key, callback) {
return this._jsonRequest({
method: 'DELETE',
url: '/1/keys/' + key,
hostType: 'write',
callback: callback
});
};
/*
@deprecated see client.addApiKey
*/
AlgoliaSearch.prototype.addUserKey = deprecate(function(acls, params, callback) {
return this.addApiKey(acls, params, callback);
}, deprecatedMessage('client.addUserKey()', 'client.addApiKey()'));
/*
* Add a new global API key
*
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string[]} params.indexes - Allowed targeted indexes for this key
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the added API key
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.addApiKey(['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* indexes: ['fruits'],
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#AddKey|Algolia REST API Documentation}
*/
AlgoliaSearch.prototype.addApiKey = function(acls, params, callback) {
var isArray = require(8);
var usage = 'Usage: client.addApiKey(arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 1 || typeof params === 'function') {
callback = params;
params = null;
}
var postObj = {
acl: acls
};
if (params) {
postObj.validity = params.validity;
postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
postObj.maxHitsPerQuery = params.maxHitsPerQuery;
postObj.indexes = params.indexes;
postObj.description = params.description;
if (params.queryParameters) {
postObj.queryParameters = this._getSearchParams(params.queryParameters, '');
}
postObj.referers = params.referers;
}
return this._jsonRequest({
method: 'POST',
url: '/1/keys',
body: postObj,
hostType: 'write',
callback: callback
});
};
/**
* @deprecated Please use client.addApiKey()
*/
AlgoliaSearch.prototype.addUserKeyWithValidity = deprecate(function(acls, params, callback) {
return this.addApiKey(acls, params, callback);
}, deprecatedMessage('client.addUserKeyWithValidity()', 'client.addApiKey()'));
/**
* @deprecated Please use client.updateApiKey()
*/
AlgoliaSearch.prototype.updateUserKey = deprecate(function(key, acls, params, callback) {
return this.updateApiKey(key, acls, params, callback);
}, deprecatedMessage('client.updateUserKey()', 'client.updateApiKey()'));
/**
* Update an existing API key
* @param {string} key - The key to update
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string[]} params.indexes - Allowed targeted indexes for this key
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the modified API key
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.updateApiKey('APIKEY', ['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* indexes: ['fruits'],
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation}
*/
AlgoliaSearch.prototype.updateApiKey = function(key, acls, params, callback) {
var isArray = require(8);
var usage = 'Usage: client.updateApiKey(key, arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 2 || typeof params === 'function') {
callback = params;
params = null;
}
var putObj = {
acl: acls
};
if (params) {
putObj.validity = params.validity;
putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
putObj.maxHitsPerQuery = params.maxHitsPerQuery;
putObj.indexes = params.indexes;
putObj.description = params.description;
if (params.queryParameters) {
putObj.queryParameters = this._getSearchParams(params.queryParameters, '');
}
putObj.referers = params.referers;
}
return this._jsonRequest({
method: 'PUT',
url: '/1/keys/' + key,
body: putObj,
hostType: 'write',
callback: callback
});
};
/**
* Initialize a new batch of search queries
* @deprecated use client.search()
*/
AlgoliaSearch.prototype.startQueriesBatch = deprecate(function startQueriesBatchDeprecated() {
this._batch = [];
}, deprecatedMessage('client.startQueriesBatch()', 'client.search()'));
/**
* Add a search query in the batch
* @deprecated use client.search()
*/
AlgoliaSearch.prototype.addQueryInBatch = deprecate(function addQueryInBatchDeprecated(indexName, query, args) {
this._batch.push({
indexName: indexName,
query: query,
params: args
});
}, deprecatedMessage('client.addQueryInBatch()', 'client.search()'));
/**
* Launch the batch of queries using XMLHttpRequest.
* @deprecated use client.search()
*/
AlgoliaSearch.prototype.sendQueriesBatch = deprecate(function sendQueriesBatchDeprecated(callback) {
return this.search(this._batch, callback);
}, deprecatedMessage('client.sendQueriesBatch()', 'client.search()'));
/**
* Perform write operations across multiple indexes.
*
* To reduce the amount of time spent on network round trips,
* you can create, update, or delete several objects in one call,
* using the batch endpoint (all operations are done in the given order).
*
* Available actions:
* - addObject
* - updateObject
* - partialUpdateObject
* - partialUpdateObjectNoCreate
* - deleteObject
*
* https://www.algolia.com/doc/rest_api#Indexes
* @param {Object[]} operations An array of operations to perform
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.batch([{
* action: 'addObject',
* indexName: 'clients',
* body: {
* name: 'Bill'
* }
* }, {
* action: 'udpateObject',
* indexName: 'fruits',
* body: {
* objectID: '29138',
* name: 'banana'
* }
* }], cb)
*/
AlgoliaSearch.prototype.batch = function(operations, callback) {
var isArray = require(8);
var usage = 'Usage: client.batch(operations[, callback])';
if (!isArray(operations)) {
throw new Error(usage);
}
return this._jsonRequest({
method: 'POST',
url: '/1/indexes/*/batch',
body: {
requests: operations
},
hostType: 'write',
callback: callback
});
};
/**
* Assign or Move a userID to a cluster
*
* @param {string} data.userID The userID to assign to a new cluster
* @param {string} data.cluster The cluster to assign the user to
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.assignUserID({ cluster: 'c1-test', userID: 'some-user' });
*/
AlgoliaSearch.prototype.assignUserID = function(data, callback) {
if (!data.userID || !data.cluster) {
throw new errors.AlgoliaSearchError('You have to provide both a userID and cluster', data);
}
return this._jsonRequest({
method: 'POST',
url: '/1/clusters/mapping',
hostType: 'write',
body: {cluster: data.cluster},
callback: callback,
headers: {
'x-algolia-user-id': data.userID
}
});
};
/**
* Get the top userIDs
*
* (the callback is the second argument)
*
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.getTopUserID();
*/
AlgoliaSearch.prototype.getTopUserID = function(callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/clusters/mapping/top',
hostType: 'read',
callback: callback
});
};
/**
* Get userID
*
* @param {string} data.userID The userID to get info about
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.getUserID({ userID: 'some-user' });
*/
AlgoliaSearch.prototype.getUserID = function(data, callback) {
if (!data.userID) {
throw new errors.AlgoliaSearchError('You have to provide a userID', {debugData: data});
}
return this._jsonRequest({
method: 'GET',
url: '/1/clusters/mapping/' + data.userID,
hostType: 'read',
callback: callback
});
};
/**
* List all the clusters
*
* (the callback is the second argument)
*
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.listClusters();
*/
AlgoliaSearch.prototype.listClusters = function(callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/clusters',
hostType: 'read',
callback: callback
});
};
/**
* List the userIDs
*
* (the callback is the second argument)
*
* @param {string} data.hitsPerPage How many hits on every page
* @param {string} data.page The page to retrieve
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.listClusters();
* client.listClusters({ page: 3, hitsPerPage: 30});
*/
AlgoliaSearch.prototype.listUserIDs = function(data, callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/clusters/mapping',
body: data,
hostType: 'read',
callback: callback
});
};
/**
* Remove an userID
*
* @param {string} data.userID The userID to assign to a new cluster
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.removeUserID({ userID: 'some-user' });
*/
AlgoliaSearch.prototype.removeUserID = function(data, callback) {
if (!data.userID) {
throw new errors.AlgoliaSearchError('You have to provide a userID', {debugData: data});
}
return this._jsonRequest({
method: 'DELETE',
url: '/1/clusters/mapping',
hostType: 'write',
callback: callback,
headers: {
'x-algolia-user-id': data.userID
}
});
};
/**
* Search for userIDs
*
* @param {string} data.cluster The cluster to target
* @param {string} data.query The query to execute
* @param {string} data.hitsPerPage How many hits on every page
* @param {string} data.page The page to retrieve
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.searchUserIDs({ cluster: 'c1-test', query: 'some-user' });
* client.searchUserIDs({
* cluster: "c1-test",
* query: "some-user",
* page: 3,
* hitsPerPage: 2
* });
*/
AlgoliaSearch.prototype.searchUserIDs = function(data, callback) {
return this._jsonRequest({
method: 'POST',
url: '/1/clusters/mapping/search',
body: data,
hostType: 'read',
callback: callback
});
};
/**
* Set strategy for personalization
*
* @param {Object} data
* @param {Object} data.eventsScoring Associate a score to an event
* @param {Object} data.eventsScoring.<eventName> The name of the event
* @param {Number} data.eventsScoring.<eventName>.score The score to associate to <eventName>
* @param {String} data.eventsScoring.<eventName>.type Either "click", "conversion" or "view"
* @param {Object} data.facetsScoring Associate a score to a facet
* @param {Object} data.facetsScoring.<facetName> The name of the facet
* @param {Number} data.facetsScoring.<facetName>.score The score to associate to <facetName>
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.setPersonalizationStrategy({
* eventsScoring: {
* "Add to cart": { score: 50, type: "conversion" },
* Purchase: { score: 100, type: "conversion" }
* },
* facetsScoring: {
* brand: { score: 100 },
* categories: { score: 10 }
* }
* });
*/
AlgoliaSearch.prototype.setPersonalizationStrategy = function(data, callback) {
return this._jsonRequest({
method: 'POST',
url: '/1/recommendation/personalization/strategy',
body: data,
hostType: 'write',
callback: callback
});
};
/**
* Get strategy for personalization
*
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* client.getPersonalizationStrategy();
*/
AlgoliaSearch.prototype.getPersonalizationStrategy = function(callback) {
return this._jsonRequest({
method: 'GET',
url: '/1/recommendation/personalization/strategy',
hostType: 'read',
callback: callback
});
};
// environment specific methods
AlgoliaSearch.prototype.destroy = notImplemented;
AlgoliaSearch.prototype.enableRateLimitForward = notImplemented;
AlgoliaSearch.prototype.disableRateLimitForward = notImplemented;
AlgoliaSearch.prototype.useSecuredAPIKey = notImplemented;
AlgoliaSearch.prototype.disableSecuredAPIKey = notImplemented;
AlgoliaSearch.prototype.generateSecuredApiKey = notImplemented;
function notImplemented() {
var message = 'Not implemented in this environment.\n' +
'If you feel this is a mistake, write to support@algolia.com';
throw new errors.AlgoliaSearchError(message);
}
},{"17":17,"18":18,"27":27,"28":28,"29":29,"30":30,"31":31,"7":7,"8":8}],17:[function(require,module,exports){
(function (process){
module.exports = AlgoliaSearchCore;
var errors = require(31);
var exitPromise = require(32);
var IndexCore = require(20);
var store = require(37);
// We will always put the API KEY in the JSON body in case of too long API KEY,
// to avoid query string being too long and failing in various conditions (our server limit, browser limit,
// proxies limit)
var MAX_API_KEY_LENGTH = 500;
var RESET_APP_DATA_TIMER =
process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) ||
60 * 2 * 1000; // after 2 minutes reset to first host
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='https:'] - The protocol used to query Algolia Search API.
* Set to 'http:' to force using http.
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = require(1)('algoliasearch');
var clone = require(27);
var isArray = require(8);
var map = require(33);
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
this.hosts = {
read: [],
write: []
};
opts = opts || {};
this._timeouts = opts.timeouts || {
connect: 1 * 1000, // 500ms connect is GPRS latency
read: 2 * 1000,
write: 30 * 1000
};
// backward compat, if opts.timeout is passed, we use it to configure all timeouts like before
if (opts.timeout) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout;
}
var protocol = opts.protocol || 'https:';
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (protocol !== 'http:' && protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
this._checkAppIdData();
if (!opts.hosts) {
var defaultHosts = map(this._shuffleResult, function(hostNumber) {
return applicationID + '-' + hostNumber + '.algolianet.com';
});
// no hosts given, compute defaults
var mainSuffix = (opts.dsn === false ? '' : '-dsn') + '.algolia.net';
this.hosts.read = [this.applicationID + mainSuffix].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
// when passing custom hosts, we need to have a different host index if the number
// of write/read hosts are different.
this.hosts.read = clone(opts.hosts);
this.hosts.write = clone(opts.hosts);
} else {
this.hosts.read = clone(opts.hosts.read);
this.hosts.write = clone(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.extraHeaders = {};
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useRequestCache = this._useCache && opts._useRequestCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders[name.toLowerCase()] = value;
};
/**
* Get the value of an extra HTTP header
*
* @param name the header field name
*/
AlgoliaSearchCore.prototype.getExtraHeader = function(name) {
return this.extraHeaders[name.toLowerCase()];
};
/**
* Remove an extra field from the HTTP request
*
* @param name the header field name
*/
AlgoliaSearchCore.prototype.unsetExtraHeader = function(name) {
delete this.extraHeaders[name.toLowerCase()];
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
if (this._ua.indexOf(';' + algoliaAgent) === -1) {
this._ua += ';' + algoliaAgent;
}
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
this._checkAppIdData();
var requestDebug = require(1)('algoliasearch:' + initialOpts.url);
var body;
var cacheID;
var additionalUA = initialOpts.additionalUA || '';
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders({
additionalUA: additionalUA,
withApiKey: false,
headers: initialOpts.headers
});
} else {
headers = this._computeRequestHeaders({
additionalUA: additionalUA,
headers: initialOpts.headers
});
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
client._checkAppIdData();
var startTime = new Date();
if (client._useCache && !client._useRequestCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && !client._useRequestCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (isCacheValidWithCurrentID(!client._useRequestCache, cache, cacheID)) {
requestDebug('serving response from cache');
var responseText = cache[cacheID];
// Cache response must match the type of the original one
return client._promise.resolve({
body: JSON.parse(responseText),
responseText: responseText
});
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to support@algolia.com to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders({
additionalUA: additionalUA,
headers: initialOpts.headers
});
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
client._setHostIndexByType(0, initialOpts.hostType);
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client._getHostByType(initialOpts.hostType);
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeouts: reqOpts.timeouts,
debug: requestDebug,
forceAuthHeaders: reqOpts.forceAuthHeaders
};
requestDebug('method: %s, url: %s, headers: %j, timeouts: %d',
options.method, url, options.headers, options.timeouts);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && !client._useRequestCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return {
responseText: httpResponse.responseText,
body: httpResponse.body
};
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occurred, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client._incrementHostIndex(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client._incrementHostIndex(initialOpts.hostType);
client._incrementTimeoutMultipler();
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
}
function isCacheValidWithCurrentID(
useRequestCache,
currentCache,
currentCacheID
) {
return (
client._useCache &&
useRequestCache &&
currentCache &&
currentCache[currentCacheID] !== undefined
);
}
function interopCallbackReturn(request, callback) {
if (isCacheValidWithCurrentID(client._useRequestCache, cache, cacheID)) {
request.catch(function() {
// Release the cache on error
delete cache[cacheID];
});
}
if (typeof initialOpts.callback === 'function') {
// either we have a callback
request.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, callback(content));
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
// either we are using promises
return request.then(callback);
}
}
if (client._useCache && client._useRequestCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && client._useRequestCache && body) {
cacheID += '_body_' + body;
}
if (isCacheValidWithCurrentID(client._useRequestCache, cache, cacheID)) {
requestDebug('serving request from cache');
var maybePromiseForCache = cache[cacheID];
// In case the cache is warmup with value that is not a promise
var promiseForCache = typeof maybePromiseForCache.then !== 'function'
? client._promise.resolve({responseText: maybePromiseForCache})
: maybePromiseForCache;
return interopCallbackReturn(promiseForCache, function(content) {
// In case of the cache request, return the original value
return JSON.parse(content.responseText);
});
}
var request = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeouts: client._getTimeoutsForRequest(initialOpts.hostType),
forceAuthHeaders: initialOpts.forceAuthHeaders
}
);
if (client._useCache && client._useRequestCache && cache) {
cache[cacheID] = request;
}
return interopCallbackReturn(request, function(content) {
// In case of the first request, return the JSON value
return content.body;
});
};
/*
* Transform search param object in query string
* @param {object} args arguments to add to the current query string
* @param {string} params current query string
* @return {string} the final query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
/**
* Compute the headers for a request
*
* @param [string] options.additionalUA semi-colon separated string with other user agents to add
* @param [boolean=true] options.withApiKey Send the api key as a header
* @param [Object] options.headers Extra headers to send
*/
AlgoliaSearchCore.prototype._computeRequestHeaders = function(options) {
var forEach = require(5);
var ua = options.additionalUA ?
this._ua + ';' + options.additionalUA :
this._ua;
var requestHeaders = {
'x-algolia-agent': ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (options.withApiKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
forEach(this.extraHeaders, function addToRequestHeaders(value, key) {
requestHeaders[key] = value;
});
if (options.headers) {
forEach(options.headers, function addToRequestHeaders(value, key) {
requestHeaders[key] = value;
});
}
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = require(8);
var map = require(33);
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
postObj.strategy = opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Search for facet values
* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
* This is the top-level API for SFFV.
*
* @param {object[]} queries An array of queries to run.
* @param {string} queries[].indexName Index name, name of the index to search.
* @param {object} queries[].params Query parameters.
* @param {string} queries[].params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} queries[].params.facetQuery Query for the facet search
* @param {string} [queries[].params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
*/
AlgoliaSearchCore.prototype.searchForFacetValues = function(queries) {
var isArray = require(8);
var map = require(33);
var usage = 'Usage: client.searchForFacetValues([{indexName, params: {facetName, facetQuery, ...params}}, ...queries])'; // eslint-disable-line max-len
if (!isArray(queries)) {
throw new Error(usage);
}
var client = this;
return client._promise.all(map(queries, function performQuery(query) {
if (
!query ||
query.indexName === undefined ||
query.params.facetName === undefined ||
query.params.facetQuery === undefined
) {
throw new Error(usage);
}
var clone = require(27);
var omit = require(35);
var indexName = query.indexName;
var params = query.params;
var facetName = params.facetName;
var filteredParams = omit(clone(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = client._getSearchParams(filteredParams, '');
return client._jsonRequest({
cache: client.cache,
method: 'POST',
url:
'/1/indexes/' +
encodeURIComponent(indexName) +
'/facets/' +
encodeURIComponent(facetName) +
'/query',
hostType: 'read',
body: {params: searchParameters}
});
}));
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
* @deprecated
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds;
}
};
/**
* Set the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) {
this._timeouts = timeouts;
};
/**
* Get the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.getTimeouts = function() {
return this._timeouts;
};
AlgoliaSearchCore.prototype._getAppIdData = function() {
var data = store.get(this.applicationID);
if (data !== null) this._cacheAppIdData(data);
return data;
};
AlgoliaSearchCore.prototype._setAppIdData = function(data) {
data.lastChange = (new Date()).getTime();
this._cacheAppIdData(data);
return store.set(this.applicationID, data);
};
AlgoliaSearchCore.prototype._checkAppIdData = function() {
var data = this._getAppIdData();
var now = (new Date()).getTime();
if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) {
return this._resetInitialAppIdData(data);
}
return data;
};
AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) {
var newData = data || {};
newData.hostIndexes = {read: 0, write: 0};
newData.timeoutMultiplier = 1;
newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]);
return this._setAppIdData(newData);
};
AlgoliaSearchCore.prototype._cacheAppIdData = function(data) {
this._hostIndexes = data.hostIndexes;
this._timeoutMultiplier = data.timeoutMultiplier;
this._shuffleResult = data.shuffleResult;
};
AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) {
var foreach = require(5);
var currentData = this._getAppIdData();
foreach(newData, function(value, key) {
currentData[key] = value;
});
return this._setAppIdData(currentData);
};
AlgoliaSearchCore.prototype._getHostByType = function(hostType) {
return this.hosts[hostType][this._getHostIndexByType(hostType)];
};
AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() {
return this._timeoutMultiplier;
};
AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) {
return this._hostIndexes[hostType];
};
AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) {
var clone = require(27);
var newHostIndexes = clone(this._hostIndexes);
newHostIndexes[hostType] = hostIndex;
this._partialAppIdDataUpdate({hostIndexes: newHostIndexes});
return hostIndex;
};
AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) {
return this._setHostIndexByType(
(this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType
);
};
AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() {
var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4);
return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier});
};
AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) {
return {
connect: this._timeouts.connect * this._timeoutMultiplier,
complete: this._timeouts[hostType] * this._timeoutMultiplier
};
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
}).call(this,require(12))
},{"1":1,"12":12,"20":20,"27":27,"31":31,"32":32,"33":33,"35":35,"37":37,"5":5,"8":8}],18:[function(require,module,exports){
var inherits = require(7);
var IndexCore = require(20);
var deprecate = require(29);
var deprecatedMessage = require(30);
var exitPromise = require(32);
var errors = require(31);
var deprecateForwardToSlaves = deprecate(
function() {},
deprecatedMessage('forwardToSlaves', 'forwardToReplicas')
);
module.exports = Index;
function Index() {
IndexCore.apply(this, arguments);
}
inherits(Index, IndexCore);
/*
* Add an object in this index
*
* @param content contains the javascript object to add inside the index
* @param objectID (optional) an objectID you want to attribute to this object
* (if the attribute already exist the old object will be overwrite)
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.addObject = function(content, objectID, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof objectID === 'function') {
callback = objectID;
objectID = undefined;
}
return this.as._jsonRequest({
method: objectID !== undefined ?
'PUT' : // update or create
'POST', // create (API generates an objectID)
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + // create
(objectID !== undefined ? '/' + encodeURIComponent(objectID) : ''), // update or create
body: content,
hostType: 'write',
callback: callback
});
};
/*
* Add several objects
*
* @param objects contains an array of objects to add
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.addObjects = function(objects, callback) {
var isArray = require(8);
var usage = 'Usage: index.addObjects(arrayOfObjects[, callback])';
if (!isArray(objects)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: []
};
for (var i = 0; i < objects.length; ++i) {
var request = {
action: 'addObject',
body: objects[i]
};
postObj.requests.push(request);
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Update partially an object (only update attributes passed in argument)
*
* @param partialObject contains the javascript attributes to override, the
* object must contains an objectID attribute
* @param createIfNotExists (optional) if false, avoid an automatic creation of the object
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.partialUpdateObject = function(partialObject, createIfNotExists, callback) {
if (arguments.length === 1 || typeof createIfNotExists === 'function') {
callback = createIfNotExists;
createIfNotExists = undefined;
}
var indexObj = this;
var url = '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(partialObject.objectID) + '/partial';
if (createIfNotExists === false) {
url += '?createIfNotExists=false';
}
return this.as._jsonRequest({
method: 'POST',
url: url,
body: partialObject,
hostType: 'write',
callback: callback
});
};
/*
* Partially Override the content of several objects
*
* @param objects contains an array of objects to update (each object must contains a objectID attribute)
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.partialUpdateObjects = function(objects, createIfNotExists, callback) {
if (arguments.length === 1 || typeof createIfNotExists === 'function') {
callback = createIfNotExists;
createIfNotExists = true;
}
var isArray = require(8);
var usage = 'Usage: index.partialUpdateObjects(arrayOfObjects[, callback])';
if (!isArray(objects)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: []
};
for (var i = 0; i < objects.length; ++i) {
var request = {
action: createIfNotExists === true ? 'partialUpdateObject' : 'partialUpdateObjectNoCreate',
objectID: objects[i].objectID,
body: objects[i]
};
postObj.requests.push(request);
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Override the content of object
*
* @param object contains the javascript object to save, the object must contains an objectID attribute
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.saveObject = function(object, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(object.objectID),
body: object,
hostType: 'write',
callback: callback
});
};
/*
* Override the content of several objects
*
* @param objects contains an array of objects to update (each object must contains a objectID attribute)
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that updateAt and taskID
*/
Index.prototype.saveObjects = function(objects, callback) {
var isArray = require(8);
var usage = 'Usage: index.saveObjects(arrayOfObjects[, callback])';
if (!isArray(objects)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: []
};
for (var i = 0; i < objects.length; ++i) {
var request = {
action: 'updateObject',
objectID: objects[i].objectID,
body: objects[i]
};
postObj.requests.push(request);
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Delete an object from the index
*
* @param objectID the unique identifier of object to delete
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.deleteObject = function(objectID, callback) {
if (typeof objectID === 'function' || typeof objectID !== 'string' && typeof objectID !== 'number') {
var err = new errors.AlgoliaSearchError(
objectID && typeof objectID !== 'function'
? 'ObjectID must be a string'
: 'Cannot delete an object without an objectID'
);
callback = objectID;
if (typeof callback === 'function') {
return callback(err);
}
return this.as._promise.reject(err);
}
var indexObj = this;
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID),
hostType: 'write',
callback: callback
});
};
/*
* Delete several objects from an index
*
* @param objectIDs contains an array of objectID to delete
* @param callback (optional) the result callback called with two arguments:
* error: null or Error('message')
* content: the server answer that contains 3 elements: createAt, taskId and objectID
*/
Index.prototype.deleteObjects = function(objectIDs, callback) {
var isArray = require(8);
var map = require(33);
var usage = 'Usage: index.deleteObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
var postObj = {
requests: map(objectIDs, function prepareRequest(objectID) {
return {
action: 'deleteObject',
objectID: objectID,
body: {
objectID: objectID
}
};
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
body: postObj,
hostType: 'write',
callback: callback
});
};
/*
* Delete all objects matching a query
*
* @param query the query string
* @param params the optional query parameters
* @param callback (optional) the result callback called with one argument
* error: null or Error('message')
* @deprecated see index.deleteBy
*/
Index.prototype.deleteByQuery = deprecate(function(query, params, callback) {
var clone = require(27);
var map = require(33);
var indexObj = this;
var client = indexObj.as;
if (arguments.length === 1 || typeof params === 'function') {
callback = params;
params = {};
} else {
params = clone(params);
}
params.attributesToRetrieve = 'objectID';
params.hitsPerPage = 1000;
params.distinct = false;
// when deleting, we should never use cache to get the
// search results
this.clearCache();
// there's a problem in how we use the promise chain,
// see how waitTask is done
var promise = this
.search(query, params)
.then(stopOrDelete);
function stopOrDelete(searchContent) {
// stop here
if (searchContent.nbHits === 0) {
// return indexObj.as._request.resolve();
return searchContent;
}
// continue and do a recursive call
var objectIDs = map(searchContent.hits, function getObjectID(object) {
return object.objectID;
});
return indexObj
.deleteObjects(objectIDs)
.then(waitTask)
.then(doDeleteByQuery);
}
function waitTask(deleteObjectsContent) {
return indexObj.waitTask(deleteObjectsContent.taskID);
}
function doDeleteByQuery() {
return indexObj.deleteByQuery(query, params);
}
if (!callback) {
return promise;
}
promise.then(success, failure);
function success() {
exitPromise(function exit() {
callback(null);
}, client._setTimeout || setTimeout);
}
function failure(err) {
exitPromise(function exit() {
callback(err);
}, client._setTimeout || setTimeout);
}
}, deprecatedMessage('index.deleteByQuery()', 'index.deleteBy()'));
/**
* Delete all objects matching a query
*
* the query parameters that can be used are:
* - filters (numeric, facet, tag)
* - geo
*
* you can not send an empty query or filters
*
* @param params the optional query parameters
* @param callback (optional) the result callback called with one argument
* error: null or Error('message')
*/
Index.prototype.deleteBy = function(params, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/deleteByQuery',
body: {params: indexObj.as._getSearchParams(params, '')},
hostType: 'write',
callback: callback
});
};
/*
* Browse all content from an index using events. Basically this will do
* .browse() -> .browseFrom -> .browseFrom -> .. until all the results are returned
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @return {EventEmitter}
* @example
* var browser = index.browseAll('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* });
*
* browser.on('result', function resultCallback(content) {
* console.log(content.hits);
* });
*
* // if any error occurs, you get it
* browser.on('error', function(err) {
* throw err;
* });
*
* // when you have browsed the whole index, you get this event
* browser.on('end', function() {
* console.log('finished');
* });
*
* // at any point if you want to stop the browsing process, you can stop it manually
* // otherwise it will go on and on
* browser.stop();
*
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
Index.prototype.browseAll = function(query, queryParameters) {
if (typeof query === 'object') {
queryParameters = query;
query = undefined;
}
var merge = require(34);
var IndexBrowser = require(19);
var browser = new IndexBrowser();
var client = this.as;
var index = this;
var params = client._getSearchParams(
merge({}, queryParameters || {}, {
query: query
}), ''
);
// start browsing
browseLoop();
function browseLoop(cursor) {
if (browser._stopped) {
return;
}
var body;
if (cursor !== undefined) {
body = {
cursor: cursor
};
} else {
body = {
params: params
};
}
client._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(index.indexName) + '/browse',
hostType: 'read',
body: body,
callback: browseCallback
});
}
function browseCallback(err, content) {
if (browser._stopped) {
return;
}
if (err) {
browser._error(err);
return;
}
browser._result(content);
// no cursor means we are finished browsing
if (content.cursor === undefined) {
browser._end();
return;
}
browseLoop(content.cursor);
}
return browser;
};
/*
* Get a Typeahead.js adapter
* @param searchParams contains an object with query parameters (see search for details)
*/
Index.prototype.ttAdapter = deprecate(function(params) {
var self = this;
return function ttAdapter(query, syncCb, asyncCb) {
var cb;
if (typeof asyncCb === 'function') {
// typeahead 0.11
cb = asyncCb;
} else {
// pre typeahead 0.11
cb = syncCb;
}
self.search(query, params, function searchDone(err, content) {
if (err) {
cb(err);
return;
}
cb(content.hits);
});
};
},
'ttAdapter is not necessary anymore and will be removed in the next version,\n' +
'have a look at autocomplete.js (https://github.com/algolia/autocomplete.js)');
/*
* Wait the publication of a task on the server.
* All server task are asynchronous and you can check with this method that the task is published.
*
* @param taskID the id of the task returned by server
* @param callback the result callback with with two arguments:
* error: null or Error('message')
* content: the server answer that contains the list of results
*/
Index.prototype.waitTask = function(taskID, callback) {
// wait minimum 100ms before retrying
var baseDelay = 100;
// wait maximum 5s before retrying
var maxDelay = 5000;
var loop = 0;
// waitTask() must be handled differently from other methods,
// it's a recursive method using a timeout
var indexObj = this;
var client = indexObj.as;
var promise = retryLoop();
function retryLoop() {
return client._jsonRequest({
method: 'GET',
hostType: 'read',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/task/' + taskID
}).then(function success(content) {
loop++;
var delay = baseDelay * loop * loop;
if (delay > maxDelay) {
delay = maxDelay;
}
if (content.status !== 'published') {
return client._promise.delay(delay).then(retryLoop);
}
return content;
});
}
if (!callback) {
return promise;
}
promise.then(successCb, failureCb);
function successCb(content) {
exitPromise(function exit() {
callback(null, content);
}, client._setTimeout || setTimeout);
}
function failureCb(err) {
exitPromise(function exit() {
callback(err);
}, client._setTimeout || setTimeout);
}
};
/*
* This function deletes the index content. Settings and index specific API keys are kept untouched.
*
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the settings object or the error message if a failure occurred
*/
Index.prototype.clearIndex = function(callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/clear',
hostType: 'write',
callback: callback
});
};
/*
* Get settings of this index
*
* @param opts an object of options to add
* @param opts.advanced get more settings like nbShards (useful for Enterprise)
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the settings object or the error message if a failure occurred
*/
Index.prototype.getSettings = function(opts, callback) {
if (arguments.length === 1 && typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = opts || {};
var indexName = encodeURIComponent(this.indexName);
return this.as._jsonRequest({
method: 'GET',
url:
'/1/indexes/' +
indexName +
'/settings?getVersion=2' +
(opts.advanced ? '&advanced=' + opts.advanced : ''),
hostType: 'read',
callback: callback
});
};
Index.prototype.searchSynonyms = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = {};
} else if (params === undefined) {
params = {};
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/search',
body: params,
hostType: 'read',
callback: callback
});
};
function exportData(method, _hitsPerPage, callback) {
function search(page, _previous) {
var options = {
page: page || 0,
hitsPerPage: _hitsPerPage || 100
};
var previous = _previous || [];
return method(options).then(function(result) {
var hits = result.hits;
var nbHits = result.nbHits;
var current = hits.map(function(s) {
delete s._highlightResult;
return s;
});
var synonyms = previous.concat(current);
if (synonyms.length < nbHits) {
return search(options.page + 1, synonyms);
}
return synonyms;
});
}
return search().then(function(data) {
if (typeof callback === 'function') {
callback(data);
return undefined;
}
return data;
});
}
/**
* Retrieve all the synonyms in an index
* @param [number=100] hitsPerPage The amount of synonyms to retrieve per batch
* @param [function] callback will be called after all synonyms are retrieved
*/
Index.prototype.exportSynonyms = function(hitsPerPage, callback) {
return exportData(this.searchSynonyms.bind(this), hitsPerPage, callback);
};
Index.prototype.saveSynonym = function(synonym, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(synonym.objectID) +
'?forwardToReplicas=' + forwardToReplicas,
body: synonym,
hostType: 'write',
callback: callback
});
};
Index.prototype.getSynonym = function(objectID, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID),
hostType: 'read',
callback: callback
});
};
Index.prototype.deleteSynonym = function(objectID, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID) +
'?forwardToReplicas=' + forwardToReplicas,
hostType: 'write',
callback: callback
});
};
Index.prototype.clearSynonyms = function(opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/clear' +
'?forwardToReplicas=' + forwardToReplicas,
hostType: 'write',
callback: callback
});
};
Index.prototype.batchSynonyms = function(synonyms, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/batch' +
'?forwardToReplicas=' + forwardToReplicas +
'&replaceExistingSynonyms=' + (opts.replaceExistingSynonyms ? 'true' : 'false'),
hostType: 'write',
body: synonyms,
callback: callback
});
};
Index.prototype.searchRules = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = {};
} else if (params === undefined) {
params = {};
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/search',
body: params,
hostType: 'read',
callback: callback
});
};
/**
* Retrieve all the query rules in an index
* @param [number=100] hitsPerPage The amount of query rules to retrieve per batch
* @param [function] callback will be called after all query rules are retrieved
* error: null or Error('message')
*/
Index.prototype.exportRules = function(hitsPerPage, callback) {
return exportData(this.searchRules.bind(this), hitsPerPage, callback);
};
Index.prototype.saveRule = function(rule, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
if (!rule.objectID) {
throw new errors.AlgoliaSearchError('Missing or empty objectID field for rule');
}
var forwardToReplicas = opts.forwardToReplicas === true ? 'true' : 'false';
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/' + encodeURIComponent(rule.objectID) +
'?forwardToReplicas=' + forwardToReplicas,
body: rule,
hostType: 'write',
callback: callback
});
};
Index.prototype.getRule = function(objectID, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/' + encodeURIComponent(objectID),
hostType: 'read',
callback: callback
});
};
Index.prototype.deleteRule = function(objectID, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var forwardToReplicas = opts.forwardToReplicas === true ? 'true' : 'false';
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/' + encodeURIComponent(objectID) +
'?forwardToReplicas=' + forwardToReplicas,
hostType: 'write',
callback: callback
});
};
Index.prototype.clearRules = function(opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var forwardToReplicas = opts.forwardToReplicas === true ? 'true' : 'false';
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/clear' +
'?forwardToReplicas=' + forwardToReplicas,
hostType: 'write',
callback: callback
});
};
Index.prototype.batchRules = function(rules, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var forwardToReplicas = opts.forwardToReplicas === true ? 'true' : 'false';
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/batch' +
'?forwardToReplicas=' + forwardToReplicas +
'&clearExistingRules=' + (opts.clearExistingRules === true ? 'true' : 'false'),
hostType: 'write',
body: rules,
callback: callback
});
};
/*
* Set settings for this index
*
* @param settings the settings object that can contains :
* - minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3).
* - minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7).
* - hitsPerPage: (integer) the number of hits per page (default = 10).
* - attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects.
* If set to null, all attributes are retrieved.
* - attributesToHighlight: (array of strings) default list of attributes to highlight.
* If set to null, all indexed attributes are highlighted.
* - attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number
* of words to return (syntax is attributeName:nbWords).
* By default no snippet is computed. If set to null, no snippet is computed.
* - attributesToIndex: (array of strings) the list of fields you want to index.
* If set to null, all textual and numerical attributes of your objects are indexed,
* but you should update it to get optimal results.
* This parameter has two important uses:
* - Limit the attributes to index: For example if you store a binary image in base64,
* you want to store it and be able to
* retrieve it but you don't want to search in the base64 string.
* - Control part of the ranking*: (see the ranking parameter for full explanation)
* Matches in attributes at the beginning of
* the list will be considered more important than matches in attributes further down the list.
* In one attribute, matching text at the beginning of the attribute will be
* considered more important than text after, you can disable
* this behavior if you add your attribute inside `unordered(AttributeName)`,
* for example attributesToIndex: ["title", "unordered(text)"].
* - attributesForFaceting: (array of strings) The list of fields you want to use for faceting.
* All strings in the attribute selected for faceting are extracted and added as a facet.
* If set to null, no attribute is used for faceting.
* - attributeForDistinct: (string) The attribute name used for the Distinct feature.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in query with the distinct=1 parameter, all hits containing a duplicate
* value for this attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best one is kept and others are removed.
* - ranking: (array of strings) controls the way results are sorted.
* We have six available criteria:
* - typo: sort according to number of typos,
* - geo: sort according to decreassing distance when performing a geo-location based search,
* - proximity: sort according to the proximity of query words in hits,
* - attribute: sort according to the order of attributes defined by attributesToIndex,
* - exact:
* - if the user query contains one word: sort objects having an attribute
* that is exactly the query word before others.
* For example if you search for the "V" TV show, you want to find it
* with the "V" query and avoid to have all popular TV
* show starting by the v letter before it.
* - if the user query contains multiple words: sort according to the
* number of words that matched exactly (and not as a prefix).
* - custom: sort according to a user defined formula set in **customRanking** attribute.
* The standard order is ["typo", "geo", "proximity", "attribute", "exact", "custom"]
* - customRanking: (array of strings) lets you specify part of the ranking.
* The syntax of this condition is an array of strings containing attributes
* prefixed by asc (ascending order) or desc (descending order) operator.
* For example `"customRanking" => ["desc(population)", "asc(name)"]`
* - queryType: Select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - highlightPreTag: (string) Specify the string that is inserted before
* the highlighted parts in the query result (default to "<em>").
* - highlightPostTag: (string) Specify the string that is inserted after
* the highlighted parts in the query result (default to "</em>").
* - optionalWords: (array of strings) Specify a list of words that should
* be considered as optional when found in the query.
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the server answer or the error message if a failure occurred
*/
Index.prototype.setSettings = function(settings, opts, callback) {
if (arguments.length === 1 || typeof opts === 'function') {
callback = opts;
opts = {};
}
if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
var indexObj = this;
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?forwardToReplicas='
+ forwardToReplicas,
hostType: 'write',
body: settings,
callback: callback
});
};
/*
* @deprecated see client.listApiKeys()
*/
Index.prototype.listUserKeys = deprecate(function(callback) {
return this.listApiKeys(callback);
}, deprecatedMessage('index.listUserKeys()', 'client.listApiKeys()'));
/*
* List all existing API keys to this index
*
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with API keys belonging to the index
*
* @deprecated see client.listApiKeys()
*/
Index.prototype.listApiKeys = deprecate(function(callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys',
hostType: 'read',
callback: callback
});
}, deprecatedMessage('index.listApiKeys()', 'client.listApiKeys()'));
/*
* @deprecated see client.getApiKey()
*/
Index.prototype.getUserKeyACL = deprecate(function(key, callback) {
return this.getApiKey(key, callback);
}, deprecatedMessage('index.getUserKeyACL()', 'client.getApiKey()'));
/*
* Get an API key from this index
*
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the right API key
*
* @deprecated see client.getApiKey()
*/
Index.prototype.getApiKey = deprecate(function(key, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
hostType: 'read',
callback: callback
});
}, deprecatedMessage('index.getApiKey()', 'client.getApiKey()'));
/*
* @deprecated see client.deleteApiKey()
*/
Index.prototype.deleteUserKey = deprecate(function(key, callback) {
return this.deleteApiKey(key, callback);
}, deprecatedMessage('index.deleteUserKey()', 'client.deleteApiKey()'));
/*
* Delete an existing API key associated to this index
*
* @param key
* @param callback the result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the deletion date
*
* @deprecated see client.deleteApiKey()
*/
Index.prototype.deleteApiKey = deprecate(function(key, callback) {
var indexObj = this;
return this.as._jsonRequest({
method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
hostType: 'write',
callback: callback
});
}, deprecatedMessage('index.deleteApiKey()', 'client.deleteApiKey()'));
/*
* @deprecated see client.addApiKey()
*/
Index.prototype.addUserKey = deprecate(function(acls, params, callback) {
return this.addApiKey(acls, params, callback);
}, deprecatedMessage('index.addUserKey()', 'client.addApiKey()'));
/*
* Add a new API key to this index
*
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will
* be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the added API key
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.addUserKey(['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#AddIndexKey|Algolia REST API Documentation}
*
* @deprecated see client.addApiKey()
*/
Index.prototype.addApiKey = deprecate(function(acls, params, callback) {
var isArray = require(8);
var usage = 'Usage: index.addApiKey(arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 1 || typeof params === 'function') {
callback = params;
params = null;
}
var postObj = {
acl: acls
};
if (params) {
postObj.validity = params.validity;
postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
postObj.maxHitsPerQuery = params.maxHitsPerQuery;
postObj.description = params.description;
if (params.queryParameters) {
postObj.queryParameters = this.as._getSearchParams(params.queryParameters, '');
}
postObj.referers = params.referers;
}
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys',
body: postObj,
hostType: 'write',
callback: callback
});
}, deprecatedMessage('index.addApiKey()', 'client.addApiKey()'));
/**
* @deprecated use client.addApiKey()
*/
Index.prototype.addUserKeyWithValidity = deprecate(function deprecatedAddUserKeyWithValidity(acls, params, callback) {
return this.addApiKey(acls, params, callback);
}, deprecatedMessage('index.addUserKeyWithValidity()', 'client.addApiKey()'));
/*
* @deprecated see client.updateApiKey()
*/
Index.prototype.updateUserKey = deprecate(function(key, acls, params, callback) {
return this.updateApiKey(key, acls, params, callback);
}, deprecatedMessage('index.updateUserKey()', 'client.updateApiKey()'));
/**
* Update an existing API key of this index
* @param {string} key - The key to update
* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param {Object} [params] - Optionnal parameters to set for the key
* @param {number} params.validity - Number of seconds after which the key will
* be automatically removed (0 means no time limit for this key)
* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
* @param {string} params.description - A description for your key
* @param {string[]} params.referers - A list of authorized referers
* @param {Object} params.queryParameters - Force the key to use specific query parameters
* @param {Function} callback - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with user keys list
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.updateApiKey('APIKEY', ['search'], {
* validity: 300,
* maxQueriesPerIPPerHour: 2000,
* maxHitsPerQuery: 3,
* description: 'Eat three fruits',
* referers: ['*.algolia.com'],
* queryParameters: {
* tagFilters: ['public'],
* }
* })
* @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation}
*
* @deprecated see client.updateApiKey()
*/
Index.prototype.updateApiKey = deprecate(function(key, acls, params, callback) {
var isArray = require(8);
var usage = 'Usage: index.updateApiKey(key, arrayOfAcls[, params, callback])';
if (!isArray(acls)) {
throw new Error(usage);
}
if (arguments.length === 2 || typeof params === 'function') {
callback = params;
params = null;
}
var putObj = {
acl: acls
};
if (params) {
putObj.validity = params.validity;
putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
putObj.maxHitsPerQuery = params.maxHitsPerQuery;
putObj.description = params.description;
if (params.queryParameters) {
putObj.queryParameters = this.as._getSearchParams(params.queryParameters, '');
}
putObj.referers = params.referers;
}
return this.as._jsonRequest({
method: 'PUT',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys/' + key,
body: putObj,
hostType: 'write',
callback: callback
});
}, deprecatedMessage('index.updateApiKey()', 'client.updateApiKey()'));
},{"19":19,"20":20,"27":27,"29":29,"30":30,"31":31,"32":32,"33":33,"34":34,"7":7,"8":8}],19:[function(require,module,exports){
'use strict';
// This is the object returned by the `index.browseAll()` method
module.exports = IndexBrowser;
var inherits = require(7);
var EventEmitter = require(4).EventEmitter;
function IndexBrowser() {
}
inherits(IndexBrowser, EventEmitter);
IndexBrowser.prototype.stop = function() {
this._stopped = true;
this._clean();
};
IndexBrowser.prototype._end = function() {
this.emit('end');
this._clean();
};
IndexBrowser.prototype._error = function(err) {
this.emit('error', err);
this._clean();
};
IndexBrowser.prototype._result = function(content) {
this.emit('result', content);
};
IndexBrowser.prototype._clean = function() {
this.removeAllListeners('stop');
this.removeAllListeners('end');
this.removeAllListeners('error');
this.removeAllListeners('result');
};
},{"4":4,"7":7}],20:[function(require,module,exports){
var buildSearchMethod = require(26);
var deprecate = require(29);
var deprecatedMessage = require(30);
module.exports = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the full text query
* @param {object} [args] (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param {function} [callback] the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the similar query
* @param {object} [args] (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = deprecate(
buildSearchMethod('similarQuery'),
deprecatedMessage(
'index.similarSearch(query[, callback])',
'index.search({ similarQuery: query }[, callback])'
)
);
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = require(34);
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse',
body: {params: params},
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse',
body: {cursor: cursor},
hostType: 'read',
callback: callback
});
};
/*
* Search for facet values
* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
*
* @param {string} params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} params.facetQuery Query for the facet search
* @param {string} [params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
* @param callback (optional)
*/
IndexCore.prototype.searchForFacetValues = function(params, callback) {
var clone = require(27);
var omit = require(35);
var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])';
if (params.facetName === undefined || params.facetQuery === undefined) {
throw new Error(usage);
}
var facetName = params.facetName;
var filteredParams = omit(clone(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = this.as._getSearchParams(filteredParams, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' +
encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
hostType: 'read',
body: {params: searchParameters},
callback: callback
});
};
IndexCore.prototype.searchFacet = deprecate(function(params, callback) {
return this.searchForFacetValues(params, callback);
}, deprecatedMessage(
'index.searchFacet(params[, callback])',
'index.searchForFacetValues(params[, callback])'
));
IndexCore.prototype._search = function(params, url, callback, additionalUA) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback,
additionalUA: additionalUA
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occurred
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = require(8);
var map = require(33);
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
},{"26":26,"27":27,"29":29,"30":30,"33":33,"34":34,"35":35,"8":8}],21:[function(require,module,exports){
(function (process){
'use strict';
// This is the AngularJS Algolia Search module
// It's using $http to do requests with a JSONP fallback
// $q promises are returned
var inherits = require(7);
var forEach = require(5);
var AlgoliaSearch = require(16);
var errors = require(31);
var inlineHeaders = require(24);
var jsonpRequest = require(25);
var places = require(36);
// expose original algoliasearch fn in window
window.algoliasearch = require(22);
if (process.env.NODE_ENV === 'debug') {
require(1).enable('algoliasearch*');
}
window.angular.module('algoliasearch', [])
.service('algolia', ['$http', '$q', '$timeout', function algoliaSearchService($http, $q, $timeout) {
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = require(27);
opts = cloneDeep(opts || {});
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchAngular(applicationID, apiKey, opts);
}
algoliasearch.version = require(38);
algoliasearch.ua = 'Algolia for AngularJS ' + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
window.__algolia = {
debug: require(1),
algoliasearch: algoliasearch
};
function AlgoliaSearchAngular() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchAngular, AlgoliaSearch);
AlgoliaSearchAngular.prototype._request = function request(url, opts) {
// Support most Angular.js versions by using $q.defer() instead
// of the new $q() constructor everywhere we need a promise
var deferred = $q.defer();
var resolve = deferred.resolve;
var reject = deferred.reject;
var timedOut;
var body = opts.body;
url = inlineHeaders(url, opts.headers);
var timeoutDeferred = $q.defer();
var timeoutPromise = timeoutDeferred.promise;
$timeout(function timedout() {
timedOut = true;
// will cancel the xhr
timeoutDeferred.resolve('test');
reject(new errors.RequestTimeout());
}, opts.timeouts.complete);
var requestHeaders = {};
// "remove" (set to undefined) possible globally set headers
// in $httpProvider.defaults.headers.common
// otherwise we might fail sometimes
// ref: https://github.com/algolia/algoliasearch-client-js/issues/135
forEach(
$http.defaults.headers.common,
function removeIt(headerValue, headerName) {
requestHeaders[headerName] = undefined;
}
);
requestHeaders.accept = 'application/json';
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
requestHeaders['content-type'] = 'application/x-www-form-urlencoded';
} else {
requestHeaders['content-type'] = 'application/json';
}
}
$http({
url: url,
method: opts.method,
data: body,
cache: false,
timeout: timeoutPromise,
headers: requestHeaders,
transformResponse: transformResponse,
// if client uses $httpProvider.defaults.withCredentials = true,
// we revert it to false to avoid CORS failure
withCredentials: false
}).then(success, error);
function success(response) {
resolve({
statusCode: response.status,
headers: response.headers,
body: JSON.parse(response.data),
responseText: response.data
});
}
// we force getting the raw data because we need it so
// for cache keys
function transformResponse(data) {
return data;
}
function error(response) {
if (timedOut) {
return;
}
// network error
if (response.status === 0) {
reject(
new errors.Network({
more: response
})
);
return;
}
resolve({
body: JSON.parse(response.data),
statusCode: response.status
});
}
return deferred.promise;
};
// using IE8 or IE9 we will always end up here
// AngularJS does not fallback to XDomainRequest
AlgoliaSearchAngular.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
var deferred = $q.defer();
var resolve = deferred.resolve;
var reject = deferred.reject;
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
return deferred.promise;
};
AlgoliaSearchAngular.prototype._promise = {
reject: function(val) {
return $q.reject(val);
},
resolve: function(val) {
// http://www.bennadel.com/blog/2735-q-when-is-the-missing-q-resolve-method-in-angularjs.htm
return $q.when(val);
},
delay: function(ms) {
var deferred = $q.defer();
var resolve = deferred.resolve;
$timeout(resolve, ms);
return deferred.promise;
},
all: function(promises) {
return $q.all(promises);
}
};
return {
Client: function(applicationID, apiKey, options) {
return algoliasearch(applicationID, apiKey, options);
},
ua: algoliasearch.ua,
version: algoliasearch.version
};
}]);
}).call(this,require(12))
},{"1":1,"12":12,"16":16,"22":22,"24":24,"25":25,"27":27,"31":31,"36":36,"38":38,"5":5,"7":7}],22:[function(require,module,exports){
'use strict';
var AlgoliaSearch = require(16);
var createAlgoliasearch = require(23);
module.exports = createAlgoliasearch(AlgoliaSearch);
},{"16":16,"23":23}],23:[function(require,module,exports){
(function (process){
'use strict';
var global = require(6);
var Promise = global.Promise || require(3).Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = require(7);
var errors = require(31);
var inlineHeaders = require(24);
var jsonpRequest = require(25);
var places = require(36);
uaSuffix = uaSuffix || '';
if (process.env.NODE_ENV === 'debug') {
require(1).enable('algoliasearch*');
}
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = require(27);
opts = cloneDeep(opts || {});
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = require(38);
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
global.__algolia = {
debug: require(1),
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in global,
hasXDomainRequest: 'XDomainRequest' in global
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var reqTimeout;
var timedOut;
var connected = false;
reqTimeout = setTimeout(onTimeout, opts.timeouts.connect);
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = onProgress;
if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange;
req.onload = onLoad;
req.onerror = onError;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
// The Analytics API never accepts Auth headers as query string
// this option exists specifically for them.
if (opts.forceAuthHeaders) {
req.setRequestHeader(
'x-algolia-application-id',
opts.headers['x-algolia-application-id']
);
req.setRequestHeader(
'x-algolia-api-key',
opts.headers['x-algolia-api-key']
);
}
} else {
req.open(opts.method, url);
}
// headers are meant to be sent after open
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
if (body) {
req.send(body);
} else {
req.send();
}
// event object not received in IE8, at least
// but we do not use it, still important to note
function onLoad(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function onError(event) {
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors.Network({
more: event
})
);
}
function onTimeout() {
timedOut = true;
req.abort();
reject(new errors.RequestTimeout());
}
function onConnect() {
connected = true;
clearTimeout(reqTimeout);
reqTimeout = setTimeout(onTimeout, opts.timeouts.complete);
}
function onProgress() {
if (!connected) onConnect();
}
function onReadyStateChange() {
if (!connected && req.readyState > 1) onConnect();
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise.reject(val);
},
resolve: function resolvePromise(val) {
return Promise.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
},
all: function all(promises) {
return Promise.all(promises);
}
};
return algoliasearch;
};
}).call(this,require(12))
},{"1":1,"12":12,"24":24,"25":25,"27":27,"3":3,"31":31,"36":36,"38":38,"6":6,"7":7}],24:[function(require,module,exports){
'use strict';
module.exports = inlineHeaders;
var encode = require(14);
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode(headers);
}
},{"14":14}],25:[function(require,module,exports){
'use strict';
module.exports = jsonpRequest;
var errors = require(31);
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data,
responseText: JSON.stringify(data)/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeouts.complete);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
},{"31":31}],26:[function(require,module,exports){
module.exports = buildSearchMethod;
var errors = require(31);
/**
* Creates a search method to be used in clients
* @param {string} queryParam the name of the attribute used for the query
* @param {string} url the url
* @return {function} the search method
*/
function buildSearchMethod(queryParam, url) {
/**
* The search method. Prepares the data and send the query to Algolia.
* @param {string} query the string used for query search
* @param {object} args additional parameters to send with the search
* @param {function} [callback] the callback to be called with the client gets the answer
* @return {undefined|Promise} If the callback is not provided then this methods returns a Promise
*/
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
// Normalizing the function signature
if (arguments.length === 0 || typeof query === 'function') {
// Usage : .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// Usage : .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// At this point we have 3 arguments with values
// Usage : .search(args) // careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
var additionalUA;
if (args !== undefined) {
if (args.additionalUA) {
additionalUA = args.additionalUA;
delete args.additionalUA;
}
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback, additionalUA);
};
}
},{"31":31}],27:[function(require,module,exports){
module.exports = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
},{}],28:[function(require,module,exports){
module.exports = createAnalyticsClient;
var algoliasearch = require(22);
function createAnalyticsClient(appId, apiKey, opts) {
var analytics = {};
opts = opts || {};
// there need to be 4 hosts, like on the client, since if requests fail,
// the counter goes up by 1, so we need to have the same amount of hosts
// 4 because: -dsn, -1, -2, -3
// This is done because the APPID used for search will be the same for the analytics client created,
// and since the state of available hosts is shared by APPID globally for the module, we had issues
// where the hostIndex would be 1 while the array was only one entry (you got an empty host)
opts.hosts = opts.hosts || [
'analytics.algolia.com',
'analytics.algolia.com',
'analytics.algolia.com',
'analytics.algolia.com'
];
opts.protocol = opts.protocol || 'https:';
analytics.as = algoliasearch(appId, apiKey, opts);
analytics.getABTests = function(_params, callback) {
var params = params || {};
var offset = params.offset || 0;
var limit = params.limit || 10;
return this.as._jsonRequest({
method: 'GET',
url: '/2/abtests?offset=' + encodeURIComponent(offset) + '&limit=' + encodeURIComponent(limit),
hostType: 'read',
forceAuthHeaders: true,
callback: callback
});
};
analytics.getABTest = function(abTestID, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/2/abtests/' + encodeURIComponent(abTestID),
hostType: 'read',
forceAuthHeaders: true,
callback: callback
});
};
analytics.addABTest = function(abTest, callback) {
return this.as._jsonRequest({
method: 'POST',
url: '/2/abtests',
body: abTest,
hostType: 'read',
forceAuthHeaders: true,
callback: callback
});
};
analytics.stopABTest = function(abTestID, callback) {
return this.as._jsonRequest({
method: 'POST',
url: '/2/abtests/' + encodeURIComponent(abTestID) + '/stop',
hostType: 'read',
forceAuthHeaders: true,
callback: callback
});
};
analytics.deleteABTest = function(abTestID, callback) {
return this.as._jsonRequest({
method: 'DELETE',
url: '/2/abtests/' + encodeURIComponent(abTestID),
hostType: 'write',
forceAuthHeaders: true,
callback: callback
});
};
analytics.waitTask = function(indexName, taskID, callback) {
return this.as.initIndex(indexName).waitTask(taskID, callback);
};
return analytics;
}
},{"22":22}],29:[function(require,module,exports){
module.exports = function deprecate(fn, message) {
var warned = false;
function deprecated() {
if (!warned) {
/* eslint no-console:0 */
console.warn(message);
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
},{}],30:[function(require,module,exports){
module.exports = function deprecatedMessage(previousUsage, newUsage) {
var githubAnchorLink = previousUsage.toLowerCase()
.replace(/[\.\(\)]/g, '');
return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
'`. Please see https://github.com/algolia/algoliasearch-client-javascript/wiki/Deprecated#' + githubAnchorLink;
};
},{}],31:[function(require,module,exports){
'use strict';
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
var inherits = require(7);
function AlgoliaSearchError(message, extraProperties) {
var forEach = require(5);
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
module.exports = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timed out before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
},{"5":5,"7":7}],32:[function(require,module,exports){
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
module.exports = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
},{}],33:[function(require,module,exports){
var foreach = require(5);
module.exports = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
},{"5":5}],34:[function(require,module,exports){
var foreach = require(5);
module.exports = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
},{"5":5}],35:[function(require,module,exports){
module.exports = function omit(obj, test) {
var keys = require(10);
var foreach = require(5);
var filtered = {};
foreach(keys(obj), function doFilter(keyName) {
if (test(keyName) !== true) {
filtered[keyName] = obj[keyName];
}
});
return filtered;
};
},{"10":10,"5":5}],36:[function(require,module,exports){
module.exports = createPlacesClient;
var qs3 = require(15);
var buildSearchMethod = require(26);
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = require(27);
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod('query', '/1/places/query');
index.reverse = function(options, callback) {
var encoded = qs3.encode(options);
return this.as._jsonRequest({
method: 'GET',
url: '/1/places/reverse?' + encoded,
hostType: 'read',
callback: callback
});
};
index.getObject = function(objectID, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/places/' + encodeURIComponent(objectID),
hostType: 'read',
callback: callback
});
};
return index;
};
}
},{"15":15,"26":26,"27":27}],37:[function(require,module,exports){
(function (global){
var debug = require(1)('algoliasearch:src/hostIndexState.js');
var localStorageNamespace = 'algoliasearch-client-js';
var store;
var moduleStore = {
state: {},
set: function(key, data) {
this.state[key] = data;
return this.state[key];
},
get: function(key) {
return this.state[key] || null;
}
};
var localStorageStore = {
set: function(key, data) {
moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure
try {
var namespace = JSON.parse(global.localStorage[localStorageNamespace]);
namespace[key] = data;
global.localStorage[localStorageNamespace] = JSON.stringify(namespace);
return namespace[key];
} catch (e) {
return localStorageFailure(key, e);
}
},
get: function(key) {
try {
return JSON.parse(global.localStorage[localStorageNamespace])[key] || null;
} catch (e) {
return localStorageFailure(key, e);
}
}
};
function localStorageFailure(key, e) {
debug('localStorage failed with', e);
cleanup();
store = moduleStore;
return store.get(key);
}
store = supportsLocalStorage() ? localStorageStore : moduleStore;
module.exports = {
get: getOrSet,
set: getOrSet,
supportsLocalStorage: supportsLocalStorage
};
function getOrSet(key, data) {
if (arguments.length === 1) {
return store.get(key);
}
return store.set(key, data);
}
function supportsLocalStorage() {
try {
if ('localStorage' in global &&
global.localStorage !== null) {
if (!global.localStorage[localStorageNamespace]) {
// actual creation of the namespace
global.localStorage.setItem(localStorageNamespace, JSON.stringify({}));
}
return true;
}
return false;
} catch (_) {
return false;
}
}
// In case of any error on localStorage, we clean our own namespace, this should handle
// quota errors when a lot of keys + data are used
function cleanup() {
try {
global.localStorage.removeItem(localStorageNamespace);
} catch (_) {
// nothing to do
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"1":1}],38:[function(require,module,exports){
'use strict';
module.exports = '3.32.1';
},{}]},{},[21]);
| sufuf3/cdnjs | ajax/libs/algoliasearch/3.32.1/algoliasearch.angular.js | JavaScript | mit | 211,935 |
define(['baseTestSetup', 'angular'], function(baseTestSetup, angular) {
'use strict';
describe('trackr.administration.employees.listController', function() {
var ListController, scope, state;
baseTestSetup();
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
state = {
go: angular.noop
};
spyOn(state, 'go');
ListController = $controller('trackr.administration.employees.listController', {
$scope: scope,
$state: state
});
}));
beforeEach(inject(function($httpBackend) {
$httpBackend.flush();
}));
it('must load companies at the start', function() {
expect(scope.employees).toBeDefined();
expect(scope.employees.length).toBeGreaterThan(0);
});
});
}); | agilemobiledev/trackr-frontend | test/modules/trackr/administration/employees/listControllerSpec.js | JavaScript | mit | 916 |
module.exports = [
[/require.include\(\) is deprecated and will be removed soon/],
[/require.include\(\) is deprecated and will be removed soon/]
];
| webpack/webpack | test/cases/parsing/typeof/warnings.js | JavaScript | mit | 151 |
var chai = require('chai')
var chaiString = require('chai-string')
var chaiAsPromised = require('chai-as-promised')
exports.config = {
specs: [__dirname + '/specs/stale.spec.js'],
capabilities: [{
browserName: 'phantomjs'
}],
mochaOpts: {
compilers: ['js:babel/register'],
timeout: 60000
},
before: function () {
chai.should()
chai.use(chaiString)
chai.use(chaiAsPromised)
global.assert = chai.assert
global.expect = chai.expect
}
}
| sebastiendavid/webdriverio | test/fixtures/stale.wdio.conf.js | JavaScript | mit | 526 |
var fs = require('fs');
if (process.argv.length !== 4) {
console.log("USAGE: node convert.js infile outfile");
process.exit(1);
}
var inFile = process.argv[2],
outFile = process.argv[3];
var inData = fs.readFileSync(inFile, 'utf8');
var lines = inData.split("\n");
var out = "create_collection('us_cities');\n";
for (var i = 0; i < lines.length; i++) {
var parts = lines[i].split(",");
var obj = {
"Country": parts[0],
"City": parts[1],
"Region": parts[2],
"Latitude": Number(parts[3]),
"Longitude": Number(parts[4])
};
out += "SELECT save('us_cities', '" + JSON.stringify(obj) + "');\n";
}
fs.writeFileSync(outFile, out, 'utf8');
console.log("done!");
| JerrySievert/mongolike | data/convert.js | JavaScript | mit | 712 |
/*globals describe, before, beforeEach, it*/
var testUtils = require('./testUtils'),
should = require('should'),
sinon = require('sinon'),
when = require('when'),
path = require('path'),
_ = require('underscore'),
// Stuff we are testing
Ghost = require('../../ghost');
describe("Ghost API", function () {
var testTemplatePath = 'core/test/unit/fixtures/',
themeTemplatePath = 'core/test/unit/fixtures/theme',
ghost;
before(function (done) {
testUtils.clearData().then(function () {
done();
}, done);
});
beforeEach(function (done) {
testUtils.initData().then(function () {
ghost = new Ghost();
done();
}, done);
});
it("is a singleton", function () {
var logStub = sinon.stub(console, "log"),
ghost1 = new Ghost(),
ghost2 = new Ghost();
should.strictEqual(ghost1, ghost2);
logStub.restore();
});
it("uses init() to initialize", function (done) {
var dataProviderInitMock = sinon.stub(ghost.dataProvider, "init", function () {
return when.resolve();
});
should.not.exist(ghost.settings());
ghost.init().then(function () {
should.exist(ghost.settings());
dataProviderInitMock.called.should.equal(true);
dataProviderInitMock.restore();
done();
}, done);
});
it("can register filters with specific priority", function () {
var filterName = 'test',
filterPriority = 9,
testFilterHandler = sinon.spy();
ghost.registerFilter(filterName, filterPriority, testFilterHandler);
should.exist(ghost.filterCallbacks[filterName]);
should.exist(ghost.filterCallbacks[filterName][filterPriority]);
ghost.filterCallbacks[filterName][filterPriority].should.include(testFilterHandler);
});
it("can register filters with default priority", function () {
var filterName = 'test',
defaultPriority = 5,
testFilterHandler = sinon.spy();
ghost.registerFilter(filterName, testFilterHandler);
should.exist(ghost.filterCallbacks[filterName]);
should.exist(ghost.filterCallbacks[filterName][defaultPriority]);
ghost.filterCallbacks[filterName][defaultPriority].should.include(testFilterHandler);
});
it("executes filters in priority order", function (done) {
var filterName = 'testpriority',
testFilterHandler1 = sinon.spy(),
testFilterHandler2 = sinon.spy(),
testFilterHandler3 = sinon.spy();
ghost.registerFilter(filterName, 0, testFilterHandler1);
ghost.registerFilter(filterName, 2, testFilterHandler2);
ghost.registerFilter(filterName, 9, testFilterHandler3);
ghost.doFilter(filterName, null, function () {
testFilterHandler1.calledBefore(testFilterHandler2).should.equal(true);
testFilterHandler2.calledBefore(testFilterHandler3).should.equal(true);
testFilterHandler3.called.should.equal(true);
done();
});
});
it("can compile a template", function (done) {
var template = path.join(process.cwd(), testTemplatePath, 'test.hbs');
should.exist(ghost.compileTemplate, 'Template Compiler exists');
ghost.compileTemplate(template).then(function (templateFn) {
should.exist(templateFn);
_.isFunction(templateFn).should.equal(true);
templateFn().should.equal('<h1>HelloWorld</h1>');
done();
}).then(null, done);
});
it("loads templates for helpers", function (done) {
var compileSpy = sinon.spy(ghost, 'compileTemplate'),
pathsStub;
should.exist(ghost.loadTemplate, 'load template function exists');
// In order for the test to work, need to replace the path to the template
pathsStub = sinon.stub(ghost, "paths", function () {
return {
// Forcing the theme path to be the same
activeTheme: path.join(process.cwd(), testTemplatePath),
helperTemplates: path.join(process.cwd(), testTemplatePath)
};
});
ghost.loadTemplate('test').then(function (templateFn) {
compileSpy.restore();
pathsStub.restore();
// test that compileTemplate was called with the expected path
compileSpy.calledOnce.should.equal(true);
compileSpy.calledWith(path.join(process.cwd(), testTemplatePath, 'test.hbs')).should.equal(true);
should.exist(templateFn);
_.isFunction(templateFn).should.equal(true);
templateFn().should.equal('<h1>HelloWorld</h1>');
done();
}).then(null, done);
});
it("loads templates from themes first", function (done) {
var compileSpy = sinon.spy(ghost, 'compileTemplate'),
pathsStub;
should.exist(ghost.loadTemplate, 'load template function exists');
// In order for the test to work, need to replace the path to the template
pathsStub = sinon.stub(ghost, "paths", function () {
return {
activeTheme: path.join(process.cwd(), themeTemplatePath),
helperTemplates: path.join(process.cwd(), testTemplatePath)
};
});
ghost.loadTemplate('test').then(function (templateFn) {
// test that compileTemplate was called with the expected path
compileSpy.calledOnce.should.equal(true);
compileSpy.calledWith(path.join(process.cwd(), themeTemplatePath, 'partials', 'test.hbs')).should.equal(true);
should.exist(templateFn);
_.isFunction(templateFn).should.equal(true);
templateFn().should.equal('<h1>HelloWorld Themed</h1>');
compileSpy.restore();
pathsStub.restore();
done();
}).then(null, done);
});
}); | od3n/ghost-on-heroku | core/test/unit/ghost_spec.js | JavaScript | mit | 6,073 |
'use strict';
var React = require('react');
var PureRenderMixin = require('react-addons-pure-render-mixin');
var SvgIcon = require('../../svg-icon');
var ToggleStar = React.createClass({
displayName: 'ToggleStar',
mixins: [PureRenderMixin],
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z' })
);
}
});
module.exports = ToggleStar; | dominikgar/flask-search-engine | node_modules/material-ui/lib/svg-icons/toggle/star.js | JavaScript | mit | 522 |
var Marionette = require('backbone.marionette');
// TODO: move to a dedicated component
var mapping = {
'ar': 'AE',
'be': 'BY',
'bg': 'BG',
'ca': 'ES',
'cs': 'CZ',
'da': 'DK',
'de': 'DE',
'el': 'GR',
'en': 'GB',
'es': 'ES',
'et': 'EE',
'fi': 'FI',
'fr': 'FR',
'ga': 'IE',
'hi': 'IN',
'hr': 'HR',
'hu': 'HU',
'id': 'ID',
'in': 'ID',
'is': 'IS',
'it': 'IT',
'iw': 'IL',
'ja': 'JP',
'ko': 'KR',
'lt': 'LT',
'lv': 'LV',
'mk': 'MK',
'ms': 'MY',
'mt': 'MT',
'nl': 'NL',
'no': 'NO',
'pl': 'PL',
'pt': 'PT',
'ro': 'RO',
'ru': 'RU',
'sk': 'SK',
'sl': 'SI',
'sq': 'AL',
'sr': 'RS',
'sv': 'SE',
'th': 'TH',
'tr': 'TR',
'uk': 'UA',
'vi': 'VN',
'zh': 'CN',
};
function getRegion(locale) {
var lang = locale.substring(0, 2);
var region = locale.substring(3, 5);
if (region)
return region;
return mapping[lang] || 'unknown';
};
module.exports = Marionette.ItemView.extend({
template: require('../templates/language-item'),
tagName: "li",
serializeData: function() {
var data = Marionette.ItemView.prototype.serializeData.call(this);
// Add region code (to display FLAG)
data.region_code = getRegion(data.locale).toUpperCase();
return data;
}
});
| Nedeas/openl10n | client/src/project/views/language-item-view.js | JavaScript | mit | 1,265 |
var files =
[
[ "MyoKit.h", "_myo_kit_8h_source.html", null ],
[ "TLMAccelerometerEvent.h", "_t_l_m_accelerometer_event_8h_source.html", null ],
[ "TLMAngle.h", "_t_l_m_angle_8h_source.html", null ],
[ "TLMArmSyncEvent.h", "_t_l_m_arm_sync_event_8h_source.html", null ],
[ "TLMArmUnsyncEvent.h", "_t_l_m_arm_unsync_event_8h_source.html", null ],
[ "TLMEmgEvent.h", "_t_l_m_emg_event_8h_source.html", null ],
[ "TLMEulerAngles.h", "_t_l_m_euler_angles_8h_source.html", null ],
[ "TLMGyroscopeEvent.h", "_t_l_m_gyroscope_event_8h_source.html", null ],
[ "TLMHub.h", "_t_l_m_hub_8h_source.html", null ],
[ "TLMLockEvent.h", "_t_l_m_lock_event_8h_source.html", null ],
[ "TLMMath.h", "_t_l_m_math_8h_source.html", null ],
[ "TLMMyo.h", "_t_l_m_myo_8h_source.html", null ],
[ "TLMOrientationEvent.h", "_t_l_m_orientation_event_8h_source.html", null ],
[ "TLMPose.h", "_t_l_m_pose_8h_source.html", null ],
[ "TLMSettingsViewController.h", "_t_l_m_settings_view_controller_8h_source.html", null ],
[ "TLMUnlockEvent.h", "_t_l_m_unlock_event_8h_source.html", null ]
]; | omarmjhd/archer | ios/Myo-iOS-SDK-0.5.2/docs/files.js | JavaScript | mit | 1,124 |
var window = self;
var Global = self;
importScripts("/javascripts/lodash.js", "/javascripts/aether.js");
try {
//Detect very modern javascript support.
(0,eval("'use strict'; let test = WeakMap && (class Test { *gen(a=7) { yield yield * () => true ; } });"));
console.log("Modern javascript detected, aw yeah!");
self.importScripts('/javascripts/esper.modern.js');
} catch (e) {
console.log("Legacy javascript detected, falling back...", e.message);
self.importScripts('/javascripts/esper.js');
}
//console.log("Aether Tome worker has finished importing scripts.");
var aethers = {};
var languagesImported = {};
var ensureLanguageImported = function(language) {
if (languagesImported[language]) return;
if (language === 'html' || language === 'javascript') return;
//Detect very modern javascript support.
try {
(0,eval("'use strict'; let test = WeakMap && (class Test { *gen(a=7) { yield yield * () => true ; } });"));
console.log(`Using modern language plugin: ${language}`);
importScripts("/javascripts/app/vendor/aether-" + language + ".modern.js");
} catch (e) {
console.log("Legacy javascript detected, using legacy plugin for", language, e.message);
importScripts("/javascripts/app/vendor/aether-" + language + ".js");
}
languagesImported[language] = true;
};
var createAether = function (spellKey, options) {
ensureLanguageImported(options.language);
aethers[spellKey] = new Aether(options);
return JSON.stringify({
"message": "Created aether for " + spellKey,
"function": "createAether"
});
};
var hasChangedSignificantly = function(spellKey, a,b,careAboutLineNumbers,careAboutLint) {
var hasChanged = aethers[spellKey].hasChangedSignificantly(a,b,careAboutLineNumbers,careAboutLint);
var functionName = "hasChangedSignificantly";
var returnObject = {
"function":functionName,
"hasChanged": hasChanged,
"spellKey": spellKey
};
return JSON.stringify(returnObject);
};
var updateLanguageAether = function(newLanguage) {
ensureLanguageImported(newLanguage);
for (var spellKey in aethers)
{
if (aethers.hasOwnProperty(spellKey))
{
aethers[spellKey].setLanguage(newLanguage);
}
}
};
var lint = function(spellKey, source) {
var currentAether = aethers[spellKey];
var lintMessages = currentAether.lint(source);
var functionName = "lint";
var returnObject = {
"lintMessages": lintMessages,
"function": functionName
};
return JSON.stringify(returnObject);
};
var transpile = function(spellKey, source) {
var currentAether = aethers[spellKey];
currentAether.transpile(source);
var functionName = "transpile";
var returnObject = {
"problems": currentAether.problems,
"function": functionName,
"spellKey": spellKey
};
return JSON.stringify(returnObject);
};
self.addEventListener('message', function(e) {
var data = JSON.parse(e.data);
if (data.function == "createAether")
{
self.postMessage(createAether(data.spellKey, data.options));
}
else if (data.function == "updateLanguageAether")
{
updateLanguageAether(data.newLanguage);
}
else if (data.function == "hasChangedSignificantly")
{
self.postMessage(hasChangedSignificantly(
data.spellKey,
data.a,
data.b,
data.careAboutLineNumbers,
data.careAboutLint
));
}
else if (data.function == "lint")
{
self.postMessage(lint(data.spellKey, data.source));
}
else if (data.function == "transpile")
{
self.postMessage(transpile(data.spellKey, data.source));
}
else
{
var message = "Didn't execute any function...";
var returnObject = {"message":message, "function":"none"};
self.postMessage(JSON.stringify(returnObject));
}
}, false);
| jeremiahyan/codecombat | app/assets/javascripts/workers/aether_worker.js | JavaScript | mit | 3,968 |
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v19.1.2
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("../../utils");
var beanStub_1 = require("../../context/beanStub");
var rowNodeBlock_1 = require("./rowNodeBlock");
var RowNodeCache = /** @class */ (function (_super) {
__extends(RowNodeCache, _super);
function RowNodeCache(cacheParams) {
var _this = _super.call(this) || this;
_this.maxRowFound = false;
_this.blocks = {};
_this.blockCount = 0;
_this.virtualRowCount = cacheParams.initialRowCount;
_this.cacheParams = cacheParams;
return _this;
}
RowNodeCache.prototype.destroy = function () {
var _this = this;
_super.prototype.destroy.call(this);
this.forEachBlockInOrder(function (block) { return _this.destroyBlock(block); });
};
RowNodeCache.prototype.init = function () {
var _this = this;
this.active = true;
this.addDestroyFunc(function () { return _this.active = false; });
};
RowNodeCache.prototype.isActive = function () {
return this.active;
};
RowNodeCache.prototype.getVirtualRowCount = function () {
return this.virtualRowCount;
};
RowNodeCache.prototype.hack_setVirtualRowCount = function (virtualRowCount) {
this.virtualRowCount = virtualRowCount;
};
RowNodeCache.prototype.isMaxRowFound = function () {
return this.maxRowFound;
};
// listener on EVENT_LOAD_COMPLETE
RowNodeCache.prototype.onPageLoaded = function (event) {
this.cacheParams.rowNodeBlockLoader.loadComplete();
this.checkBlockToLoad();
// if we are not active, then we ignore all events, otherwise we could end up getting the
// grid to refresh even though we are no longer the active cache
if (!this.isActive()) {
return;
}
this.logger.log("onPageLoaded: page = " + event.page.getBlockNumber() + ", lastRow = " + event.lastRow);
if (event.success) {
this.checkVirtualRowCount(event.page, event.lastRow);
}
};
RowNodeCache.prototype.purgeBlocksIfNeeded = function (blockToExclude) {
var _this = this;
// put all candidate blocks into a list for sorting
var blocksForPurging = [];
this.forEachBlockInOrder(function (block) {
// we exclude checking for the page just created, as this has yet to be accessed and hence
// the lastAccessed stamp will not be updated for the first time yet
if (block === blockToExclude) {
return;
}
blocksForPurging.push(block);
});
// note: need to verify that this sorts items in the right order
blocksForPurging.sort(function (a, b) { return b.getLastAccessed() - a.getLastAccessed(); });
// we remove (maxBlocksInCache - 1) as we already excluded the 'just created' page.
// in other words, after the splice operation below, we have taken out the blocks
// we want to keep, which means we are left with blocks that we can potentially purge
var maxBlocksProvided = this.cacheParams.maxBlocksInCache > 0;
var blocksToKeep = maxBlocksProvided ? this.cacheParams.maxBlocksInCache - 1 : null;
var emptyBlocksToKeep = RowNodeCache.MAX_EMPTY_BLOCKS_TO_KEEP - 1;
blocksForPurging.forEach(function (block, index) {
var purgeBecauseBlockEmpty = block.getState() === rowNodeBlock_1.RowNodeBlock.STATE_DIRTY && index >= emptyBlocksToKeep;
var purgeBecauseCacheFull = maxBlocksProvided ? index >= blocksToKeep : false;
if (purgeBecauseBlockEmpty || purgeBecauseCacheFull) {
// we never purge blocks if they are open, as purging them would mess up with
// our indexes, it would be very messy to restore the purged block to it's
// previous state if it had open children (and what if open children of open
// children, jeeeesus, just thinking about it freaks me out) so best is have a
// rule, if block is open, we never purge.
if (block.isAnyNodeOpen(_this.virtualRowCount)) {
return;
}
// at this point, block is not needed, and no open nodes, so burn baby burn
_this.removeBlockFromCache(block);
}
});
};
RowNodeCache.prototype.postCreateBlock = function (newBlock) {
newBlock.addEventListener(rowNodeBlock_1.RowNodeBlock.EVENT_LOAD_COMPLETE, this.onPageLoaded.bind(this));
this.setBlock(newBlock.getBlockNumber(), newBlock);
this.purgeBlocksIfNeeded(newBlock);
this.checkBlockToLoad();
};
RowNodeCache.prototype.removeBlockFromCache = function (blockToRemove) {
if (!blockToRemove) {
return;
}
this.destroyBlock(blockToRemove);
// we do not want to remove the 'loaded' event listener, as the
// concurrent loads count needs to be updated when the load is complete
// if the purged page is in loading state
};
// gets called after: 1) block loaded 2) block created 3) cache refresh
RowNodeCache.prototype.checkBlockToLoad = function () {
this.cacheParams.rowNodeBlockLoader.checkBlockToLoad();
};
RowNodeCache.prototype.checkVirtualRowCount = function (block, lastRow) {
// if client provided a last row, we always use it, as it could change between server calls
// if user deleted data and then called refresh on the grid.
if (typeof lastRow === 'number' && lastRow >= 0) {
this.virtualRowCount = lastRow;
this.maxRowFound = true;
this.onCacheUpdated();
}
else if (!this.maxRowFound) {
// otherwise, see if we need to add some virtual rows
var lastRowIndex = (block.getBlockNumber() + 1) * this.cacheParams.blockSize;
var lastRowIndexPlusOverflow = lastRowIndex + this.cacheParams.overflowSize;
if (this.virtualRowCount < lastRowIndexPlusOverflow) {
this.virtualRowCount = lastRowIndexPlusOverflow;
this.onCacheUpdated();
}
else if (this.cacheParams.dynamicRowHeight) {
// the only other time is if dynamic row height, as loading rows
// will change the height of the block, given the height of the rows
// is only known after the row is loaded.
this.onCacheUpdated();
}
}
};
RowNodeCache.prototype.setVirtualRowCount = function (rowCount, maxRowFound) {
this.virtualRowCount = rowCount;
// if undefined is passed, we do not set this value, if one of {true,false}
// is passed, we do set the value.
if (utils_1.Utils.exists(maxRowFound)) {
this.maxRowFound = maxRowFound;
}
// if we are still searching, then the row count must not end at the end
// of a particular page, otherwise the searching will not pop into the
// next page
if (!this.maxRowFound) {
if (this.virtualRowCount % this.cacheParams.blockSize === 0) {
this.virtualRowCount++;
}
}
this.onCacheUpdated();
};
RowNodeCache.prototype.forEachNodeDeep = function (callback, sequence) {
var _this = this;
this.forEachBlockInOrder(function (block) {
block.forEachNodeDeep(callback, sequence, _this.virtualRowCount);
});
};
RowNodeCache.prototype.forEachBlockInOrder = function (callback) {
var ids = this.getBlockIdsSorted();
this.forEachBlockId(ids, callback);
};
RowNodeCache.prototype.forEachBlockInReverseOrder = function (callback) {
var ids = this.getBlockIdsSorted().reverse();
this.forEachBlockId(ids, callback);
};
RowNodeCache.prototype.forEachBlockId = function (ids, callback) {
var _this = this;
ids.forEach(function (id) {
var block = _this.blocks[id];
callback(block, id);
});
};
RowNodeCache.prototype.getBlockIdsSorted = function () {
// get all page id's as NUMBERS (not strings, as we need to sort as numbers) and in descending order
var numberComparator = function (a, b) { return a - b; }; // default comparator for array is string comparison
var blockIds = Object.keys(this.blocks).map(function (idStr) { return parseInt(idStr, 10); }).sort(numberComparator);
return blockIds;
};
RowNodeCache.prototype.getBlock = function (blockId) {
return this.blocks[blockId];
};
RowNodeCache.prototype.setBlock = function (id, block) {
this.blocks[id] = block;
this.blockCount++;
this.cacheParams.rowNodeBlockLoader.addBlock(block);
};
RowNodeCache.prototype.destroyBlock = function (block) {
delete this.blocks[block.getBlockNumber()];
block.destroy();
this.blockCount--;
this.cacheParams.rowNodeBlockLoader.removeBlock(block);
};
// gets called 1) row count changed 2) cache purged 3) items inserted
RowNodeCache.prototype.onCacheUpdated = function () {
if (this.isActive()) {
// this results in both row models (infinite and server side) firing ModelUpdated,
// however server side row model also updates the row indexes first
var event_1 = {
type: RowNodeCache.EVENT_CACHE_UPDATED
};
this.dispatchEvent(event_1);
}
};
RowNodeCache.prototype.purgeCache = function () {
var _this = this;
this.forEachBlockInOrder(function (block) { return _this.removeBlockFromCache(block); });
// re-initialise cache - this ensures a cache with no rows can reload when purged!
this.virtualRowCount = this.cacheParams.initialRowCount;
this.maxRowFound = false;
this.onCacheUpdated();
};
RowNodeCache.prototype.getRowNodesInRange = function (firstInRange, lastInRange) {
var _this = this;
var result = [];
var lastBlockId = -1;
var inActiveRange = false;
var numberSequence = new utils_1.NumberSequence();
// if only one node passed, we start the selection at the top
if (utils_1.Utils.missing(firstInRange)) {
inActiveRange = true;
}
var foundGapInSelection = false;
this.forEachBlockInOrder(function (block, id) {
if (foundGapInSelection)
return;
if (inActiveRange && (lastBlockId + 1 !== id)) {
foundGapInSelection = true;
return;
}
lastBlockId = id;
block.forEachNodeShallow(function (rowNode) {
var hitFirstOrLast = rowNode === firstInRange || rowNode === lastInRange;
if (inActiveRange || hitFirstOrLast) {
result.push(rowNode);
}
if (hitFirstOrLast) {
inActiveRange = !inActiveRange;
}
}, numberSequence, _this.virtualRowCount);
});
// inActiveRange will be still true if we never hit the second rowNode
var invalidRange = foundGapInSelection || inActiveRange;
return invalidRange ? [] : result;
};
RowNodeCache.EVENT_CACHE_UPDATED = 'cacheUpdated';
// this property says how many empty blocks should be in a cache, eg if scrolls down fast and creates 10
// blocks all for loading, the grid will only load the last 2 - it will assume the blocks the user quickly
// scrolled over are not needed to be loaded.
RowNodeCache.MAX_EMPTY_BLOCKS_TO_KEEP = 2;
return RowNodeCache;
}(beanStub_1.BeanStub));
exports.RowNodeCache = RowNodeCache;
| sufuf3/cdnjs | ajax/libs/ag-grid/19.1.2/lib/rowModels/cache/rowNodeCache.js | JavaScript | mit | 12,672 |
/*! airbrake-js v1.6.4 */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory((function webpackLoadOptionalExternalModule() { try { return require("os"); } catch(e) {} }()), require("cross-fetch"));
else if(typeof define === 'function' && define.amd)
define(["os", "cross-fetch"], factory);
else if(typeof exports === 'object')
exports["Client"] = factory((function webpackLoadOptionalExternalModule() { try { return require("os"); } catch(e) {} }()), require("cross-fetch"));
else
root["airbrakeJs"] = root["airbrakeJs"] || {}, root["airbrakeJs"]["Client"] = factory(root[undefined], root["fetch"]);
})(typeof self !== 'undefined' ? self : this, function(__WEBPACK_EXTERNAL_MODULE_os__, __WEBPACK_EXTERNAL_MODULE_cross_fetch__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/error-stack-parser/error-stack-parser.js":
/*!***************************************************************!*\
!*** ./node_modules/error-stack-parser/error-stack-parser.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/*** IMPORTS FROM imports-loader ***/
var define = false;
(function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define('error-stack-parser', ['stackframe'], factory);
} else if (true) {
module.exports = factory(__webpack_require__(/*! stackframe */ "./node_modules/stackframe/stackframe.js"));
} else {}
}(this, function ErrorStackParser(StackFrame) {
'use strict';
var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+\:\d+/;
var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+\:\d+|\(native\))/m;
var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code\])?$/;
return {
/**
* Given an Error object, extract the most information from it.
*
* @param {Error} error object
* @return {Array} of StackFrames
*/
parse: function ErrorStackParser$$parse(error) {
if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') {
return this.parseOpera(error);
} else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {
return this.parseV8OrIE(error);
} else if (error.stack) {
return this.parseFFOrSafari(error);
} else {
throw new Error('Cannot parse given Error object');
}
},
// Separate line and column numbers from a string of the form: (URI:Line:Column)
extractLocation: function ErrorStackParser$$extractLocation(urlLike) {
// Fail-fast but return locations like "(native)"
if (urlLike.indexOf(':') === -1) {
return [urlLike];
}
var regExp = /(.+?)(?:\:(\d+))?(?:\:(\d+))?$/;
var parts = regExp.exec(urlLike.replace(/[\(\)]/g, ''));
return [parts[1], parts[2] || undefined, parts[3] || undefined];
},
parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) {
var filtered = error.stack.split('\n').filter(function(line) {
return !!line.match(CHROME_IE_STACK_REGEXP);
}, this);
return filtered.map(function(line) {
if (line.indexOf('(eval ') > -1) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
line = line.replace(/eval code/g, 'eval').replace(/(\(eval at [^\()]*)|(\)\,.*$)/g, '');
}
var tokens = line.replace(/^\s+/, '').replace(/\(eval code/g, '(').split(/\s+/).slice(1);
var locationParts = this.extractLocation(tokens.pop());
var functionName = tokens.join(' ') || undefined;
var fileName = ['eval', '<anonymous>'].indexOf(locationParts[0]) > -1 ? undefined : locationParts[0];
return new StackFrame({
functionName: functionName,
fileName: fileName,
lineNumber: locationParts[1],
columnNumber: locationParts[2],
source: line
});
}, this);
},
parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) {
var filtered = error.stack.split('\n').filter(function(line) {
return !line.match(SAFARI_NATIVE_CODE_REGEXP);
}, this);
return filtered.map(function(line) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
if (line.indexOf(' > eval') > -1) {
line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g, ':$1');
}
if (line.indexOf('@') === -1 && line.indexOf(':') === -1) {
// Safari eval frames only have function names and nothing else
return new StackFrame({
functionName: line
});
} else {
var functionNameRegex = /((.*".+"[^@]*)?[^@]*)(?:@)/;
var matches = line.match(functionNameRegex);
var functionName = matches && matches[1] ? matches[1] : undefined;
var locationParts = this.extractLocation(line.replace(functionNameRegex, ''));
return new StackFrame({
functionName: functionName,
fileName: locationParts[0],
lineNumber: locationParts[1],
columnNumber: locationParts[2],
source: line
});
}
}, this);
},
parseOpera: function ErrorStackParser$$parseOpera(e) {
if (!e.stacktrace || (e.message.indexOf('\n') > -1 &&
e.message.split('\n').length > e.stacktrace.split('\n').length)) {
return this.parseOpera9(e);
} else if (!e.stack) {
return this.parseOpera10(e);
} else {
return this.parseOpera11(e);
}
},
parseOpera9: function ErrorStackParser$$parseOpera9(e) {
var lineRE = /Line (\d+).*script (?:in )?(\S+)/i;
var lines = e.message.split('\n');
var result = [];
for (var i = 2, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
result.push(new StackFrame({
fileName: match[2],
lineNumber: match[1],
source: lines[i]
}));
}
}
return result;
},
parseOpera10: function ErrorStackParser$$parseOpera10(e) {
var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;
var lines = e.stacktrace.split('\n');
var result = [];
for (var i = 0, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
result.push(
new StackFrame({
functionName: match[3] || undefined,
fileName: match[2],
lineNumber: match[1],
source: lines[i]
})
);
}
}
return result;
},
// Opera 10.65+ Error.stack very similar to FF/Safari
parseOpera11: function ErrorStackParser$$parseOpera11(error) {
var filtered = error.stack.split('\n').filter(function(line) {
return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/);
}, this);
return filtered.map(function(line) {
var tokens = line.split('@');
var locationParts = this.extractLocation(tokens.pop());
var functionCall = (tokens.shift() || '');
var functionName = functionCall
.replace(/<anonymous function(: (\w+))?>/, '$2')
.replace(/\([^\)]*\)/g, '') || undefined;
var argsRaw;
if (functionCall.match(/\(([^\)]*)\)/)) {
argsRaw = functionCall.replace(/^[^\(]+\(([^\)]*)\)$/, '$1');
}
var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ?
undefined : argsRaw.split(',');
return new StackFrame({
functionName: functionName,
args: args,
fileName: locationParts[0],
lineNumber: locationParts[1],
columnNumber: locationParts[2],
source: line
});
}, this);
}
};
}));
/***/ }),
/***/ "./node_modules/promise-polyfill/src/finally.js":
/*!******************************************************!*\
!*** ./node_modules/promise-polyfill/src/finally.js ***!
\******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* @this {Promise}
*/
function finallyConstructor(callback) {
var constructor = this.constructor;
return this.then(
function(value) {
return constructor.resolve(callback()).then(function() {
return value;
});
},
function(reason) {
return constructor.resolve(callback()).then(function() {
return constructor.reject(reason);
});
}
);
}
/* harmony default export */ __webpack_exports__["default"] = (finallyConstructor);
/***/ }),
/***/ "./node_modules/promise-polyfill/src/index.js":
/*!****************************************************!*\
!*** ./node_modules/promise-polyfill/src/index.js ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(setImmediate) {/* harmony import */ var _finally__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./finally */ "./node_modules/promise-polyfill/src/finally.js");
// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;
function noop() {}
// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
return function() {
fn.apply(thisArg, arguments);
};
}
/**
* @constructor
* @param {Function} fn
*/
function Promise(fn) {
if (!(this instanceof Promise))
throw new TypeError('Promises must be constructed via new');
if (typeof fn !== 'function') throw new TypeError('not a function');
/** @type {!number} */
this._state = 0;
/** @type {!boolean} */
this._handled = false;
/** @type {Promise|undefined} */
this._value = undefined;
/** @type {!Array<!Function>} */
this._deferreds = [];
doResolve(fn, this);
}
function handle(self, deferred) {
while (self._state === 3) {
self = self._value;
}
if (self._state === 0) {
self._deferreds.push(deferred);
return;
}
self._handled = true;
Promise._immediateFn(function() {
var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
if (cb === null) {
(self._state === 1 ? resolve : reject)(deferred.promise, self._value);
return;
}
var ret;
try {
ret = cb(self._value);
} catch (e) {
reject(deferred.promise, e);
return;
}
resolve(deferred.promise, ret);
});
}
function resolve(self, newValue) {
try {
// Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self)
throw new TypeError('A promise cannot be resolved with itself.');
if (
newValue &&
(typeof newValue === 'object' || typeof newValue === 'function')
) {
var then = newValue.then;
if (newValue instanceof Promise) {
self._state = 3;
self._value = newValue;
finale(self);
return;
} else if (typeof then === 'function') {
doResolve(bind(then, newValue), self);
return;
}
}
self._state = 1;
self._value = newValue;
finale(self);
} catch (e) {
reject(self, e);
}
}
function reject(self, newValue) {
self._state = 2;
self._value = newValue;
finale(self);
}
function finale(self) {
if (self._state === 2 && self._deferreds.length === 0) {
Promise._immediateFn(function() {
if (!self._handled) {
Promise._unhandledRejectionFn(self._value);
}
});
}
for (var i = 0, len = self._deferreds.length; i < len; i++) {
handle(self, self._deferreds[i]);
}
self._deferreds = null;
}
/**
* @constructor
*/
function Handler(onFulfilled, onRejected, promise) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.promise = promise;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, self) {
var done = false;
try {
fn(
function(value) {
if (done) return;
done = true;
resolve(self, value);
},
function(reason) {
if (done) return;
done = true;
reject(self, reason);
}
);
} catch (ex) {
if (done) return;
done = true;
reject(self, ex);
}
}
Promise.prototype['catch'] = function(onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function(onFulfilled, onRejected) {
// @ts-ignore
var prom = new this.constructor(noop);
handle(this, new Handler(onFulfilled, onRejected, prom));
return prom;
};
Promise.prototype['finally'] = _finally__WEBPACK_IMPORTED_MODULE_0__["default"];
Promise.all = function(arr) {
return new Promise(function(resolve, reject) {
if (!arr || typeof arr.length === 'undefined')
throw new TypeError('Promise.all accepts an array');
var args = Array.prototype.slice.call(arr);
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then;
if (typeof then === 'function') {
then.call(
val,
function(val) {
res(i, val);
},
reject
);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
Promise.resolve = function(value) {
if (value && typeof value === 'object' && value.constructor === Promise) {
return value;
}
return new Promise(function(resolve) {
resolve(value);
});
};
Promise.reject = function(value) {
return new Promise(function(resolve, reject) {
reject(value);
});
};
Promise.race = function(values) {
return new Promise(function(resolve, reject) {
for (var i = 0, len = values.length; i < len; i++) {
values[i].then(resolve, reject);
}
});
};
// Use polyfill for setImmediate for performance gains
Promise._immediateFn =
(typeof setImmediate === 'function' &&
function(fn) {
setImmediate(fn);
}) ||
function(fn) {
setTimeoutFunc(fn, 0);
};
Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
if (typeof console !== 'undefined' && console) {
console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
}
};
/* harmony default export */ __webpack_exports__["default"] = (Promise);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../timers-browserify/main.js */ "./node_modules/timers-browserify/main.js").setImmediate))
/***/ }),
/***/ "./node_modules/promise-polyfill/src/polyfill.js":
/*!*******************************************************!*\
!*** ./node_modules/promise-polyfill/src/polyfill.js ***!
\*******************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index */ "./node_modules/promise-polyfill/src/index.js");
/* harmony import */ var _finally__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./finally */ "./node_modules/promise-polyfill/src/finally.js");
/** @suppress {undefinedVars} */
var globalNS = (function() {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') {
return self;
}
if (typeof window !== 'undefined') {
return window;
}
if (typeof global !== 'undefined') {
return global;
}
throw new Error('unable to locate global object');
})();
if (!('Promise' in globalNS)) {
globalNS['Promise'] = _index__WEBPACK_IMPORTED_MODULE_0__["default"];
} else if (!globalNS.Promise.prototype['finally']) {
globalNS.Promise.prototype['finally'] = _finally__WEBPACK_IMPORTED_MODULE_1__["default"];
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js")))
/***/ }),
/***/ "./node_modules/setimmediate/setImmediate.js":
/*!***************************************************!*\
!*** ./node_modules/setimmediate/setImmediate.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {(function (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var registerImmediate;
function setImmediate(callback) {
// Callback can either be a function or a string
if (typeof callback !== "function") {
callback = new Function("" + callback);
}
// Copy function arguments
var args = new Array(arguments.length - 1);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 1];
}
// Store and register the task
var task = { callback: callback, args: args };
tasksByHandle[nextHandle] = task;
registerImmediate(nextHandle);
return nextHandle++;
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function run(task) {
var callback = task.callback;
var args = task.args;
switch (args.length) {
case 0:
callback();
break;
case 1:
callback(args[0]);
break;
case 2:
callback(args[0], args[1]);
break;
case 3:
callback(args[0], args[1], args[2]);
break;
default:
callback.apply(undefined, args);
break;
}
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(runIfPresent, 0, handle);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
run(task);
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function installNextTickImplementation() {
registerImmediate = function(handle) {
process.nextTick(function () { runIfPresent(handle); });
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function() {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function(event) {
if (event.source === global &&
typeof event.data === "string" &&
event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
registerImmediate = function(handle) {
global.postMessage(messagePrefix + handle, "*");
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function(event) {
var handle = event.data;
runIfPresent(handle);
};
registerImmediate = function(handle) {
channel.port2.postMessage(handle);
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
registerImmediate = function(handle) {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var script = doc.createElement("script");
script.onreadystatechange = function () {
runIfPresent(handle);
script.onreadystatechange = null;
html.removeChild(script);
script = null;
};
html.appendChild(script);
};
}
function installSetTimeoutImplementation() {
registerImmediate = function(handle) {
setTimeout(runIfPresent, 0, handle);
};
}
// If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
// Don't get fooled by e.g. browserify environments.
if ({}.toString.call(global.process) === "[object process]") {
// For Node.js before 0.9
installNextTickImplementation();
} else if (canUsePostMessage()) {
// For non-IE10 modern browsers
installPostMessageImplementation();
} else if (global.MessageChannel) {
// For web workers, where supported
installMessageChannelImplementation();
} else if (doc && "onreadystatechange" in doc.createElement("script")) {
// For IE 6–8
installReadyStateChangeImplementation();
} else {
// For older browsers
installSetTimeoutImplementation();
}
attachTo.setImmediate = setImmediate;
attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js")))
/***/ }),
/***/ "./node_modules/stackframe/stackframe.js":
/*!***********************************************!*\
!*** ./node_modules/stackframe/stackframe.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/*** IMPORTS FROM imports-loader ***/
var define = false;
(function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define('stackframe', [], factory);
} else if (true) {
module.exports = factory();
} else {}
}(this, function() {
'use strict';
function _isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function _capitalize(str) {
return str.charAt(0).toUpperCase() + str.substring(1);
}
function _getter(p) {
return function() {
return this[p];
};
}
var booleanProps = ['isConstructor', 'isEval', 'isNative', 'isToplevel'];
var numericProps = ['columnNumber', 'lineNumber'];
var stringProps = ['fileName', 'functionName', 'source'];
var arrayProps = ['args'];
var props = booleanProps.concat(numericProps, stringProps, arrayProps);
function StackFrame(obj) {
if (obj instanceof Object) {
for (var i = 0; i < props.length; i++) {
if (obj.hasOwnProperty(props[i]) && obj[props[i]] !== undefined) {
this['set' + _capitalize(props[i])](obj[props[i]]);
}
}
}
}
StackFrame.prototype = {
getArgs: function() {
return this.args;
},
setArgs: function(v) {
if (Object.prototype.toString.call(v) !== '[object Array]') {
throw new TypeError('Args must be an Array');
}
this.args = v;
},
getEvalOrigin: function() {
return this.evalOrigin;
},
setEvalOrigin: function(v) {
if (v instanceof StackFrame) {
this.evalOrigin = v;
} else if (v instanceof Object) {
this.evalOrigin = new StackFrame(v);
} else {
throw new TypeError('Eval Origin must be an Object or StackFrame');
}
},
toString: function() {
var functionName = this.getFunctionName() || '{anonymous}';
var args = '(' + (this.getArgs() || []).join(',') + ')';
var fileName = this.getFileName() ? ('@' + this.getFileName()) : '';
var lineNumber = _isNumber(this.getLineNumber()) ? (':' + this.getLineNumber()) : '';
var columnNumber = _isNumber(this.getColumnNumber()) ? (':' + this.getColumnNumber()) : '';
return functionName + args + fileName + lineNumber + columnNumber;
}
};
for (var i = 0; i < booleanProps.length; i++) {
StackFrame.prototype['get' + _capitalize(booleanProps[i])] = _getter(booleanProps[i]);
StackFrame.prototype['set' + _capitalize(booleanProps[i])] = (function(p) {
return function(v) {
this[p] = Boolean(v);
};
})(booleanProps[i]);
}
for (var j = 0; j < numericProps.length; j++) {
StackFrame.prototype['get' + _capitalize(numericProps[j])] = _getter(numericProps[j]);
StackFrame.prototype['set' + _capitalize(numericProps[j])] = (function(p) {
return function(v) {
if (!_isNumber(v)) {
throw new TypeError(p + ' must be a Number');
}
this[p] = Number(v);
};
})(numericProps[j]);
}
for (var k = 0; k < stringProps.length; k++) {
StackFrame.prototype['get' + _capitalize(stringProps[k])] = _getter(stringProps[k]);
StackFrame.prototype['set' + _capitalize(stringProps[k])] = (function(p) {
return function(v) {
this[p] = String(v);
};
})(stringProps[k]);
}
return StackFrame;
}));
/***/ }),
/***/ "./node_modules/timers-browserify/main.js":
/*!************************************************!*\
!*** ./node_modules/timers-browserify/main.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
(typeof self !== "undefined" && self) ||
window;
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(scope, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(/*! setimmediate */ "./node_modules/setimmediate/setImmediate.js");
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto. Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
(typeof global !== "undefined" && global.setImmediate) ||
(this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
(typeof global !== "undefined" && global.clearImmediate) ||
(this && this.clearImmediate);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js")))
/***/ }),
/***/ "./node_modules/webpack/buildin/global.js":
/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/***/ "./src/client.ts":
/*!***********************!*\
!*** ./src/client.ts ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
__webpack_require__(/*! promise-polyfill/src/polyfill */ "./node_modules/promise-polyfill/src/polyfill.js");
var jsonify_notice_1 = __importDefault(__webpack_require__(/*! ./jsonify_notice */ "./src/jsonify_notice.ts"));
var stacktracejs_1 = __importDefault(__webpack_require__(/*! ./processor/stacktracejs */ "./src/processor/stacktracejs.ts"));
var angular_message_1 = __importDefault(__webpack_require__(/*! ./filter/angular_message */ "./src/filter/angular_message.ts"));
var debounce_1 = __importDefault(__webpack_require__(/*! ./filter/debounce */ "./src/filter/debounce.ts"));
var ignore_1 = __importDefault(__webpack_require__(/*! ./filter/ignore */ "./src/filter/ignore.ts"));
var node_1 = __importDefault(__webpack_require__(/*! ./filter/node */ "./src/filter/node.ts"));
var uncaught_message_1 = __importDefault(__webpack_require__(/*! ./filter/uncaught_message */ "./src/filter/uncaught_message.ts"));
var window_1 = __importDefault(__webpack_require__(/*! ./filter/window */ "./src/filter/window.ts"));
var http_req_1 = __webpack_require__(/*! ./http_req */ "./src/http_req/index.ts");
var historian_1 = __webpack_require__(/*! ./historian */ "./src/historian.ts");
var routes_1 = __webpack_require__(/*! ./routes */ "./src/routes.ts");
var Client = /** @class */ (function () {
function Client(opts) {
var _this = this;
this.filters = [];
this.offline = false;
this.todo = [];
this.onClose = [];
if (!opts.projectId || !opts.projectKey) {
throw new Error('airbrake: projectId and projectKey are required');
}
this.opts = opts;
this.opts.host = this.opts.host || 'https://api.airbrake.io';
this.opts.timeout = this.opts.timeout || 10000;
this.opts.keysBlacklist = this.opts.keysBlacklist || [/password/, /secret/];
this.url = this.opts.host + "/api/v3/projects/" + this.opts.projectId + "/notices?key=" + this.opts.projectKey;
this.processor = this.opts.processor || stacktracejs_1.default;
this.requester = http_req_1.makeRequester(this.opts);
this.addFilter(ignore_1.default);
this.addFilter(debounce_1.default());
this.addFilter(uncaught_message_1.default);
this.addFilter(angular_message_1.default);
if (!this.opts.environment &&
typeof process !== 'undefined' &&
process.env.NODE_ENV) {
this.opts.environment = process.env.NODE_ENV;
}
if (this.opts.environment) {
this.addFilter(function (notice) {
notice.context.environment = _this.opts.environment;
return notice;
});
}
if (typeof window === 'object') {
this.addFilter(window_1.default);
if (window.addEventListener) {
this.onOnline = this.onOnline.bind(this);
window.addEventListener('online', this.onOnline);
this.onOffline = this.onOffline.bind(this);
window.addEventListener('offline', this.onOffline);
this.onUnhandledrejection = this.onUnhandledrejection.bind(this);
window.addEventListener('unhandledrejection', this.onUnhandledrejection);
this.onClose.push(function () {
window.removeEventListener('online', _this.onOnline);
window.removeEventListener('offline', _this.onOffline);
window.removeEventListener('unhandledrejection', _this.onUnhandledrejection);
});
}
}
else {
this.addFilter(node_1.default);
}
var historianOpts = opts.instrumentation || {};
if (typeof historianOpts.console === undefined) {
historianOpts.console = !isDevEnv(opts.environment);
}
this.historian = historian_1.Historian.instance(historianOpts);
this.historian.registerNotifier(this);
}
Client.prototype.close = function () {
for (var _i = 0, _a = this.onClose; _i < _a.length; _i++) {
var fn = _a[_i];
fn();
}
this.historian.unregisterNotifier(this);
};
Client.prototype.addFilter = function (filter) {
this.filters.push(filter);
};
Client.prototype.notify = function (err) {
var _this = this;
var notice = {
id: '',
errors: [],
context: __assign({ severity: 'error' }, err.context),
params: err.params || {},
environment: err.environment || {},
session: err.session || {},
};
if (typeof err !== 'object' || err.error === undefined) {
err = { error: err };
}
if (!err.error) {
notice.error = new Error("airbrake: got err=" + JSON.stringify(err.error) + ", wanted an Error");
return Promise.resolve(notice);
}
if (this.opts.ignoreWindowError && err.context && err.context.windowError) {
notice.error = new Error('airbrake: window error is ignored');
return Promise.resolve(notice);
}
if (this.offline) {
return new Promise(function (resolve, reject) {
_this.todo.push({
err: err,
resolve: resolve,
reject: reject,
});
while (_this.todo.length > 100) {
var j = _this.todo.shift();
if (j === undefined) {
break;
}
notice.error = new Error('airbrake: offline queue is too large');
j.resolve(notice);
}
});
}
var history = this.historian.getHistory();
if (history.length > 0) {
notice.context.history = history;
}
var error = this.processor(err.error);
notice.errors.push(error);
for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {
var filter = _a[_i];
var r = filter(notice);
if (r === null) {
notice.error = new Error('airbrake: error is filtered');
return Promise.resolve(notice);
}
notice = r;
}
if (!notice.context) {
notice.context = {};
}
notice.context.language = 'JavaScript';
notice.context.notifier = {
name: 'airbrake-js',
version: "1.6.4",
url: 'https://github.com/airbrake/airbrake-js',
};
return this.sendNotice(notice);
};
Client.prototype.sendNotice = function (notice) {
var body = jsonify_notice_1.default(notice, {
keysBlacklist: this.opts.keysBlacklist,
});
if (this.opts.reporter) {
if (typeof this.opts.reporter === 'function') {
return this.opts.reporter(notice);
}
else {
console.warn('airbrake: options.reporter must be a function');
}
}
var req = {
method: 'POST',
url: this.url,
body: body,
};
return this.requester(req)
.then(function (resp) {
notice.id = resp.json.id;
return notice;
})
.catch(function (err) {
notice.error = err;
return notice;
});
};
// TODO: fix wrapping for multiple clients
Client.prototype.wrap = function (fn, props) {
if (props === void 0) { props = []; }
if (fn._airbrake) {
return fn;
}
// tslint:disable-next-line:no-this-assignment
var client = this;
var airbrakeWrapper = function () {
var fnArgs = Array.prototype.slice.call(arguments);
var wrappedArgs = client.wrapArguments(fnArgs);
try {
return fn.apply(this, wrappedArgs);
}
catch (err) {
client.notify({ error: err, params: { arguments: fnArgs } });
this.historian.ignoreNextWindowError();
throw err;
}
};
for (var prop in fn) {
if (fn.hasOwnProperty(prop)) {
airbrakeWrapper[prop] = fn[prop];
}
}
for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
var prop = props_1[_i];
if (fn.hasOwnProperty(prop)) {
airbrakeWrapper[prop] = fn[prop];
}
}
airbrakeWrapper._airbrake = true;
airbrakeWrapper.inner = fn;
return airbrakeWrapper;
};
Client.prototype.wrapArguments = function (args) {
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (typeof arg === 'function') {
args[i] = this.wrap(arg);
}
}
return args;
};
Client.prototype.call = function (fn) {
var _args = [];
for (var _i = 1; _i < arguments.length; _i++) {
_args[_i - 1] = arguments[_i];
}
var wrapper = this.wrap(fn);
return wrapper.apply(this, Array.prototype.slice.call(arguments, 1));
};
Client.prototype.onerror = function () {
this.historian.onerror.apply(this.historian, arguments);
};
Client.prototype.notifyRequest = function (req) {
if (!this.routes) {
this.routes = new routes_1.Routes(this.opts);
}
this.routes.notifyRequest(req);
};
Client.prototype.onOnline = function () {
this.offline = false;
var _loop_1 = function (j) {
this_1.notify(j.err).then(function (notice) {
j.resolve(notice);
});
};
var this_1 = this;
for (var _i = 0, _a = this.todo; _i < _a.length; _i++) {
var j = _a[_i];
_loop_1(j);
}
this.todo = [];
};
Client.prototype.onOffline = function () {
this.offline = true;
};
Client.prototype.onUnhandledrejection = function (e) {
// Handle native or bluebird Promise rejections
// https://developer.mozilla.org/en-US/docs/Web/Events/unhandledrejection
// http://bluebirdjs.com/docs/api/error-management-configuration.html
var reason = e.reason ||
(e.detail && e.detail.reason) ||
'unhandled rejection with no reason given';
var msg = reason.message || String(reason);
if (msg.indexOf && msg.indexOf('airbrake: ') === 0) {
return;
}
this.notify(reason);
};
return Client;
}());
function isDevEnv(env) {
return env && env.startsWith && env.startsWith('dev');
}
module.exports = Client;
/***/ }),
/***/ "./src/filter/angular_message.ts":
/*!***************************************!*\
!*** ./src/filter/angular_message.ts ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var re = new RegExp([
'^',
'\\[(\\$.+)\\]',
'\\s',
'([\\s\\S]+)',
'$',
].join(''));
function filter(notice) {
var err = notice.errors[0];
if (err.type !== '' && err.type !== 'Error') {
return notice;
}
var m = err.message.match(re);
if (m !== null) {
err.type = m[1];
err.message = m[2];
}
return notice;
}
exports.default = filter;
/***/ }),
/***/ "./src/filter/debounce.ts":
/*!********************************!*\
!*** ./src/filter/debounce.ts ***!
\********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function makeFilter() {
var lastNoticeJSON;
var timeout;
return function (notice) {
var s = JSON.stringify(notice.errors);
if (s === lastNoticeJSON) {
return null;
}
if (timeout) {
clearTimeout(timeout);
}
lastNoticeJSON = s;
timeout = setTimeout(function () {
lastNoticeJSON = '';
}, 1000);
return notice;
};
}
exports.default = makeFilter;
/***/ }),
/***/ "./src/filter/ignore.ts":
/*!******************************!*\
!*** ./src/filter/ignore.ts ***!
\******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var IGNORED_MESSAGES = [
'Script error',
'Script error.',
'InvalidAccessError',
];
function filter(notice) {
var err = notice.errors[0];
if (err.type === '' && IGNORED_MESSAGES.indexOf(err.message) !== -1) {
return null;
}
if (err.backtrace && err.backtrace.length > 0) {
var frame = err.backtrace[0];
if (frame.file === '<anonymous>') {
return null;
}
}
return notice;
}
exports.default = filter;
/***/ }),
/***/ "./src/filter/node.ts":
/*!****************************!*\
!*** ./src/filter/node.ts ***!
\****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function filter(notice) {
var os;
try {
os = __webpack_require__(/*! os */ "os");
}
catch (_) {
// ignore
}
if (os) {
notice.context.os = os.type() + "/" + os.release();
notice.context.architecture = os.arch();
notice.context.hostname = os.hostname();
notice.params.os = {
homedir: os.homedir(),
uptime: os.uptime(),
freemem: os.freemem(),
totalmem: os.totalmem(),
loadavg: os.loadavg(),
};
}
if (process) {
notice.context.platform = process.platform;
if (!notice.context.rootDirectory) {
notice.context.rootDirectory = process.cwd();
}
notice.params.process = {
pid: process.pid,
cwd: process.cwd(),
execPath: process.execPath,
argv: process.argv,
};
['uptime', 'cpuUsage', 'memoryUsage'].map(function (name) {
if (process[name]) {
notice.params.process[name] = process[name]();
}
});
}
return notice;
}
exports.default = filter;
/***/ }),
/***/ "./src/filter/uncaught_message.ts":
/*!****************************************!*\
!*** ./src/filter/uncaught_message.ts ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var re = new RegExp([
'^',
'Uncaught\\s',
'(.+?)',
':\\s',
'(.+)',
'$',
].join(''));
function filter(notice) {
var err = notice.errors[0];
if (err.type !== '' && err.type !== 'Error') {
return notice;
}
var m = err.message.match(re);
if (m !== null) {
err.type = m[1];
err.message = m[2];
}
return notice;
}
exports.default = filter;
/***/ }),
/***/ "./src/filter/window.ts":
/*!******************************!*\
!*** ./src/filter/window.ts ***!
\******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function filter(notice) {
if (window.navigator && window.navigator.userAgent) {
notice.context.userAgent = window.navigator.userAgent;
}
if (window.location) {
notice.context.url = String(window.location);
// Set root directory to group errors on different subdomains together.
notice.context.rootDirectory =
window.location.protocol + '//' + window.location.host;
}
return notice;
}
exports.default = filter;
/***/ }),
/***/ "./src/historian.ts":
/*!**************************!*\
!*** ./src/historian.ts ***!
\**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var dom_1 = __webpack_require__(/*! ./instrumentation/dom */ "./src/instrumentation/dom.ts");
var CONSOLE_METHODS = ['debug', 'log', 'info', 'warn', 'error'];
var Historian = /** @class */ (function () {
function Historian(opts) {
if (opts === void 0) { opts = {}; }
var _this = this;
this.historyMaxLen = 20;
this.notifiers = [];
this.errors = [];
this.ignoreWindowError = 0;
this.history = [];
this.ignoreNextXHR = 0;
if (enabled(opts.console) && typeof console === 'object' && console.error) {
this.consoleError = console.error;
}
if (typeof window === 'object') {
if (enabled(opts.onerror)) {
// tslint:disable-next-line:no-this-assignment
var self_1 = this;
var oldHandler_1 = window.onerror;
window.onerror = function () {
if (oldHandler_1) {
oldHandler_1.apply(this, arguments);
}
self_1.onerror.apply(self_1, arguments);
};
}
this.domEvents();
if (enabled(opts.fetch) && typeof fetch === 'function') {
this.fetch();
}
if (enabled(opts.history) && typeof history === 'object') {
this.location();
}
}
if (typeof process === 'object' && typeof process.on === 'function') {
process.on('uncaughtException', function (err) {
_this.notify(err).then(function () {
if (process.listeners('uncaughtException').length !== 1) {
return;
}
if (_this.consoleError) {
_this.consoleError('uncaught exception', err);
}
process.exit(1);
});
});
process.on('unhandledRejection', function (reason, _p) {
var msg = reason.message || String(reason);
if (msg.indexOf && msg.indexOf('airbrake: ') === 0) {
return;
}
_this.notify(reason).then(function () {
if (process.listeners('unhandledRejection').length !== 1) {
return;
}
if (_this.consoleError) {
_this.consoleError('unhandled rejection', reason);
}
process.exit(1);
});
});
}
if (enabled(opts.console) && typeof console === 'object') {
this.console();
}
if (enabled(opts.xhr) && typeof XMLHttpRequest !== 'undefined') {
this.xhr();
}
}
Historian.instance = function (opts) {
if (opts === void 0) { opts = {}; }
if (!Historian._instance) {
Historian._instance = new Historian(opts);
}
return Historian._instance;
};
Historian.prototype.registerNotifier = function (notifier) {
this.notifiers.push(notifier);
for (var _i = 0, _a = this.errors; _i < _a.length; _i++) {
var err = _a[_i];
this.notifyNotifiers(err);
}
this.errors = [];
};
Historian.prototype.unregisterNotifier = function (notifier) {
var i = this.notifiers.indexOf(notifier);
if (i !== -1) {
this.notifiers.splice(i, 1);
}
};
Historian.prototype.notify = function (err) {
if (this.notifiers.length > 0) {
return this.notifyNotifiers(err);
}
this.errors.push(err);
if (this.errors.length > this.historyMaxLen) {
this.errors = this.errors.slice(-this.historyMaxLen);
}
return Promise.resolve(null);
};
Historian.prototype.notifyNotifiers = function (err) {
var promises = [];
for (var _i = 0, _a = this.notifiers; _i < _a.length; _i++) {
var notifier = _a[_i];
promises.push(notifier.notify(err));
}
return Promise.all(promises).then(function (notices) {
return notices[0];
});
};
Historian.prototype.onerror = function (message, filename, line, column, err) {
if (this.ignoreWindowError > 0) {
return;
}
if (err) {
this.notify({
error: err,
context: {
windowError: true,
},
});
return;
}
// Ignore errors without file or line.
if (!filename || !line) {
return;
}
this.notify({
error: {
message: message,
fileName: filename,
lineNumber: line,
columnNumber: column,
noStack: true,
},
context: {
windowError: true,
},
});
};
Historian.prototype.ignoreNextWindowError = function () {
var _this = this;
this.ignoreWindowError++;
setTimeout(function () { return _this.ignoreWindowError--; });
};
Historian.prototype.getHistory = function () {
return this.history;
};
Historian.prototype.pushHistory = function (state) {
if (this.isDupState(state)) {
if (this.lastState.num) {
this.lastState.num++;
}
else {
this.lastState.num = 2;
}
return;
}
if (!state.date) {
state.date = new Date();
}
this.history.push(state);
this.lastState = state;
if (this.history.length > this.historyMaxLen) {
this.history = this.history.slice(-this.historyMaxLen);
}
};
Historian.prototype.isDupState = function (state) {
if (!this.lastState) {
return false;
}
for (var key in state) {
if (!state.hasOwnProperty(key) || key === 'date') {
continue;
}
if (state[key] !== this.lastState[key]) {
return false;
}
}
return true;
};
Historian.prototype.domEvents = function () {
var handler = dom_1.makeEventHandler(this);
if (window.addEventListener) {
window.addEventListener('load', handler);
window.addEventListener('error', function (event) {
if ('error' in event) {
return;
}
handler(event);
}, true);
}
if (typeof document === 'object' && document.addEventListener) {
document.addEventListener('DOMContentLoaded', handler);
document.addEventListener('click', handler);
document.addEventListener('keypress', handler);
}
};
Historian.prototype.console = function () {
// tslint:disable-next-line:no-this-assignment
var client = this;
var _loop_1 = function (m) {
if (!(m in console)) {
return "continue";
}
var oldFn = console[m];
var newFn = (function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
oldFn.apply(console, args);
client.pushHistory({
type: 'log',
severity: m,
arguments: args,
});
});
newFn.inner = oldFn;
console[m] = newFn;
};
for (var _i = 0, CONSOLE_METHODS_1 = CONSOLE_METHODS; _i < CONSOLE_METHODS_1.length; _i++) {
var m = CONSOLE_METHODS_1[_i];
_loop_1(m);
}
};
Historian.prototype.unwrapConsole = function () {
for (var _i = 0, CONSOLE_METHODS_2 = CONSOLE_METHODS; _i < CONSOLE_METHODS_2.length; _i++) {
var m = CONSOLE_METHODS_2[_i];
if (m in console && console[m].inner) {
console[m] = console[m].inner;
}
}
};
Historian.prototype.fetch = function () {
// tslint:disable-next-line:no-this-assignment
var client = this;
var oldFetch = window.fetch;
window.fetch = function (input, init) {
var state = {
type: 'xhr',
date: new Date(),
};
state.url = typeof input === 'string' ? input : input.url;
state.method = init && init.method ? init.method : 'GET';
// Some platforms (e.g. react-native) implement fetch via XHR.
client.ignoreNextXHR++;
setTimeout(function () { return client.ignoreNextXHR--; });
return oldFetch
.apply(this, arguments)
.then(function (resp) {
state.statusCode = resp.status;
state.duration = new Date().getTime() - state.date.getTime();
client.pushHistory(state);
return resp;
})
.catch(function (err) {
state.error = err;
state.duration = new Date().getTime() - state.date.getTime();
client.pushHistory(state);
throw err;
});
};
};
Historian.prototype.xhr = function () {
// tslint:disable-next-line:no-this-assignment
var client = this;
var oldOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, _async, _user, _password) {
if (client.ignoreNextXHR === 0) {
this.__state = {
type: 'xhr',
method: method,
url: url,
};
}
oldOpen.apply(this, arguments);
};
var oldSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (_data) {
var oldFn = this.onreadystatechange;
this.onreadystatechange = function (_ev) {
if (this.readyState === 4 && this.__state) {
client.recordReq(this);
}
if (oldFn) {
return oldFn.apply(this, arguments);
}
};
if (this.__state) {
this.__state.date = new Date();
}
return oldSend.apply(this, arguments);
};
};
Historian.prototype.recordReq = function (req) {
var state = req.__state;
state.statusCode = req.status;
state.duration = new Date().getTime() - state.date.getTime();
this.pushHistory(state);
};
Historian.prototype.location = function () {
this.lastLocation = document.location.pathname;
// tslint:disable-next-line:no-this-assignment
var client = this;
var oldFn = window.onpopstate;
window.onpopstate = function (_event) {
client.recordLocation(document.location.pathname);
if (oldFn) {
return oldFn.apply(this, arguments);
}
};
var oldPushState = history.pushState;
history.pushState = function (_state, _title, url) {
if (url) {
client.recordLocation(url.toString());
}
oldPushState.apply(this, arguments);
};
};
Historian.prototype.recordLocation = function (url) {
var index = url.indexOf('://');
if (index >= 0) {
url = url.slice(index + 3);
index = url.indexOf('/');
url = index >= 0 ? url.slice(index) : '/';
}
else if (url.charAt(0) !== '/') {
url = '/' + url;
}
this.pushHistory({
type: 'location',
from: this.lastLocation,
to: url,
});
this.lastLocation = url;
};
return Historian;
}());
exports.Historian = Historian;
function enabled(v) {
return v === undefined || v === true;
}
/***/ }),
/***/ "./src/http_req/fetch.ts":
/*!*******************************!*\
!*** ./src/http_req/fetch.ts ***!
\*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// tslint:disable-next-line:no-var-requires
var fetch = __webpack_require__(/*! cross-fetch */ "cross-fetch");
var index_1 = __webpack_require__(/*! ./index */ "./src/http_req/index.ts");
var rateLimitReset = 0;
function request(req) {
var utime = Date.now() / 1000;
if (utime < rateLimitReset) {
return Promise.reject(index_1.errors.ipRateLimited);
}
var opt = {
method: req.method,
body: req.body,
};
return fetch(req.url, opt).then(function (resp) {
if (resp.status === 401) {
throw index_1.errors.unauthorized;
}
if (resp.status === 429) {
var s = resp.headers.get('X-RateLimit-Delay');
if (!s) {
throw index_1.errors.ipRateLimited;
}
var n = parseInt(s, 10);
if (n > 0) {
rateLimitReset = Date.now() / 1000 + n;
}
throw index_1.errors.ipRateLimited;
}
if (resp.status === 204) {
return { json: null };
}
if (resp.status >= 200 && resp.status < 300) {
return resp.json().then(function (json) {
return { json: json };
});
}
if (resp.status >= 400 && resp.status < 500) {
return resp.json().then(function (json) {
var err = new Error(json.message);
throw err;
});
}
return resp.text().then(function (body) {
var err = new Error("airbrake: fetch: unexpected response: code=" + resp.status + " body='" + body + "'");
throw err;
});
});
}
exports.request = request;
/***/ }),
/***/ "./src/http_req/index.ts":
/*!*******************************!*\
!*** ./src/http_req/index.ts ***!
\*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fetch_1 = __webpack_require__(/*! ./fetch */ "./src/http_req/fetch.ts");
var node_1 = __webpack_require__(/*! ./node */ "./src/http_req/node.ts");
function makeRequester(opts) {
if (opts.request) {
return node_1.makeRequester(opts.request);
}
return fetch_1.request;
}
exports.makeRequester = makeRequester;
exports.errors = {
unauthorized: new Error('airbrake: unauthorized: project id or key are wrong'),
ipRateLimited: new Error('airbrake: IP is rate limited'),
};
/***/ }),
/***/ "./src/http_req/node.ts":
/*!******************************!*\
!*** ./src/http_req/node.ts ***!
\******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var index_1 = __webpack_require__(/*! ./index */ "./src/http_req/index.ts");
function makeRequester(api) {
return function (req) {
return request(req, api);
};
}
exports.makeRequester = makeRequester;
var rateLimitReset = 0;
function request(req, api) {
var utime = Date.now() / 1000;
if (utime < rateLimitReset) {
return Promise.reject(index_1.errors.ipRateLimited);
}
return new Promise(function (resolve, reject) {
api({
url: req.url,
method: req.method,
body: req.body,
headers: {
'content-type': 'application/json',
},
timeout: req.timeout,
}, function (error, resp, body) {
if (error) {
reject(error);
return;
}
if (!resp.statusCode) {
error = new Error("airbrake: request: response statusCode is " + resp.statusCode);
reject(error);
return;
}
if (resp.statusCode === 401) {
reject(index_1.errors.unauthorized);
return;
}
if (resp.statusCode === 429) {
reject(index_1.errors.ipRateLimited);
var h = resp.headers['x-ratelimit-delay'];
if (!h) {
return;
}
var s = void 0;
if (typeof h === 'string') {
s = h;
}
else if (h instanceof Array) {
s = h[0];
}
else {
return;
}
var n = parseInt(s, 10);
if (n > 0) {
rateLimitReset = Date.now() / 1000 + n;
}
return;
}
if (resp.statusCode === 204) {
resolve({ json: null });
return;
}
if (resp.statusCode >= 200 && resp.statusCode < 300) {
var json = void 0;
try {
json = JSON.parse(body);
}
catch (err) {
reject(err);
return;
}
resolve(json);
return;
}
if (resp.statusCode >= 400 && resp.statusCode < 500) {
var json = void 0;
try {
json = JSON.parse(body);
}
catch (err) {
reject(err);
return;
}
error = new Error(json.message);
reject(error);
return;
}
body = body.trim();
error = new Error("airbrake: node: unexpected response: code=" + resp.statusCode + " body='" + body + "'");
reject(error);
});
});
}
/***/ }),
/***/ "./src/instrumentation/dom.ts":
/*!************************************!*\
!*** ./src/instrumentation/dom.ts ***!
\************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var elemAttrs = ['type', 'name', 'src'];
function elemName(elem) {
if (!elem) {
return '';
}
var s = [];
if (elem.tagName) {
s.push(elem.tagName.toLowerCase());
}
if (elem.id) {
s.push('#');
s.push(elem.id);
}
if (elem.classList) {
s.push('.');
s.push(Array.from(elem.classList).join('.'));
}
else if (elem.className) {
var str = classNameString(elem.className);
if (str !== '') {
s.push('.');
s.push(str);
}
}
if (elem.getAttribute) {
for (var _i = 0, elemAttrs_1 = elemAttrs; _i < elemAttrs_1.length; _i++) {
var attr = elemAttrs_1[_i];
var value = elem.getAttribute(attr);
if (value) {
s.push("[" + attr + "=\"" + value + "\"]");
}
}
}
return s.join('');
}
function classNameString(name) {
if (name.split) {
return name.split(' ').join('.');
}
if (name.baseVal && name.baseVal.split) {
// SVGAnimatedString
return name.baseVal.split(' ').join('.');
}
console.error('unsupported HTMLElement.className type', typeof name);
return '';
}
function elemPath(elem) {
var maxLen = 10;
var path = [];
var parent = elem;
while (parent) {
var name_1 = elemName(parent);
if (name_1 !== '') {
path.push(name_1);
if (path.length > maxLen) {
break;
}
}
parent = parent.parentNode;
}
if (path.length === 0) {
return String(elem);
}
return path.reverse().join(' > ');
}
function makeEventHandler(client) {
return function (event) {
var target;
try {
target = event.target;
}
catch (_) {
return;
}
if (!target) {
return;
}
var state = { type: event.type };
try {
state.target = elemPath(target);
}
catch (err) {
state.target = "<" + String(err) + ">";
}
client.pushHistory(state);
};
}
exports.makeEventHandler = makeEventHandler;
/***/ }),
/***/ "./src/jsonify_notice.ts":
/*!*******************************!*\
!*** ./src/jsonify_notice.ts ***!
\*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FILTERED = '[Filtered]';
var MAX_OBJ_LENGTH = 128;
// jsonifyNotice serializes notice to JSON and truncates params,
// environment and session keys.
function jsonifyNotice(notice, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.maxLength, maxLength = _c === void 0 ? 64000 : _c, _d = _b.keysBlacklist, keysBlacklist = _d === void 0 ? [] : _d;
if (notice.errors) {
for (var i = 0; i < notice.errors.length; i++) {
var t = new Truncator({ keysBlacklist: keysBlacklist });
notice.errors[i] = t.truncate(notice.errors[i]);
}
}
var s = '';
var keys = ['context', 'params', 'environment', 'session'];
for (var level = 0; level < 8; level++) {
var opts = { level: level, keysBlacklist: keysBlacklist };
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
var obj = notice[key];
if (obj) {
notice[key] = truncate(obj, opts);
}
}
s = JSON.stringify(notice);
if (s.length < maxLength) {
return s;
}
}
var params = {
json: s.slice(0, Math.floor(maxLength / 2)) + '...',
};
keys.push('errors');
for (var _e = 0, keys_2 = keys; _e < keys_2.length; _e++) {
var key = keys_2[_e];
var obj = notice[key];
if (!obj) {
continue;
}
s = JSON.stringify(obj);
params[key] = s.length;
}
var err = new Error("airbrake: notice exceeds max length and can't be truncated");
err.params = params;
throw err;
}
exports.default = jsonifyNotice;
function scale(num, level) {
return num >> level || 1;
}
var Truncator = /** @class */ (function () {
function Truncator(opts) {
this.maxStringLength = 1024;
this.maxObjectLength = MAX_OBJ_LENGTH;
this.maxArrayLength = MAX_OBJ_LENGTH;
this.maxDepth = 8;
this.keys = [];
this.keysBlacklist = [];
this.seen = [];
var level = opts.level || 0;
this.keysBlacklist = opts.keysBlacklist || [];
this.maxStringLength = scale(this.maxStringLength, level);
this.maxObjectLength = scale(this.maxObjectLength, level);
this.maxArrayLength = scale(this.maxArrayLength, level);
this.maxDepth = scale(this.maxDepth, level);
}
Truncator.prototype.truncate = function (value, key, depth) {
if (key === void 0) { key = ''; }
if (depth === void 0) { depth = 0; }
if (value === null || value === undefined) {
return value;
}
switch (typeof value) {
case 'boolean':
case 'number':
case 'function':
return value;
case 'string':
return this.truncateString(value);
case 'object':
break;
default:
return this.truncateString(String(value));
}
if (value instanceof String) {
return this.truncateString(value.toString());
}
if (value instanceof Boolean ||
value instanceof Number ||
value instanceof Date ||
value instanceof RegExp) {
return value;
}
if (value instanceof Error) {
return this.truncateString(value.toString());
}
if (this.seen.indexOf(value) >= 0) {
return "[Circular " + this.getPath(value) + "]";
}
var type = objectType(value);
depth++;
if (depth > this.maxDepth) {
return "[Truncated " + type + "]";
}
this.keys.push(key);
this.seen.push(value);
switch (type) {
case 'Array':
return this.truncateArray(value, depth);
case 'Object':
return this.truncateObject(value, depth);
default:
var saved = this.maxDepth;
this.maxDepth = 0;
var obj = this.truncateObject(value, depth);
obj.__type = type;
this.maxDepth = saved;
return obj;
}
};
Truncator.prototype.getPath = function (value) {
var index = this.seen.indexOf(value);
var path = [this.keys[index]];
for (var i = index; i >= 0; i--) {
var sub = this.seen[i];
if (sub && getAttr(sub, path[0]) === value) {
value = sub;
path.unshift(this.keys[i]);
}
}
return '~' + path.join('.');
};
Truncator.prototype.truncateString = function (s) {
if (s.length > this.maxStringLength) {
return s.slice(0, this.maxStringLength) + '...';
}
return s;
};
Truncator.prototype.truncateArray = function (arr, depth) {
if (depth === void 0) { depth = 0; }
var length = 0;
var dst = [];
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
dst.push(this.truncate(el, i.toString(), depth));
length++;
if (length >= this.maxArrayLength) {
break;
}
}
return dst;
};
Truncator.prototype.truncateObject = function (obj, depth) {
if (depth === void 0) { depth = 0; }
var length = 0;
var dst = {};
for (var key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
continue;
}
if (isBlacklisted(key, this.keysBlacklist)) {
dst[key] = FILTERED;
continue;
}
var value = getAttr(obj, key);
if (value === undefined || typeof value === 'function') {
continue;
}
dst[key] = this.truncate(value, key, depth);
length++;
if (length >= this.maxObjectLength) {
break;
}
}
return dst;
};
return Truncator;
}());
function truncate(value, opts) {
if (opts === void 0) { opts = {}; }
var t = new Truncator(opts);
return t.truncate(value);
}
exports.truncate = truncate;
function getAttr(obj, attr) {
// Ignore browser specific exception trying to read an attribute (#79).
try {
return obj[attr];
}
catch (_) {
return;
}
}
function objectType(obj) {
var s = Object.prototype.toString.apply(obj);
return s.slice('[object '.length, -1);
}
function isBlacklisted(key, keysBlacklist) {
for (var _i = 0, keysBlacklist_1 = keysBlacklist; _i < keysBlacklist_1.length; _i++) {
var v = keysBlacklist_1[_i];
if (v === key) {
return true;
}
if (v instanceof RegExp) {
if (key.match(v)) {
return true;
}
}
}
return false;
}
/***/ }),
/***/ "./src/processor/stacktracejs.ts":
/*!***************************************!*\
!*** ./src/processor/stacktracejs.ts ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ErrorStackParser = __webpack_require__(/*! error-stack-parser */ "./node_modules/error-stack-parser/error-stack-parser.js");
var hasConsole = typeof console === 'object' && console.warn;
function parse(err) {
try {
return ErrorStackParser.parse(err);
}
catch (parseErr) {
if (hasConsole && err.stack) {
console.warn('ErrorStackParser:', parseErr.toString(), err.stack);
}
}
if (err.fileName) {
return [err];
}
return [];
}
function processor(err) {
var backtrace = [];
if (!err.noStack) {
var frames_2 = parse(err);
if (frames_2.length === 0) {
try {
throw new Error('fake');
}
catch (fakeErr) {
frames_2 = parse(fakeErr);
frames_2.shift();
frames_2.shift();
}
}
for (var _i = 0, frames_1 = frames_2; _i < frames_1.length; _i++) {
var frame = frames_1[_i];
backtrace.push({
function: frame.functionName || '',
file: frame.fileName || '',
line: frame.lineNumber || 0,
column: frame.columnNumber || 0,
});
}
}
var type = err.name ? err.name : '';
var msg = err.message ? String(err.message) : String(err);
return {
type: type,
message: msg,
backtrace: backtrace,
};
}
exports.default = processor;
/***/ }),
/***/ "./src/routes.ts":
/*!***********************!*\
!*** ./src/routes.ts ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var http_req_1 = __webpack_require__(/*! ./http_req */ "./src/http_req/index.ts");
var FLUSH_INTERVAL = 15000; // 15 seconds
var Routes = /** @class */ (function () {
function Routes(opts) {
// TODO: use RouteKey as map key
this.m = {};
this.opts = opts;
this.url = this.opts.host + "/api/v5/projects/" + this.opts.projectId + "/routes-stats?key=" + this.opts.projectKey;
this.requester = http_req_1.makeRequester(this.opts);
}
Routes.prototype.notifyRequest = function (req) {
var _this = this;
var ms = durationMs(req.start, req.end);
if (ms === 0) {
ms = 0.1;
}
var minute = 60 * 1000;
req.start = new Date(Math.floor(toTime(req.start) / minute) * minute);
var key = {
method: req.method,
route: req.route,
statusCode: req.statusCode,
time: req.start,
};
var keyStr = JSON.stringify(key);
var stat;
if (keyStr in this.m) {
stat = this.m[keyStr];
}
else {
stat = {
count: 0,
sum: 0,
sumsq: 0,
};
if (this.opts.TDigest) {
stat.tdigest = new this.opts.TDigest();
}
this.m[keyStr] = stat;
}
stat.count++;
stat.sum += ms;
stat.sumsq += ms * ms;
if (stat.tdigest) {
stat.tdigest.push(ms);
}
if (this.timer) {
return;
}
this.timer = setTimeout(function () {
_this.flush();
}, FLUSH_INTERVAL);
};
Routes.prototype.flush = function () {
var routes = [];
for (var keyStr in this.m) {
if (!this.m.hasOwnProperty(keyStr)) {
continue;
}
var key = JSON.parse(keyStr);
var v = __assign({}, key, this.m[keyStr]);
if (v.tdigest) {
v.tdigestCentroids = this.tdigestCentroids(v.tdigest);
delete v.tdigest;
}
routes.push(v);
}
this.m = {};
this.timer = null;
var req = {
method: 'POST',
url: this.url,
body: JSON.stringify({ routes: routes }),
};
this.requester(req)
.then(function (_resp) {
// nothing
})
.catch(function (err) {
if (console.error) {
console.error('can not report routes stats', err);
}
});
};
Routes.prototype.tdigestCentroids = function (td) {
var means = [];
var counts = [];
td.centroids.each(function (c) {
means.push(c.mean);
counts.push(c.n);
});
return {
mean: means,
count: counts,
};
};
return Routes;
}());
exports.Routes = Routes;
var NS_PER_MS = 1e6;
function toTime(tm) {
if (tm instanceof Date) {
return tm.getTime();
}
if (typeof tm === 'number') {
return tm;
}
if (tm instanceof Array) {
return tm[0] + tm[1] / NS_PER_MS;
}
throw new Error("unsupported type: " + typeof tm);
}
function durationMs(start, end) {
if (start instanceof Date && end instanceof Date) {
return end.getTime() - start.getTime();
}
if (typeof start === 'number' && typeof end === 'number') {
return end - start;
}
if (start instanceof Array && end instanceof Array) {
var ms = end[0] - start[0];
ms += (end[1] - start[1]) / NS_PER_MS;
return ms;
}
throw new Error("unsupported type: " + typeof start);
}
/***/ }),
/***/ 0:
/*!*****************************!*\
!*** multi ./src/client.ts ***!
\*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./src/client.ts */"./src/client.ts");
/***/ }),
/***/ "cross-fetch":
/*!********************************************************************************************************!*\
!*** external {"commonjs":"cross-fetch","commonjs2":"cross-fetch","amd":"cross-fetch","root":"fetch"} ***!
\********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_cross_fetch__;
/***/ }),
/***/ "os":
/*!**************************************************************!*\
!*** external {"commonjs":"os","commonjs2":"os","amd":"os"} ***!
\**************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
if(typeof __WEBPACK_EXTERNAL_MODULE_os__ === 'undefined') {var e = new Error("Cannot find module 'undefined'"); e.code = 'MODULE_NOT_FOUND'; throw e;}
module.exports = __WEBPACK_EXTERNAL_MODULE_os__;
/***/ })
/******/ });
});
//# sourceMappingURL=client.js.map | extend1994/cdnjs | ajax/libs/airbrake-js/1.6.4/client.js | JavaScript | mit | 89,299 |
/**
* @license Highcharts JS v7.1.3 (2019-08-14)
*
* Sonification module
*
* (c) 2012-2019 Øystein Moseng
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/modules/sonification', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'modules/sonification/Instrument.js', [_modules['parts/Globals.js']], function (H) {
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Instrument class for sonification module.
*
* License: www.highcharts.com/license
*
* */
/**
* A set of options for the Instrument class.
*
* @requires module:modules/sonification
*
* @interface Highcharts.InstrumentOptionsObject
*//**
* The type of instrument. Currently only `oscillator` is supported. Defaults
* to `oscillator`.
* @name Highcharts.InstrumentOptionsObject#type
* @type {string|undefined}
*//**
* The unique ID of the instrument. Generated if not supplied.
* @name Highcharts.InstrumentOptionsObject#id
* @type {string|undefined}
*//**
* When using functions to determine frequency or other parameters during
* playback, this options specifies how often to call the callback functions.
* Number given in milliseconds. Defaults to 20.
* @name Highcharts.InstrumentOptionsObject#playCallbackInterval
* @type {number|undefined}
*//**
* A list of allowed frequencies for this instrument. If trying to play a
* frequency not on this list, the closest frequency will be used. Set to `null`
* to allow all frequencies to be used. Defaults to `null`.
* @name Highcharts.InstrumentOptionsObject#allowedFrequencies
* @type {Array<number>|undefined}
*//**
* Options specific to oscillator instruments.
* @name Highcharts.InstrumentOptionsObject#oscillator
* @type {Highcharts.OscillatorOptionsObject|undefined}
*/
/**
* Options for playing an instrument.
*
* @requires module:modules/sonification
*
* @interface Highcharts.InstrumentPlayOptionsObject
*//**
* The frequency of the note to play. Can be a fixed number, or a function. The
* function receives one argument: the relative time of the note playing (0
* being the start, and 1 being the end of the note). It should return the
* frequency number for each point in time. The poll interval of this function
* is specified by the Instrument.playCallbackInterval option.
* @name Highcharts.InstrumentPlayOptionsObject#frequency
* @type {number|Function}
*//**
* The duration of the note in milliseconds.
* @name Highcharts.InstrumentPlayOptionsObject#duration
* @type {number}
*//**
* The minimum frequency to allow. If the instrument has a set of allowed
* frequencies, the closest frequency is used by default. Use this option to
* stop too low frequencies from being used.
* @name Highcharts.InstrumentPlayOptionsObject#minFrequency
* @type {number|undefined}
*//**
* The maximum frequency to allow. If the instrument has a set of allowed
* frequencies, the closest frequency is used by default. Use this option to
* stop too high frequencies from being used.
* @name Highcharts.InstrumentPlayOptionsObject#maxFrequency
* @type {number|undefined}
*//**
* The volume of the instrument. Can be a fixed number between 0 and 1, or a
* function. The function receives one argument: the relative time of the note
* playing (0 being the start, and 1 being the end of the note). It should
* return the volume for each point in time. The poll interval of this function
* is specified by the Instrument.playCallbackInterval option. Defaults to 1.
* @name Highcharts.InstrumentPlayOptionsObject#volume
* @type {number|Function|undefined}
*//**
* The panning of the instrument. Can be a fixed number between -1 and 1, or a
* function. The function receives one argument: the relative time of the note
* playing (0 being the start, and 1 being the end of the note). It should
* return the panning value for each point in time. The poll interval of this
* function is specified by the Instrument.playCallbackInterval option.
* Defaults to 0.
* @name Highcharts.InstrumentPlayOptionsObject#pan
* @type {number|Function|undefined}
*//**
* Callback function to be called when the play is completed.
* @name Highcharts.InstrumentPlayOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* @requires module:modules/sonification
*
* @interface Highcharts.OscillatorOptionsObject
*//**
* The waveform shape to use for oscillator instruments. Defaults to `sine`.
* @name Highcharts.OscillatorOptionsObject#waveformShape
* @type {string|undefined}
*/
// Default options for Instrument constructor
var defaultOptions = {
type: 'oscillator',
playCallbackInterval: 20,
oscillator: {
waveformShape: 'sine'
}
};
/**
* The Instrument class. Instrument objects represent an instrument capable of
* playing a certain pitch for a specified duration.
*
* @sample highcharts/sonification/instrument/
* Using Instruments directly
* @sample highcharts/sonification/instrument-advanced/
* Using callbacks for instrument parameters
*
* @requires module:modules/sonification
*
* @class
* @name Highcharts.Instrument
*
* @param {Highcharts.InstrumentOptionsObject} options
* Options for the instrument instance.
*/
function Instrument(options) {
this.init(options);
}
Instrument.prototype.init = function (options) {
if (!this.initAudioContext()) {
H.error(29);
return;
}
this.options = H.merge(defaultOptions, options);
this.id = this.options.id = options && options.id || H.uniqueKey();
// Init the audio nodes
var ctx = H.audioContext;
this.gainNode = ctx.createGain();
this.setGain(0);
this.panNode = ctx.createStereoPanner && ctx.createStereoPanner();
if (this.panNode) {
this.setPan(0);
this.gainNode.connect(this.panNode);
this.panNode.connect(ctx.destination);
} else {
this.gainNode.connect(ctx.destination);
}
// Oscillator initialization
if (this.options.type === 'oscillator') {
this.initOscillator(this.options.oscillator);
}
// Init timer list
this.playCallbackTimers = [];
};
/**
* Return a copy of an instrument. Only one instrument instance can play at a
* time, so use this to get a new copy of the instrument that can play alongside
* it. The new instrument copy will receive a new ID unless one is supplied in
* options.
*
* @function Highcharts.Instrument#copy
*
* @param {Highcharts.InstrumentOptionsObject} [options]
* Options to merge in for the copy.
*
* @return {Highcharts.Instrument}
* A new Instrument instance with the same options.
*/
Instrument.prototype.copy = function (options) {
return new Instrument(H.merge(this.options, { id: null }, options));
};
/**
* Init the audio context, if we do not have one.
* @private
* @return {boolean} True if successful, false if not.
*/
Instrument.prototype.initAudioContext = function () {
var Context = H.win.AudioContext || H.win.webkitAudioContext,
hasOldContext = !!H.audioContext;
if (Context) {
H.audioContext = H.audioContext || new Context();
if (
!hasOldContext &&
H.audioContext &&
H.audioContext.state === 'running'
) {
H.audioContext.suspend(); // Pause until we need it
}
return !!(
H.audioContext &&
H.audioContext.createOscillator &&
H.audioContext.createGain
);
}
return false;
};
/**
* Init an oscillator instrument.
* @private
* @param {object} oscillatorOptions - The oscillator options passed to
* Highcharts.Instrument#init.
*/
Instrument.prototype.initOscillator = function (options) {
var ctx = H.audioContext;
this.oscillator = ctx.createOscillator();
this.oscillator.type = options.waveformShape;
this.oscillator.connect(this.gainNode);
this.oscillatorStarted = false;
};
/**
* Set pan position.
* @private
* @param {number} panValue - The pan position to set for the instrument.
*/
Instrument.prototype.setPan = function (panValue) {
if (this.panNode) {
this.panNode.pan.setValueAtTime(panValue, H.audioContext.currentTime);
}
};
/**
* Set gain level. A maximum of 1.2 is allowed before we emit a warning. The
* actual volume is not set above this level regardless of input.
* @private
* @param {number} gainValue - The gain level to set for the instrument.
* @param {number} [rampTime=0] - Gradually change the gain level, time given in
* milliseconds.
*/
Instrument.prototype.setGain = function (gainValue, rampTime) {
if (this.gainNode) {
if (gainValue > 1.2) {
console.warn( // eslint-disable-line
'Highcharts sonification warning: ' +
'Volume of instrument set too high.'
);
gainValue = 1.2;
}
if (rampTime) {
this.gainNode.gain.setValueAtTime(
this.gainNode.gain.value, H.audioContext.currentTime
);
this.gainNode.gain.linearRampToValueAtTime(
gainValue,
H.audioContext.currentTime + rampTime / 1000
);
} else {
this.gainNode.gain.setValueAtTime(
gainValue, H.audioContext.currentTime
);
}
}
};
/**
* Cancel ongoing gain ramps.
* @private
*/
Instrument.prototype.cancelGainRamp = function () {
if (this.gainNode) {
this.gainNode.gain.cancelScheduledValues(0);
}
};
/**
* Get the closest valid frequency for this instrument.
* @private
* @param {number} frequency - The target frequency.
* @param {number} [min] - Minimum frequency to return.
* @param {number} [max] - Maximum frequency to return.
* @return {number} The closest valid frequency to the input frequency.
*/
Instrument.prototype.getValidFrequency = function (frequency, min, max) {
var validFrequencies = this.options.allowedFrequencies,
maximum = H.pick(max, Infinity),
minimum = H.pick(min, -Infinity);
return !validFrequencies || !validFrequencies.length ?
// No valid frequencies for this instrument, return the target
frequency :
// Use the valid frequencies and return the closest match
validFrequencies.reduce(function (acc, cur) {
// Find the closest allowed value
return Math.abs(cur - frequency) < Math.abs(acc - frequency) &&
cur < maximum && cur > minimum ?
cur : acc;
}, Infinity);
};
/**
* Clear existing play callback timers.
* @private
*/
Instrument.prototype.clearPlayCallbackTimers = function () {
this.playCallbackTimers.forEach(function (timer) {
clearInterval(timer);
});
this.playCallbackTimers = [];
};
/**
* Set the current frequency being played by the instrument. The closest valid
* frequency between the frequency limits is used.
* @param {number} frequency - The frequency to set.
* @param {object} [frequencyLimits] - Object with maxFrequency and minFrequency
*/
Instrument.prototype.setFrequency = function (frequency, frequencyLimits) {
var limits = frequencyLimits || {},
validFrequency = this.getValidFrequency(
frequency, limits.min, limits.max
);
if (this.options.type === 'oscillator') {
this.oscillatorPlay(validFrequency);
}
};
/**
* Play oscillator instrument.
* @private
* @param {number} frequency - The frequency to play.
*/
Instrument.prototype.oscillatorPlay = function (frequency) {
if (!this.oscillatorStarted) {
this.oscillator.start();
this.oscillatorStarted = true;
}
this.oscillator.frequency.setValueAtTime(
frequency, H.audioContext.currentTime
);
};
/**
* Prepare instrument before playing. Resumes the audio context and starts the
* oscillator.
* @private
*/
Instrument.prototype.preparePlay = function () {
this.setGain(0.001);
if (H.audioContext.state === 'suspended') {
H.audioContext.resume();
}
if (this.oscillator && !this.oscillatorStarted) {
this.oscillator.start();
this.oscillatorStarted = true;
}
};
/**
* Play the instrument according to options.
*
* @sample highcharts/sonification/instrument/
* Using Instruments directly
* @sample highcharts/sonification/instrument-advanced/
* Using callbacks for instrument parameters
*
* @function Highcharts.Instrument#play
*
* @param {Highcharts.InstrumentPlayOptionsObject} options
* Options for the playback of the instrument.
*/
Instrument.prototype.play = function (options) {
var instrument = this,
duration = options.duration || 0,
// Set a value, or if it is a function, set it continously as a timer.
// Pass in the value/function to set, the setter function, and any
// additional data to pass through to the setter function.
setOrStartTimer = function (value, setter, setterData) {
var target = options.duration,
currentDurationIx = 0,
callbackInterval = instrument.options.playCallbackInterval;
if (typeof value === 'function') {
var timer = setInterval(function () {
currentDurationIx++;
var curTime = currentDurationIx * callbackInterval / target;
if (curTime >= 1) {
instrument[setter](value(1), setterData);
clearInterval(timer);
} else {
instrument[setter](value(curTime), setterData);
}
}, callbackInterval);
instrument.playCallbackTimers.push(timer);
} else {
instrument[setter](value, setterData);
}
};
if (!instrument.id) {
// No audio support - do nothing
return;
}
// If the AudioContext is suspended we have to resume it before playing
if (
H.audioContext.state === 'suspended' ||
this.oscillator && !this.oscillatorStarted
) {
instrument.preparePlay();
// Try again in 10ms
setTimeout(function () {
instrument.play(options);
}, 10);
return;
}
// Clear any existing play timers
if (instrument.playCallbackTimers.length) {
instrument.clearPlayCallbackTimers();
}
// Clear any gain ramps
instrument.cancelGainRamp();
// Clear stop oscillator timer
if (instrument.stopOscillatorTimeout) {
clearTimeout(instrument.stopOscillatorTimeout);
delete instrument.stopOscillatorTimeout;
}
// If a note is playing right now, clear the stop timeout, and call the
// callback.
if (instrument.stopTimeout) {
clearTimeout(instrument.stopTimeout);
delete instrument.stopTimeout;
if (instrument.stopCallback) {
// We have a callback for the play we are interrupting. We do not
// allow this callback to start a new play, because that leads to
// chaos. We pass in 'cancelled' to indicate that this note did not
// finish, but still stopped.
instrument._play = instrument.play;
instrument.play = function () { };
instrument.stopCallback('cancelled');
instrument.play = instrument._play;
}
}
// Stop the note without fadeOut if the duration is too short to hear the
// note otherwise.
var immediate = duration < H.sonification.fadeOutDuration + 20;
// Stop the instrument after the duration of the note
instrument.stopCallback = options.onEnd;
var onStop = function () {
delete instrument.stopTimeout;
instrument.stop(immediate);
};
if (duration) {
instrument.stopTimeout = setTimeout(
onStop,
immediate ? duration :
duration - H.sonification.fadeOutDuration
);
// Play the note
setOrStartTimer(options.frequency, 'setFrequency', null, {
minFrequency: options.minFrequency,
maxFrequency: options.maxFrequency
});
// Set the volume and panning
setOrStartTimer(H.pick(options.volume, 1), 'setGain', 4); // Slight ramp
setOrStartTimer(H.pick(options.pan, 0), 'setPan');
} else {
// No note duration, so just stop immediately
onStop();
}
};
/**
* Mute an instrument that is playing. If the instrument is not currently
* playing, this function does nothing.
*
* @function Highcharts.Instrument#mute
*/
Instrument.prototype.mute = function () {
this.setGain(0.0001, H.sonification.fadeOutDuration * 0.8);
};
/**
* Stop the instrument playing.
*
* @function Highcharts.Instrument#stop
*
* @param {boolean} immediately
* Whether to do the stop immediately or fade out.
*
* @param {Function} onStopped
* Callback function to be called when the stop is completed.
*
* @param {*} callbackData
* Data to send to the onEnd callback functions.
*/
Instrument.prototype.stop = function (immediately, onStopped, callbackData) {
var instr = this,
reset = function () {
// Remove timeout reference
if (instr.stopOscillatorTimeout) {
delete instr.stopOscillatorTimeout;
}
// The oscillator may have stopped in the meantime here, so allow
// this function to fail if so.
try {
instr.oscillator.stop();
} catch (e) {}
instr.oscillator.disconnect(instr.gainNode);
// We need a new oscillator in order to restart it
instr.initOscillator(instr.options.oscillator);
// Done stopping, call the callback from the stop
if (onStopped) {
onStopped(callbackData);
}
// Call the callback for the play we finished
if (instr.stopCallback) {
instr.stopCallback(callbackData);
}
};
// Clear any existing timers
if (instr.playCallbackTimers.length) {
instr.clearPlayCallbackTimers();
}
if (instr.stopTimeout) {
clearTimeout(instr.stopTimeout);
}
if (immediately) {
instr.setGain(0);
reset();
} else {
instr.mute();
// Stop the oscillator after the mute fade-out has finished
instr.stopOscillatorTimeout =
setTimeout(reset, H.sonification.fadeOutDuration + 100);
}
};
return Instrument;
});
_registerModule(_modules, 'modules/sonification/musicalFrequencies.js', [], function () {
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* List of musical frequencies from C0 to C8.
*
* License: www.highcharts.com/license
*
* */
var frequencies = [
16.351597831287414, // C0
17.323914436054505,
18.354047994837977,
19.445436482630058,
20.601722307054366,
21.826764464562746,
23.12465141947715,
24.499714748859326,
25.956543598746574,
27.5, // A0
29.13523509488062,
30.86770632850775,
32.70319566257483, // C1
34.64782887210901,
36.70809598967594,
38.890872965260115,
41.20344461410875,
43.653528929125486,
46.2493028389543,
48.999429497718666,
51.91308719749314,
55, // A1
58.27047018976124,
61.7354126570155,
65.40639132514966, // C2
69.29565774421802,
73.41619197935188,
77.78174593052023,
82.4068892282175,
87.30705785825097,
92.4986056779086,
97.99885899543733,
103.82617439498628,
110, // A2
116.54094037952248,
123.47082531403103,
130.8127826502993, // C3
138.59131548843604,
146.8323839587038,
155.56349186104046,
164.81377845643496,
174.61411571650194,
184.9972113558172,
195.99771799087463,
207.65234878997256,
220, // A3
233.08188075904496,
246.94165062806206,
261.6255653005986, // C4
277.1826309768721,
293.6647679174076,
311.1269837220809,
329.6275569128699,
349.2282314330039,
369.9944227116344,
391.99543598174927,
415.3046975799451,
440, // A4
466.1637615180899,
493.8833012561241,
523.2511306011972, // C5
554.3652619537442,
587.3295358348151,
622.2539674441618,
659.2551138257398,
698.4564628660078,
739.9888454232688,
783.9908719634985,
830.6093951598903,
880, // A5
932.3275230361799,
987.7666025122483,
1046.5022612023945, // C6
1108.7305239074883,
1174.6590716696303,
1244.5079348883237,
1318.5102276514797,
1396.9129257320155,
1479.9776908465376,
1567.981743926997,
1661.2187903197805,
1760, // A6
1864.6550460723597,
1975.533205024496,
2093.004522404789, // C7
2217.4610478149766,
2349.31814333926,
2489.0158697766474,
2637.02045530296,
2793.825851464031,
2959.955381693075,
3135.9634878539946,
3322.437580639561,
3520, // A7
3729.3100921447194,
3951.066410048992,
4186.009044809578 // C8
];
return frequencies;
});
_registerModule(_modules, 'modules/sonification/utilities.js', [_modules['modules/sonification/musicalFrequencies.js']], function (musicalFrequencies) {
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Utility functions for sonification.
*
* License: www.highcharts.com/license
*
* */
/**
* The SignalHandler class. Stores signal callbacks (event handlers), and
* provides an interface to register them, and emit signals. The word "event" is
* not used to avoid confusion with TimelineEvents.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.SignalHandler
*
* @param {Array<string>} supportedSignals
* List of supported signal names.
*/
function SignalHandler(supportedSignals) {
this.init(supportedSignals || []);
}
SignalHandler.prototype.init = function (supportedSignals) {
this.supportedSignals = supportedSignals;
this.signals = {};
};
/**
* Register a set of signal callbacks with this SignalHandler.
* Multiple signal callbacks can be registered for the same signal.
* @private
* @param {object} signals - An object that contains a mapping from the signal
* name to the callbacks. Only supported events are considered.
*/
SignalHandler.prototype.registerSignalCallbacks = function (signals) {
var signalHandler = this;
signalHandler.supportedSignals.forEach(function (supportedSignal) {
if (signals[supportedSignal]) {
(
signalHandler.signals[supportedSignal] =
signalHandler.signals[supportedSignal] || []
).push(
signals[supportedSignal]
);
}
});
};
/**
* Clear signal callbacks, optionally by name.
* @private
* @param {Array<string>} [signalNames] - A list of signal names to clear. If
* not supplied, all signal callbacks are removed.
*/
SignalHandler.prototype.clearSignalCallbacks = function (signalNames) {
var signalHandler = this;
if (signalNames) {
signalNames.forEach(function (signalName) {
if (signalHandler.signals[signalName]) {
delete signalHandler.signals[signalName];
}
});
} else {
signalHandler.signals = {};
}
};
/**
* Emit a signal. Does nothing if the signal does not exist, or has no
* registered callbacks.
* @private
* @param {string} signalNames - Name of signal to emit.
* @param {*} data - Data to pass to the callback.
*/
SignalHandler.prototype.emitSignal = function (signalName, data) {
var retval;
if (this.signals[signalName]) {
this.signals[signalName].forEach(function (handler) {
var result = handler(data);
retval = result !== undefined ? result : retval;
});
}
return retval;
};
var utilities = {
// List of musical frequencies from C0 to C8
musicalFrequencies: musicalFrequencies,
// SignalHandler class
SignalHandler: SignalHandler,
/**
* Get a musical scale by specifying the semitones from 1-12 to include.
* 1: C, 2: C#, 3: D, 4: D#, 5: E, 6: F,
* 7: F#, 8: G, 9: G#, 10: A, 11: Bb, 12: B
* @private
* @param {Array<number>} semitones - Array of semitones from 1-12 to
* include in the scale. Duplicate entries are ignored.
* @return {Array<number>} Array of frequencies from C0 to C8 that are
* included in this scale.
*/
getMusicalScale: function (semitones) {
return musicalFrequencies.filter(function (freq, i) {
var interval = i % 12 + 1;
return semitones.some(function (allowedInterval) {
return allowedInterval === interval;
});
});
},
/**
* Calculate the extreme values in a chart for a data prop.
* @private
* @param {Highcharts.Chart} chart - The chart
* @param {string} prop - The data prop to find extremes for
* @return {object} Object with min and max properties
*/
calculateDataExtremes: function (chart, prop) {
return chart.series.reduce(function (extremes, series) {
// We use cropped points rather than series.data here, to allow
// users to zoom in for better fidelity.
series.points.forEach(function (point) {
var val = point[prop] !== undefined ?
point[prop] : point.options[prop];
extremes.min = Math.min(extremes.min, val);
extremes.max = Math.max(extremes.max, val);
});
return extremes;
}, {
min: Infinity,
max: -Infinity
});
},
/**
* Translate a value on a virtual axis. Creates a new, virtual, axis with a
* min and max, and maps the relative value onto this axis.
* @private
* @param {number} value - The relative data value to translate.
* @param {object} dataExtremes - The possible extremes for this value.
* @param {object} limits - Limits for the virtual axis.
* @return {number} The value mapped to the virtual axis.
*/
virtualAxisTranslate: function (value, dataExtremes, limits) {
var lenValueAxis = dataExtremes.max - dataExtremes.min,
lenVirtualAxis = limits.max - limits.min,
virtualAxisValue = limits.min +
lenVirtualAxis * (value - dataExtremes.min) / lenValueAxis;
return lenValueAxis > 0 ?
Math.max(Math.min(virtualAxisValue, limits.max), limits.min) :
limits.min;
}
};
return utilities;
});
_registerModule(_modules, 'modules/sonification/instrumentDefinitions.js', [_modules['modules/sonification/Instrument.js'], _modules['modules/sonification/utilities.js']], function (Instrument, utilities) {
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Instrument definitions for sonification module.
*
* License: www.highcharts.com/license
*
* */
var instruments = {};
['sine', 'square', 'triangle', 'sawtooth'].forEach(function (waveform) {
// Add basic instruments
instruments[waveform] = new Instrument({
oscillator: { waveformShape: waveform }
});
// Add musical instruments
instruments[waveform + 'Musical'] = new Instrument({
allowedFrequencies: utilities.musicalFrequencies,
oscillator: { waveformShape: waveform }
});
// Add scaled instruments
instruments[waveform + 'Major'] = new Instrument({
allowedFrequencies: utilities.getMusicalScale([1, 3, 5, 6, 8, 10, 12]),
oscillator: { waveformShape: waveform }
});
});
return instruments;
});
_registerModule(_modules, 'modules/sonification/Earcon.js', [_modules['parts/Globals.js']], function (H) {
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Earcons for the sonification module in Highcharts.
*
* License: www.highcharts.com/license
*
* */
/**
* Define an Instrument and the options for playing it.
*
* @requires module:modules/sonification
*
* @interface Highcharts.EarconInstrument
*//**
* An instrument instance or the name of the instrument in the
* Highcharts.sonification.instruments map.
* @name Highcharts.EarconInstrument#instrument
* @type {Highcharts.Instrument|String}
*//**
* The options to pass to Instrument.play.
* @name Highcharts.EarconInstrument#playOptions
* @type {object}
*/
/**
* Options for an Earcon.
*
* @requires module:modules/sonification
*
* @interface Highcharts.EarconOptionsObject
*//**
* The instruments and their options defining this earcon.
* @name Highcharts.EarconOptionsObject#instruments
* @type {Array<Highcharts.EarconInstrument>}
*//**
* The unique ID of the Earcon. Generated if not supplied.
* @name Highcharts.EarconOptionsObject#id
* @type {string|undefined}
*//**
* Global panning of all instruments. Overrides all panning on individual
* instruments. Can be a number between -1 and 1.
* @name Highcharts.EarconOptionsObject#pan
* @type {number|undefined}
*//**
* Master volume for all instruments. Volume settings on individual instruments
* can still be used for relative volume between the instruments. This setting
* does not affect volumes set by functions in individual instruments. Can be a
* number between 0 and 1. Defaults to 1.
* @name Highcharts.EarconOptionsObject#volume
* @type {number|undefined}
*//**
* Callback function to call when earcon has finished playing.
* @name Highcharts.EarconOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* The Earcon class. Earcon objects represent a certain sound consisting of
* one or more instruments playing a predefined sound.
*
* @sample highcharts/sonification/earcon/
* Using earcons directly
*
* @requires module:modules/sonification
*
* @class
* @name Highcharts.Earcon
*
* @param {Highcharts.EarconOptionsObject} options
* Options for the Earcon instance.
*/
function Earcon(options) {
this.init(options || {});
}
Earcon.prototype.init = function (options) {
this.options = options;
if (!this.options.id) {
this.options.id = this.id = H.uniqueKey();
}
this.instrumentsPlaying = {};
};
/**
* Play the earcon, optionally overriding init options.
*
* @sample highcharts/sonification/earcon/
* Using earcons directly
*
* @function Highcharts.Earcon#sonify
*
* @param {Highcharts.EarconOptionsObject} options
* Override existing options.
*/
Earcon.prototype.sonify = function (options) {
var playOptions = H.merge(this.options, options);
// Find master volume/pan settings
var masterVolume = H.pick(playOptions.volume, 1),
masterPan = playOptions.pan,
earcon = this,
playOnEnd = options && options.onEnd,
masterOnEnd = earcon.options.onEnd;
// Go through the instruments and play them
playOptions.instruments.forEach(function (opts) {
var instrument = typeof opts.instrument === 'string' ?
H.sonification.instruments[opts.instrument] : opts.instrument,
instrumentOpts = H.merge(opts.playOptions),
instrOnEnd,
instrumentCopy,
copyId;
if (instrument && instrument.play) {
if (opts.playOptions) {
// Handle master pan/volume
if (typeof opts.playOptions.volume !== 'function') {
instrumentOpts.volume = H.pick(masterVolume, 1) *
H.pick(opts.playOptions.volume, 1);
}
instrumentOpts.pan = H.pick(masterPan, instrumentOpts.pan);
// Handle onEnd
instrOnEnd = instrumentOpts.onEnd;
instrumentOpts.onEnd = function () {
delete earcon.instrumentsPlaying[copyId];
if (instrOnEnd) {
instrOnEnd.apply(this, arguments);
}
if (!Object.keys(earcon.instrumentsPlaying).length) {
if (playOnEnd) {
playOnEnd.apply(this, arguments);
}
if (masterOnEnd) {
masterOnEnd.apply(this, arguments);
}
}
};
// Play the instrument. Use a copy so we can play multiple at
// the same time.
instrumentCopy = instrument.copy();
copyId = instrumentCopy.id;
earcon.instrumentsPlaying[copyId] = instrumentCopy;
instrumentCopy.play(instrumentOpts);
}
} else {
H.error(30);
}
});
};
/**
* Cancel any current sonification of the Earcon. Calls onEnd functions.
*
* @function Highcharts.Earcon#cancelSonify
*
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the earcon is
* cancelled synchronously.
*/
Earcon.prototype.cancelSonify = function (fadeOut) {
var playing = this.instrumentsPlaying,
instrIds = playing && Object.keys(playing);
if (instrIds && instrIds.length) {
instrIds.forEach(function (instr) {
playing[instr].stop(!fadeOut, null, 'cancelled');
});
this.instrumentsPlaying = {};
}
};
return Earcon;
});
_registerModule(_modules, 'modules/sonification/pointSonify.js', [_modules['parts/Globals.js'], _modules['modules/sonification/utilities.js']], function (H, utilities) {
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Code for sonifying single points.
*
* License: www.highcharts.com/license
*
* */
/**
* Define the parameter mapping for an instrument.
*
* @requires module:modules/sonification
*
* @interface Highcharts.PointInstrumentMappingObject
*//**
* Define the volume of the instrument. This can be a string with a data
* property name, e.g. `'y'`, in which case this data property is used to define
* the volume relative to the `y`-values of the other points. A higher `y` value
* would then result in a higher volume. This option can also be a fixed number
* or a function. If it is a function, this function is called in regular
* intervals while the note is playing. It receives three arguments: The point,
* the dataExtremes, and the current relative time - where 0 is the beginning of
* the note and 1 is the end. The function should return the volume of the note
* as a number between 0 and 1.
* @name Highcharts.PointInstrumentMappingObject#volume
* @type {string|number|Function}
*//**
* Define the duration of the notes for this instrument. This can be a string
* with a data property name, e.g. `'y'`, in which case this data property is
* used to define the duration relative to the `y`-values of the other points. A
* higher `y` value would then result in a longer duration. This option can also
* be a fixed number or a function. If it is a function, this function is called
* once before the note starts playing, and should return the duration in
* milliseconds. It receives two arguments: The point, and the dataExtremes.
* @name Highcharts.PointInstrumentMappingObject#duration
* @type {string|number|Function}
*//**
* Define the panning of the instrument. This can be a string with a data
* property name, e.g. `'x'`, in which case this data property is used to define
* the panning relative to the `x`-values of the other points. A higher `x`
* value would then result in a higher panning value (panned further to the
* right). This option can also be a fixed number or a function. If it is a
* function, this function is called in regular intervals while the note is
* playing. It receives three arguments: The point, the dataExtremes, and the
* current relative time - where 0 is the beginning of the note and 1 is the
* end. The function should return the panning of the note as a number between
* -1 and 1.
* @name Highcharts.PointInstrumentMappingObject#pan
* @type {string|number|Function|undefined}
*//**
* Define the frequency of the instrument. This can be a string with a data
* property name, e.g. `'y'`, in which case this data property is used to define
* the frequency relative to the `y`-values of the other points. A higher `y`
* value would then result in a higher frequency. This option can also be a
* fixed number or a function. If it is a function, this function is called in
* regular intervals while the note is playing. It receives three arguments:
* The point, the dataExtremes, and the current relative time - where 0 is the
* beginning of the note and 1 is the end. The function should return the
* frequency of the note as a number (in Hz).
* @name Highcharts.PointInstrumentMappingObject#frequency
* @type {string|number|Function}
*/
/**
* @requires module:modules/sonification
*
* @interface Highcharts.PointInstrumentOptionsObject
*//**
* The minimum duration for a note when using a data property for duration. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.duration. Defaults to 20.
* @name Highcharts.PointInstrumentOptionsObject#minDuration
* @type {number|undefined}
*//**
* The maximum duration for a note when using a data property for duration. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.duration. Defaults to 2000.
* @name Highcharts.PointInstrumentOptionsObject#maxDuration
* @type {number|undefined}
*//**
* The minimum pan value for a note when using a data property for panning. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.pan. Defaults to -1 (fully left).
* @name Highcharts.PointInstrumentOptionsObject#minPan
* @type {number|undefined}
*//**
* The maximum pan value for a note when using a data property for panning. Can
* be overridden by using either a fixed number or a function for
* instrumentMapping.pan. Defaults to 1 (fully right).
* @name Highcharts.PointInstrumentOptionsObject#maxPan
* @type {number|undefined}
*//**
* The minimum volume for a note when using a data property for volume. Can be
* overridden by using either a fixed number or a function for
* instrumentMapping.volume. Defaults to 0.1.
* @name Highcharts.PointInstrumentOptionsObject#minVolume
* @type {number|undefined}
*//**
* The maximum volume for a note when using a data property for volume. Can be
* overridden by using either a fixed number or a function for
* instrumentMapping.volume. Defaults to 1.
* @name Highcharts.PointInstrumentOptionsObject#maxVolume
* @type {number|undefined}
*//**
* The minimum frequency for a note when using a data property for frequency.
* Can be overridden by using either a fixed number or a function for
* instrumentMapping.frequency. Defaults to 220.
* @name Highcharts.PointInstrumentOptionsObject#minFrequency
* @type {number|undefined}
*//**
* The maximum frequency for a note when using a data property for frequency.
* Can be overridden by using either a fixed number or a function for
* instrumentMapping.frequency. Defaults to 2200.
* @name Highcharts.PointInstrumentOptionsObject#maxFrequency
* @type {number|undefined}
*/
/**
* An instrument definition for a point, specifying the instrument to play and
* how to play it.
*
* @interface Highcharts.PointInstrumentObject
*//**
* An Instrument instance or the name of the instrument in the
* Highcharts.sonification.instruments map.
* @name Highcharts.PointInstrumentObject#instrument
* @type {Highcharts.Instrument|string}
*//**
* Mapping of instrument parameters for this instrument.
* @name Highcharts.PointInstrumentObject#instrumentMapping
* @type {Highcharts.PointInstrumentMappingObject}
*//**
* Options for this instrument.
* @name Highcharts.PointInstrumentObject#instrumentOptions
* @type {Highcharts.PointInstrumentOptionsObject|undefined}
*//**
* Callback to call when the instrument has stopped playing.
* @name Highcharts.PointInstrumentObject#onEnd
* @type {Function|undefined}
*/
/**
* Options for sonifying a point.
* @interface Highcharts.PointSonifyOptionsObject
*//**
* The instrument definitions for this point.
* @name Highcharts.PointSonifyOptionsObject#instruments
* @type {Array<Highcharts.PointInstrumentObject>}
*//**
* Optionally provide the minimum/maximum values for the points. If this is not
* supplied, it is calculated from the points in the chart on demand. This
* option is supplied in the following format, as a map of point data properties
* to objects with min/max values:
* ```js
* dataExtremes: {
* y: {
* min: 0,
* max: 100
* },
* z: {
* min: -10,
* max: 10
* }
* // Properties used and not provided are calculated on demand
* }
* ```
* @name Highcharts.PointSonifyOptionsObject#dataExtremes
* @type {object|undefined}
*//**
* Callback called when the sonification has finished.
* @name Highcharts.PointSonifyOptionsObject#onEnd
* @type {Function|undefined}
*/
// Defaults for the instrument options
// NOTE: Also change defaults in Highcharts.PointInstrumentOptionsObject if
// making changes here.
var defaultInstrumentOptions = {
minDuration: 20,
maxDuration: 2000,
minVolume: 0.1,
maxVolume: 1,
minPan: -1,
maxPan: 1,
minFrequency: 220,
maxFrequency: 2200
};
/**
* Sonify a single point.
*
* @sample highcharts/sonification/point-basic/
* Click on points to sonify
* @sample highcharts/sonification/point-advanced/
* Sonify bubbles
*
* @requires module:modules/sonification
*
* @function Highcharts.Point#sonify
*
* @param {Highcharts.PointSonifyOptionsObject} options
* Options for the sonification of the point.
*/
function pointSonify(options) {
var point = this,
chart = point.series.chart,
dataExtremes = options.dataExtremes || {},
// Get the value to pass to instrument.play from the mapping value
// passed in.
getMappingValue = function (
value, makeFunction, allowedExtremes, allowedValues
) {
// Fixed number, just use that
if (typeof value === 'number' || value === undefined) {
return value;
}
// Function. Return new function if we try to use callback,
// otherwise call it now and return result.
if (typeof value === 'function') {
return makeFunction ?
function (time) {
return value(point, dataExtremes, time);
} :
value(point, dataExtremes);
}
// String, this is a data prop.
if (typeof value === 'string') {
// Find data extremes if we don't have them
dataExtremes[value] = dataExtremes[value] ||
utilities.calculateDataExtremes(
point.series.chart, value
);
// Find the value
return utilities.virtualAxisTranslate(
H.pick(point[value], point.options[value]),
dataExtremes[value],
allowedExtremes,
allowedValues
);
}
};
// Register playing point on chart
chart.sonification.currentlyPlayingPoint = point;
// Keep track of instruments playing
point.sonification = point.sonification || {};
point.sonification.instrumentsPlaying =
point.sonification.instrumentsPlaying || {};
// Register signal handler for the point
var signalHandler = point.sonification.signalHandler =
point.sonification.signalHandler ||
new utilities.SignalHandler(['onEnd']);
signalHandler.clearSignalCallbacks();
signalHandler.registerSignalCallbacks({ onEnd: options.onEnd });
// If we have a null point or invisible point, just return
if (point.isNull || !point.visible || !point.series.visible) {
signalHandler.emitSignal('onEnd');
return;
}
// Go through instruments and play them
options.instruments.forEach(function (instrumentDefinition) {
var instrument = typeof instrumentDefinition.instrument === 'string' ?
H.sonification.instruments[instrumentDefinition.instrument] :
instrumentDefinition.instrument,
mapping = instrumentDefinition.instrumentMapping || {},
extremes = H.merge(
defaultInstrumentOptions,
instrumentDefinition.instrumentOptions
),
id = instrument.id,
onEnd = function (cancelled) {
// Instrument on end
if (instrumentDefinition.onEnd) {
instrumentDefinition.onEnd.apply(this, arguments);
}
// Remove currently playing point reference on chart
if (
chart.sonification &&
chart.sonification.currentlyPlayingPoint
) {
delete chart.sonification.currentlyPlayingPoint;
}
// Remove reference from instruments playing
if (
point.sonification && point.sonification.instrumentsPlaying
) {
delete point.sonification.instrumentsPlaying[id];
// This was the last instrument?
if (
!Object.keys(
point.sonification.instrumentsPlaying
).length
) {
signalHandler.emitSignal('onEnd', cancelled);
}
}
};
// Play the note on the instrument
if (instrument && instrument.play) {
point.sonification.instrumentsPlaying[instrument.id] = instrument;
instrument.play({
frequency: getMappingValue(
mapping.frequency,
true,
{ min: extremes.minFrequency, max: extremes.maxFrequency }
),
duration: getMappingValue(
mapping.duration,
false,
{ min: extremes.minDuration, max: extremes.maxDuration }
),
pan: getMappingValue(
mapping.pan,
true,
{ min: extremes.minPan, max: extremes.maxPan }
),
volume: getMappingValue(
mapping.volume,
true,
{ min: extremes.minVolume, max: extremes.maxVolume }
),
onEnd: onEnd,
minFrequency: extremes.minFrequency,
maxFrequency: extremes.maxFrequency
});
} else {
H.error(30);
}
});
}
/**
* Cancel sonification of a point. Calls onEnd functions.
*
* @requires module:modules/sonification
*
* @function Highcharts.Point#cancelSonify
*
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the points are
* cancelled synchronously.
*/
function pointCancelSonify(fadeOut) {
var playing = this.sonification && this.sonification.instrumentsPlaying,
instrIds = playing && Object.keys(playing);
if (instrIds && instrIds.length) {
instrIds.forEach(function (instr) {
playing[instr].stop(!fadeOut, null, 'cancelled');
});
this.sonification.instrumentsPlaying = {};
this.sonification.signalHandler.emitSignal('onEnd', 'cancelled');
}
}
var pointSonifyFunctions = {
pointSonify: pointSonify,
pointCancelSonify: pointCancelSonify
};
return pointSonifyFunctions;
});
_registerModule(_modules, 'modules/sonification/chartSonify.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js'], _modules['modules/sonification/utilities.js']], function (H, U, utilities) {
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Sonification functions for chart/series.
*
* License: www.highcharts.com/license
*
* */
/**
* An Earcon configuration, specifying an Earcon and when to play it.
*
* @requires module:modules/sonification
*
* @interface Highcharts.EarconConfiguration
*//**
* An Earcon instance.
* @name Highcharts.EarconConfiguration#earcon
* @type {Highcharts.Earcon}
*//**
* The ID of the point to play the Earcon on.
* @name Highcharts.EarconConfiguration#onPoint
* @type {string|undefined}
*//**
* A function to determine whether or not to play this earcon on a point. The
* function is called for every point, receiving that point as parameter. It
* should return either a boolean indicating whether or not to play the earcon,
* or a new Earcon instance - in which case the new Earcon will be played.
* @name Highcharts.EarconConfiguration#condition
* @type {Function|undefined}
*/
/**
* Options for sonifying a series.
*
* @requires module:modules/sonification
*
* @interface Highcharts.SonifySeriesOptionsObject
*//**
* The duration for playing the points. Note that points might continue to play
* after the duration has passed, but no new points will start playing.
* @name Highcharts.SonifySeriesOptionsObject#duration
* @type {number}
*//**
* The axis to use for when to play the points. Can be a string with a data
* property (e.g. `x`), or a function. If it is a function, this function
* receives the point as argument, and should return a numeric value. The points
* with the lowest numeric values are then played first, and the time between
* points will be proportional to the distance between the numeric values.
* @name Highcharts.SonifySeriesOptionsObject#pointPlayTime
* @type {string|Function}
*//**
* The instrument definitions for the points in this series.
* @name Highcharts.SonifySeriesOptionsObject#instruments
* @type {Array<Highcharts.PointInstrumentObject>}
*//**
* Earcons to add to the series.
* @name Highcharts.SonifySeriesOptionsObject#earcons
* @type {Array<Highcharts.EarconConfiguration>|undefined}
*//**
* Optionally provide the minimum/maximum data values for the points. If this is
* not supplied, it is calculated from all points in the chart on demand. This
* option is supplied in the following format, as a map of point data properties
* to objects with min/max values:
* ```js
* dataExtremes: {
* y: {
* min: 0,
* max: 100
* },
* z: {
* min: -10,
* max: 10
* }
* // Properties used and not provided are calculated on demand
* }
* ```
* @name Highcharts.SonifySeriesOptionsObject#dataExtremes
* @type {object|undefined}
*//**
* Callback before a point is played.
* @name Highcharts.SonifySeriesOptionsObject#onPointStart
* @type {Function|undefined}
*//**
* Callback after a point has finished playing.
* @name Highcharts.SonifySeriesOptionsObject#onPointEnd
* @type {Function|undefined}
*//**
* Callback after the series has played.
* @name Highcharts.SonifySeriesOptionsObject#onEnd
* @type {Function|undefined}
*/
var isArray = U.isArray,
splat = U.splat;
/**
* Get the relative time value of a point.
* @private
* @param {Highcharts.Point} point - The point.
* @param {Function|string} timeProp - The time axis data prop or the time
* function.
* @return {number} The time value.
*/
function getPointTimeValue(point, timeProp) {
return typeof timeProp === 'function' ?
timeProp(point) :
H.pick(point[timeProp], point.options[timeProp]);
}
/**
* Get the time extremes of this series. This is handled outside of the
* dataExtremes, as we always want to just sonify the visible points, and we
* always want the extremes to be the extremes of the visible points.
* @private
* @param {Highcharts.Series} series - The series to compute on.
* @param {Function|string} timeProp - The time axis data prop or the time
* function.
* @return {object} Object with min/max extremes for the time values.
*/
function getTimeExtremes(series, timeProp) {
// Compute the extremes from the visible points.
return series.points.reduce(function (acc, point) {
var value = getPointTimeValue(point, timeProp);
acc.min = Math.min(acc.min, value);
acc.max = Math.max(acc.max, value);
return acc;
}, {
min: Infinity,
max: -Infinity
});
}
/**
* Calculate value extremes for used instrument data properties.
* @private
* @param {Highcharts.Chart} chart - The chart to calculate extremes from.
* @param {Array<Highcharts.PointInstrumentObject>} instruments - The instrument
* definitions used.
* @param {object} [dataExtremes] - Predefined extremes for each data prop.
* @return {object} New extremes with data properties mapped to min/max objects.
*/
function getExtremesForInstrumentProps(chart, instruments, dataExtremes) {
return (
instruments || []
).reduce(function (newExtremes, instrumentDefinition) {
Object.keys(instrumentDefinition.instrumentMapping || {}).forEach(
function (instrumentParameter) {
var value = instrumentDefinition.instrumentMapping[
instrumentParameter
];
if (typeof value === 'string' && !newExtremes[value]) {
// This instrument parameter is mapped to a data prop.
// If we don't have predefined data extremes, find them.
newExtremes[value] = utilities.calculateDataExtremes(
chart, value
);
}
}
);
return newExtremes;
}, H.merge(dataExtremes));
}
/**
* Get earcons for the point if there are any.
* @private
* @param {Highcharts.Point} point - The point to find earcons for.
* @param {Array<Highcharts.EarconConfiguration>} earconDefinitions - Earcons to
* check.
* @return {Array<Highcharts.Earcon>} Array of earcons to be played with this
* point.
*/
function getPointEarcons(point, earconDefinitions) {
return earconDefinitions.reduce(
function (earcons, earconDefinition) {
var cond,
earcon = earconDefinition.earcon;
if (earconDefinition.condition) {
// We have a condition. This overrides onPoint
cond = earconDefinition.condition(point);
if (cond instanceof H.sonification.Earcon) {
// Condition returned an earcon
earcons.push(cond);
} else if (cond) {
// Condition returned true
earcons.push(earcon);
}
} else if (
earconDefinition.onPoint &&
point.id === earconDefinition.onPoint
) {
// We have earcon onPoint
earcons.push(earcon);
}
return earcons;
}, []
);
}
/**
* Utility function to get a new list of instrument options where all the
* instrument references are copies.
* @private
* @param {Array<Highcharts.PointInstrumentObject>} instruments - The instrument
* options.
* @return {Array<Highcharts.PointInstrumentObject>} Array of copied instrument
* options.
*/
function makeInstrumentCopies(instruments) {
return instruments.map(function (instrumentDef) {
var instrument = instrumentDef.instrument,
copy = (typeof instrument === 'string' ?
H.sonification.instruments[instrument] :
instrument).copy();
return H.merge(instrumentDef, { instrument: copy });
});
}
/**
* Create a TimelinePath from a series. Takes the same options as seriesSonify.
* To intuitively allow multiple series to play simultaneously we make copies of
* the instruments for each series.
* @private
* @param {Highcharts.Series} series - The series to build from.
* @param {object} options - The options for building the TimelinePath.
* @return {Highcharts.TimelinePath} A timeline path with events.
*/
function buildTimelinePathFromSeries(series, options) {
// options.timeExtremes is internal and used so that the calculations from
// chart.sonify can be reused.
var timeExtremes = options.timeExtremes || getTimeExtremes(
series, options.pointPlayTime, options.dataExtremes
),
// Get time offset for a point, relative to duration
pointToTime = function (point) {
return utilities.virtualAxisTranslate(
getPointTimeValue(point, options.pointPlayTime),
timeExtremes,
{ min: 0, max: options.duration }
);
},
// Compute any data extremes that aren't defined yet
dataExtremes = getExtremesForInstrumentProps(
series.chart, options.instruments, options.dataExtremes
),
// Make copies of the instruments used for this series, to allow
// multiple series with the same instrument to play together
instruments = makeInstrumentCopies(options.instruments),
// Go through the points, convert to events, optionally add Earcons
timelineEvents = series.points.reduce(function (events, point) {
var earcons = getPointEarcons(point, options.earcons || []),
time = pointToTime(point);
return events.concat(
// Event object for point
new H.sonification.TimelineEvent({
eventObject: point,
time: time,
id: point.id,
playOptions: {
instruments: instruments,
dataExtremes: dataExtremes
}
}),
// Earcons
earcons.map(function (earcon) {
return new H.sonification.TimelineEvent({
eventObject: earcon,
time: time
});
})
);
}, []);
// Build the timeline path
return new H.sonification.TimelinePath({
events: timelineEvents,
onStart: function () {
if (options.onStart) {
options.onStart(series);
}
},
onEventStart: function (event) {
var eventObject = event.options && event.options.eventObject;
if (eventObject instanceof H.Point) {
// Check for hidden series
if (
!eventObject.series.visible &&
!eventObject.series.chart.series.some(function (series) {
return series.visible;
})
) {
// We have no visible series, stop the path.
event.timelinePath.timeline.pause();
event.timelinePath.timeline.resetCursor();
return false;
}
// Emit onPointStart
if (options.onPointStart) {
options.onPointStart(event, eventObject);
}
}
},
onEventEnd: function (eventData) {
var eventObject = eventData.event && eventData.event.options &&
eventData.event.options.eventObject;
if (eventObject instanceof H.Point && options.onPointEnd) {
options.onPointEnd(eventData.event, eventObject);
}
},
onEnd: function () {
if (options.onEnd) {
options.onEnd(series);
}
}
});
}
/**
* Sonify a series.
*
* @sample highcharts/sonification/series-basic/
* Click on series to sonify
* @sample highcharts/sonification/series-earcon/
* Series with earcon
* @sample highcharts/sonification/point-play-time/
* Play y-axis by time
* @sample highcharts/sonification/earcon-on-point/
* Earcon set on point
*
* @requires module:modules/sonification
*
* @function Highcharts.Series#sonify
*
* @param {Highcharts.SonifySeriesOptionsObject} options
* The options for sonifying this series.
*/
function seriesSonify(options) {
var timelinePath = buildTimelinePathFromSeries(this, options),
chartSonification = this.chart.sonification;
// Only one timeline can play at a time. If we want multiple series playing
// at the same time, use chart.sonify.
if (chartSonification.timeline) {
chartSonification.timeline.pause();
}
// Create new timeline for this series, and play it.
chartSonification.timeline = new H.sonification.Timeline({
paths: [timelinePath]
});
chartSonification.timeline.play();
}
/**
* Utility function to assemble options for creating a TimelinePath from a
* series when sonifying an entire chart.
* @private
* @param {Highcharts.Series} series - The series to return options for.
* @param {object} dataExtremes - Pre-calculated data extremes for the chart.
* @param {object} chartSonifyOptions - Options passed in to chart.sonify.
* @return {object} Options for buildTimelinePathFromSeries.
*/
function buildSeriesOptions(series, dataExtremes, chartSonifyOptions) {
var seriesOptions = chartSonifyOptions.seriesOptions || {};
return H.merge(
{
// Calculated dataExtremes for chart
dataExtremes: dataExtremes,
// We need to get timeExtremes for each series. We pass this
// in when building the TimelinePath objects to avoid
// calculating twice.
timeExtremes: getTimeExtremes(
series, chartSonifyOptions.pointPlayTime
),
// Some options we just pass on
instruments: chartSonifyOptions.instruments,
onStart: chartSonifyOptions.onSeriesStart,
onEnd: chartSonifyOptions.onSeriesEnd,
earcons: chartSonifyOptions.earcons
},
// Merge in the specific series options by ID
isArray(seriesOptions) ? (
H.find(seriesOptions, function (optEntry) {
return optEntry.id === H.pick(series.id, series.options.id);
}) || {}
) : seriesOptions,
{
// Forced options
pointPlayTime: chartSonifyOptions.pointPlayTime
}
);
}
/**
* Utility function to normalize the ordering of timeline paths when sonifying
* a chart.
* @private
* @param {string|Array<string|Highcharts.Earcon|Array<string|Highcharts.Earcon>>} orderOptions -
* Order options for the sonification.
* @param {Highcharts.Chart} chart - The chart we are sonifying.
* @param {Function} seriesOptionsCallback - A function that takes a series as
* argument, and returns the series options for that series to be used with
* buildTimelinePathFromSeries.
* @return {Array<object|Array<object|Highcharts.TimelinePath>>} If order is
* sequential, we return an array of objects to create series paths from. If
* order is simultaneous we return an array of an array with the same. If there
* is a custom order, we return an array of arrays of either objects (for
* series) or TimelinePaths (for earcons and delays).
*/
function buildPathOrder(orderOptions, chart, seriesOptionsCallback) {
var order;
if (orderOptions === 'sequential' || orderOptions === 'simultaneous') {
// Just add the series from the chart
order = chart.series.reduce(function (seriesList, series) {
if (series.visible) {
seriesList.push({
series: series,
seriesOptions: seriesOptionsCallback(series)
});
}
return seriesList;
}, []);
// If order is simultaneous, group all series together
if (orderOptions === 'simultaneous') {
order = [order];
}
} else {
// We have a specific order, and potentially custom items - like
// earcons or silent waits.
order = orderOptions.reduce(function (orderList, orderDef) {
// Return set of items to play simultaneously. Could be only one.
var simulItems = splat(orderDef).reduce(function (items, item) {
var itemObject;
// Is this item a series ID?
if (typeof item === 'string') {
var series = chart.get(item);
if (series.visible) {
itemObject = {
series: series,
seriesOptions: seriesOptionsCallback(series)
};
}
// Is it an earcon? If so, just create the path.
} else if (item instanceof H.sonification.Earcon) {
// Path with a single event
itemObject = new H.sonification.TimelinePath({
events: [new H.sonification.TimelineEvent({
eventObject: item
})]
});
}
// Is this item a silent wait? If so, just create the path.
if (item.silentWait) {
itemObject = new H.sonification.TimelinePath({
silentWait: item.silentWait
});
}
// Add to items to play simultaneously
if (itemObject) {
items.push(itemObject);
}
return items;
}, []);
// Add to order list
if (simulItems.length) {
orderList.push(simulItems);
}
return orderList;
}, []);
}
return order;
}
/**
* Utility function to add a silent wait after all series.
* @private
* @param {Array<object|Array<object|TimelinePath>>} order - The order of items.
* @param {number} wait - The wait in milliseconds to add.
* @return {Array<object|Array<object|TimelinePath>>} The order with waits inserted.
*/
function addAfterSeriesWaits(order, wait) {
if (!wait) {
return order;
}
return order.reduce(function (newOrder, orderDef, i) {
var simultaneousPaths = splat(orderDef);
newOrder.push(simultaneousPaths);
// Go through the simultaneous paths and see if there is a series there
if (
i < order.length - 1 && // Do not add wait after last series
simultaneousPaths.some(function (item) {
return item.series;
})
) {
// We have a series, meaning we should add a wait after these
// paths have finished.
newOrder.push(new H.sonification.TimelinePath({
silentWait: wait
}));
}
return newOrder;
}, []);
}
/**
* Utility function to find the total amout of wait time in the TimelinePaths.
* @private
* @param {Array<object|Array<object|TimelinePath>>} order - The order of
* TimelinePaths/items.
* @return {number} The total time in ms spent on wait paths between playing.
*/
function getWaitTime(order) {
return order.reduce(function (waitTime, orderDef) {
var def = splat(orderDef);
return waitTime + (
def.length === 1 && def[0].options && def[0].options.silentWait || 0
);
}, 0);
}
/**
* Utility function to ensure simultaneous paths have start/end events at the
* same time, to sync them.
* @private
* @param {Array<Highcharts.TimelinePath>} paths - The paths to sync.
*/
function syncSimultaneousPaths(paths) {
// Find the extremes for these paths
var extremes = paths.reduce(function (extremes, path) {
var events = path.events;
if (events && events.length) {
extremes.min = Math.min(events[0].time, extremes.min);
extremes.max = Math.max(
events[events.length - 1].time, extremes.max
);
}
return extremes;
}, {
min: Infinity,
max: -Infinity
});
// Go through the paths and add events to make them fit the same timespan
paths.forEach(function (path) {
var events = path.events,
hasEvents = events && events.length,
eventsToAdd = [];
if (!(hasEvents && events[0].time <= extremes.min)) {
eventsToAdd.push(new H.sonification.TimelineEvent({
time: extremes.min
}));
}
if (!(hasEvents && events[events.length - 1].time >= extremes.max)) {
eventsToAdd.push(new H.sonification.TimelineEvent({
time: extremes.max
}));
}
if (eventsToAdd.length) {
path.addTimelineEvents(eventsToAdd);
}
});
}
/**
* Utility function to find the total duration span for all simul path sets
* that include series.
* @private
* @param {Array<object|Array<object|Highcharts.TimelinePath>>} order - The
* order of TimelinePaths/items.
* @return {number} The total time value span difference for all series.
*/
function getSimulPathDurationTotal(order) {
return order.reduce(function (durationTotal, orderDef) {
return durationTotal + splat(orderDef).reduce(
function (maxPathDuration, item) {
var timeExtremes = item.series && item.seriesOptions &&
item.seriesOptions.timeExtremes;
return timeExtremes ?
Math.max(
maxPathDuration, timeExtremes.max - timeExtremes.min
) : maxPathDuration;
},
0
);
}, 0);
}
/**
* Function to calculate the duration in ms for a series.
* @private
* @param {number} seriesValueDuration - The duration of the series in value
* difference.
* @param {number} totalValueDuration - The total duration of all (non
* simultaneous) series in value difference.
* @param {number} totalDurationMs - The desired total duration for all series
* in milliseconds.
* @return {number} The duration for the series in milliseconds.
*/
function getSeriesDurationMs(
seriesValueDuration, totalValueDuration, totalDurationMs
) {
// A series spanning the whole chart would get the full duration.
return utilities.virtualAxisTranslate(
seriesValueDuration,
{ min: 0, max: totalValueDuration },
{ min: 0, max: totalDurationMs }
);
}
/**
* Convert series building objects into paths and return a new list of
* TimelinePaths.
* @private
* @param {Array<object|Array<object|Highcharts.TimelinePath>>} order - The
* order list.
* @param {number} duration - Total duration to aim for in milliseconds.
* @return {Array<Array<Highcharts.TimelinePath>>} Array of TimelinePath objects
* to play.
*/
function buildPathsFromOrder(order, duration) {
// Find time used for waits (custom or after series), and subtract it from
// available duration.
var totalAvailableDurationMs = Math.max(
duration - getWaitTime(order), 0
),
// Add up simultaneous path durations to find total value span duration
// of everything
totalUsedDuration = getSimulPathDurationTotal(order);
// Go through the order list and convert the items
return order.reduce(function (allPaths, orderDef) {
var simultaneousPaths = splat(orderDef).reduce(
function (simulPaths, item) {
if (item instanceof H.sonification.TimelinePath) {
// This item is already a path object
simulPaths.push(item);
} else if (item.series) {
// We have a series.
// We need to set the duration of the series
item.seriesOptions.duration =
item.seriesOptions.duration || getSeriesDurationMs(
item.seriesOptions.timeExtremes.max -
item.seriesOptions.timeExtremes.min,
totalUsedDuration,
totalAvailableDurationMs
);
// Add the path
simulPaths.push(buildTimelinePathFromSeries(
item.series,
item.seriesOptions
));
}
return simulPaths;
}, []
);
// Add in the simultaneous paths
allPaths.push(simultaneousPaths);
return allPaths;
}, []);
}
/**
* Options for sonifying a chart.
*
* @requires module:modules/sonification
*
* @interface Highcharts.SonifyChartOptionsObject
*//**
* Duration for sonifying the entire chart. The duration is distributed across
* the different series intelligently, but does not take earcons into account.
* It is also possible to set the duration explicitly per series, using
* `seriesOptions`. Note that points may continue to play after the duration has
* passed, but no new points will start playing.
* @name Highcharts.SonifyChartOptionsObject#duration
* @type {number}
*//**
* Define the order to play the series in. This can be given as a string, or an
* array specifying a custom ordering. If given as a string, valid values are
* `sequential` - where each series is played in order - or `simultaneous`,
* where all series are played at once. For custom ordering, supply an array as
* the order. Each element in the array can be either a string with a series ID,
* an Earcon object, or an object with a numeric `silentWait` property
* designating a number of milliseconds to wait before continuing. Each element
* of the array will be played in order. To play elements simultaneously, group
* the elements in an array.
* @name Highcharts.SonifyChartOptionsObject#order
* @type {string|Array<string|Highcharts.Earcon|Array<string|Highcharts.Earcon>>}
*//**
* The axis to use for when to play the points. Can be a string with a data
* property (e.g. `x`), or a function. If it is a function, this function
* receives the point as argument, and should return a numeric value. The points
* with the lowest numeric values are then played first, and the time between
* points will be proportional to the distance between the numeric values. This
* option can not be overridden per series.
* @name Highcharts.SonifyChartOptionsObject#pointPlayTime
* @type {string|Function}
*//**
* Milliseconds of silent waiting to add between series. Note that waiting time
* is considered part of the sonify duration.
* @name Highcharts.SonifyChartOptionsObject#afterSeriesWait
* @type {number|undefined}
*//**
* Options as given to `series.sonify` to override options per series. If the
* option is supplied as an array of options objects, the `id` property of the
* object should correspond to the series' id. If the option is supplied as a
* single object, the options apply to all series.
* @name Highcharts.SonifyChartOptionsObject#seriesOptions
* @type {Object|Array<object>|undefined}
*//**
* The instrument definitions for the points in this chart.
* @name Highcharts.SonifyChartOptionsObject#instruments
* @type {Array<Highcharts.PointInstrumentObject>|undefined}
*//**
* Earcons to add to the chart. Note that earcons can also be added per series
* using `seriesOptions`.
* @name Highcharts.SonifyChartOptionsObject#earcons
* @type {Array<Highcharts.EarconConfiguration>|undefined}
*//**
* Optionally provide the minimum/maximum data values for the points. If this is
* not supplied, it is calculated from all points in the chart on demand. This
* option is supplied in the following format, as a map of point data properties
* to objects with min/max values:
* ```js
* dataExtremes: {
* y: {
* min: 0,
* max: 100
* },
* z: {
* min: -10,
* max: 10
* }
* // Properties used and not provided are calculated on demand
* }
* ```
* @name Highcharts.SonifyChartOptionsObject#dataExtremes
* @type {object|undefined}
*//**
* Callback before a series is played.
* @name Highcharts.SonifyChartOptionsObject#onSeriesStart
* @type {Function|undefined}
*//**
* Callback after a series has finished playing.
* @name Highcharts.SonifyChartOptionsObject#onSeriesEnd
* @type {Function|undefined}
*//**
* Callback after the chart has played.
* @name Highcharts.SonifyChartOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* Sonify a chart.
*
* @sample highcharts/sonification/chart-sequential/
* Sonify a basic chart
* @sample highcharts/sonification/chart-simultaneous/
* Sonify series simultaneously
* @sample highcharts/sonification/chart-custom-order/
* Custom defined order of series
* @sample highcharts/sonification/chart-earcon/
* Earcons on chart
* @sample highcharts/sonification/chart-events/
* Sonification events on chart
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#sonify
*
* @param {Highcharts.SonifyChartOptionsObject} options
* The options for sonifying this chart.
*/
function chartSonify(options) {
// Only one timeline can play at a time.
if (this.sonification.timeline) {
this.sonification.timeline.pause();
}
// Calculate data extremes for the props used
var dataExtremes = getExtremesForInstrumentProps(
this, options.instruments, options.dataExtremes
);
// Figure out ordering of series and custom paths
var order = buildPathOrder(options.order, this, function (series) {
return buildSeriesOptions(series, dataExtremes, options);
});
// Add waits after simultaneous paths with series in them.
order = addAfterSeriesWaits(order, options.afterSeriesWait || 0);
// We now have a list of either TimelinePath objects or series that need to
// be converted to TimelinePath objects. Convert everything to paths.
var paths = buildPathsFromOrder(order, options.duration);
// Sync simultaneous paths
paths.forEach(function (simultaneousPaths) {
syncSimultaneousPaths(simultaneousPaths);
});
// We have a set of paths. Create the timeline, and play it.
this.sonification.timeline = new H.sonification.Timeline({
paths: paths,
onEnd: options.onEnd
});
this.sonification.timeline.play();
}
/**
* Get a list of the points currently under cursor.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#getCurrentSonifyPoints
*
* @return {Array<Highcharts.Point>}
* The points currently under the cursor.
*/
function getCurrentPoints() {
var cursorObj;
if (this.sonification.timeline) {
cursorObj = this.sonification.timeline.getCursor(); // Cursor per pathID
return Object.keys(cursorObj).map(function (path) {
// Get the event objects under cursor for each path
return cursorObj[path].eventObject;
}).filter(function (eventObj) {
// Return the events that are points
return eventObj instanceof H.Point;
});
}
return [];
}
/**
* Set the cursor to a point or set of points in different series.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#setSonifyCursor
*
* @param {Highcharts.Point|Array<Highcharts.Point>} points
* The point or points to set the cursor to. If setting multiple points
* under the cursor, the points have to be in different series that are
* being played simultaneously.
*/
function setCursor(points) {
var timeline = this.sonification.timeline;
if (timeline) {
splat(points).forEach(function (point) {
// We created the events with the ID of the points, which makes
// this easy. Just call setCursor for each ID.
timeline.setCursor(point.id);
});
}
}
/**
* Pause the running sonification.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#pauseSonify
*
* @param {boolean} [fadeOut=true]
* Fade out as we pause to avoid clicks.
*/
function pause(fadeOut) {
if (this.sonification.timeline) {
this.sonification.timeline.pause(H.pick(fadeOut, true));
} else if (this.sonification.currentlyPlayingPoint) {
this.sonification.currentlyPlayingPoint.cancelSonify(fadeOut);
}
}
/**
* Resume the currently running sonification. Requires series.sonify or
* chart.sonify to have been played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#resumeSonify
*
* @param {Function} onEnd
* Callback to call when play finished.
*/
function resume(onEnd) {
if (this.sonification.timeline) {
this.sonification.timeline.play(onEnd);
}
}
/**
* Play backwards from cursor. Requires series.sonify or chart.sonify to have
* been played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#rewindSonify
*
* @param {Function} onEnd
* Callback to call when play finished.
*/
function rewind(onEnd) {
if (this.sonification.timeline) {
this.sonification.timeline.rewind(onEnd);
}
}
/**
* Cancel current sonification and reset cursor.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#cancelSonify
*
* @param {boolean} [fadeOut=true]
* Fade out as we pause to avoid clicks.
*/
function cancel(fadeOut) {
this.pauseSonify(fadeOut);
this.resetSonifyCursor();
}
/**
* Reset cursor to start. Requires series.sonify or chart.sonify to have been
* played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#resetSonifyCursor
*/
function resetCursor() {
if (this.sonification.timeline) {
this.sonification.timeline.resetCursor();
}
}
/**
* Reset cursor to end. Requires series.sonify or chart.sonify to have been
* played at some point earlier.
*
* @requires module:modules/sonification
*
* @function Highcharts.Chart#resetSonifyCursorEnd
*/
function resetCursorEnd() {
if (this.sonification.timeline) {
this.sonification.timeline.resetCursorEnd();
}
}
// Export functions
var chartSonifyFunctions = {
chartSonify: chartSonify,
seriesSonify: seriesSonify,
pause: pause,
resume: resume,
rewind: rewind,
cancel: cancel,
getCurrentPoints: getCurrentPoints,
setCursor: setCursor,
resetCursor: resetCursor,
resetCursorEnd: resetCursorEnd
};
return chartSonifyFunctions;
});
_registerModule(_modules, 'modules/sonification/Timeline.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js'], _modules['modules/sonification/utilities.js']], function (H, U, utilities) {
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* TimelineEvent class definition.
*
* License: www.highcharts.com/license
*
* */
/**
* A set of options for the TimelineEvent class.
*
* @requires module:modules/sonification
*
* @private
* @interface Highcharts.TimelineEventOptionsObject
*//**
* The object we want to sonify when playing the TimelineEvent. Can be any
* object that implements the `sonify` and `cancelSonify` functions. If this is
* not supplied, the TimelineEvent is considered a silent event, and the onEnd
* event is immediately called.
* @name Highcharts.TimelineEventOptionsObject#eventObject
* @type {*}
*//**
* Options to pass on to the eventObject when playing it.
* @name Highcharts.TimelineEventOptionsObject#playOptions
* @type {object|undefined}
*//**
* The time at which we want this event to play (in milliseconds offset). This
* is not used for the TimelineEvent.play function, but rather intended as a
* property to decide when to call TimelineEvent.play. Defaults to 0.
* @name Highcharts.TimelineEventOptionsObject#time
* @type {number|undefined}
*//**
* Unique ID for the event. Generated automatically if not supplied.
* @name Highcharts.TimelineEventOptionsObject#id
* @type {string|undefined}
*//**
* Callback called when the play has finished.
* @name Highcharts.TimelineEventOptionsObject#onEnd
* @type {Function|undefined}
*/
var splat = U.splat;
/**
* The TimelineEvent class. Represents a sound event on a timeline.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.TimelineEvent
*
* @param {Highcharts.TimelineEventOptionsObject} options
* Options for the TimelineEvent.
*/
function TimelineEvent(options) {
this.init(options || {});
}
TimelineEvent.prototype.init = function (options) {
this.options = options;
this.time = options.time || 0;
this.id = this.options.id = options.id || H.uniqueKey();
};
/**
* Play the event. Does not take the TimelineEvent.time option into account,
* and plays the event immediately.
*
* @function Highcharts.TimelineEvent#play
*
* @param {Highcharts.TimelineEventOptionsObject} [options]
* Options to pass in to the eventObject when playing it.
*/
TimelineEvent.prototype.play = function (options) {
var eventObject = this.options.eventObject,
masterOnEnd = this.options.onEnd,
playOnEnd = options && options.onEnd,
playOptionsOnEnd = this.options.playOptions &&
this.options.playOptions.onEnd,
playOptions = H.merge(this.options.playOptions, options);
if (eventObject && eventObject.sonify) {
// If we have multiple onEnds defined, use all
playOptions.onEnd = masterOnEnd || playOnEnd || playOptionsOnEnd ?
function () {
var args = arguments;
[masterOnEnd, playOnEnd, playOptionsOnEnd].forEach(
function (onEnd) {
if (onEnd) {
onEnd.apply(this, args);
}
}
);
} : undefined;
eventObject.sonify(playOptions);
} else {
if (playOnEnd) {
playOnEnd();
}
if (masterOnEnd) {
masterOnEnd();
}
}
};
/**
* Cancel the sonification of this event. Does nothing if the event is not
* currently sonifying.
*
* @function Highcharts.TimelineEvent#cancel
*
* @param {boolean} [fadeOut=false]
* Whether or not to fade out as we stop. If false, the event is
* cancelled synchronously.
*/
TimelineEvent.prototype.cancel = function (fadeOut) {
this.options.eventObject.cancelSonify(fadeOut);
};
/**
* A set of options for the TimelinePath class.
*
* @requires module:modules/
*
* @private
* @interface Highcharts.TimelinePathOptionsObject
*//**
* List of TimelineEvents to play on this track.
* @name Highcharts.TimelinePathOptionsObject#events
* @type {Array<Highcharts.TimelineEvent>}
*//**
* If this option is supplied, this path ignores all events and just waits for
* the specified number of milliseconds before calling onEnd.
* @name Highcharts.TimelinePathOptionsObject#silentWait
* @type {number|undefined}
*//**
* Unique ID for this timeline path. Automatically generated if not supplied.
* @name Highcharts.TimelinePathOptionsObject#id
* @type {string|undefined}
*//**
* Callback called before the path starts playing.
* @name Highcharts.TimelinePathOptionsObject#onStart
* @type {Function|undefined}
*//**
* Callback function to call before an event plays.
* @name Highcharts.TimelinePathOptionsObject#onEventStart
* @type {Function|undefined}
*//**
* Callback function to call after an event has stopped playing.
* @name Highcharts.TimelinePathOptionsObject#onEventEnd
* @type {Function|undefined}
*//**
* Callback called when the whole path is finished.
* @name Highcharts.TimelinePathOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* The TimelinePath class. Represents a track on a timeline with a list of
* sound events to play at certain times relative to each other.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.TimelinePath
*
* @param {Highcharts.TimelinePathOptionsObject} options
* Options for the TimelinePath.
*/
function TimelinePath(options) {
this.init(options);
}
TimelinePath.prototype.init = function (options) {
this.options = options;
this.id = this.options.id = options.id || H.uniqueKey();
this.cursor = 0;
this.eventsPlaying = {};
// Handle silent wait, otherwise use events from options
this.events = options.silentWait ?
[
new TimelineEvent({ time: 0 }),
new TimelineEvent({ time: options.silentWait })
] :
this.options.events;
// We need to sort our events by time
this.sortEvents();
// Get map from event ID to index
this.updateEventIdMap();
// Signal events to fire
this.signalHandler = new utilities.SignalHandler(
['playOnEnd', 'masterOnEnd', 'onStart', 'onEventStart', 'onEventEnd']
);
this.signalHandler.registerSignalCallbacks(
H.merge(options, { masterOnEnd: options.onEnd })
);
};
/**
* Sort the internal event list by time.
* @private
*/
TimelinePath.prototype.sortEvents = function () {
this.events = this.events.sort(function (a, b) {
return a.time - b.time;
});
};
/**
* Update the internal eventId to index map.
* @private
*/
TimelinePath.prototype.updateEventIdMap = function () {
this.eventIdMap = this.events.reduce(function (acc, cur, i) {
acc[cur.id] = i;
return acc;
}, {});
};
/**
* Add events to the path. Should not be done while the path is playing.
* The new events are inserted according to their time property.
* @private
* @param {Array<Highcharts.TimelineEvent>} newEvents - The new timeline events
* to add.
*/
TimelinePath.prototype.addTimelineEvents = function (newEvents) {
this.events = this.events.concat(newEvents);
this.sortEvents(); // Sort events by time
this.updateEventIdMap(); // Update the event ID to index map
};
/**
* Get the current TimelineEvent under the cursor.
* @private
* @return {Highcharts.TimelineEvent} The current timeline event.
*/
TimelinePath.prototype.getCursor = function () {
return this.events[this.cursor];
};
/**
* Set the current TimelineEvent under the cursor.
* @private
* @param {string} eventId - The ID of the timeline event to set as current.
* @return {boolean} True if there is an event with this ID in the path. False
* otherwise.
*/
TimelinePath.prototype.setCursor = function (eventId) {
var ix = this.eventIdMap[eventId];
if (ix !== undefined) {
this.cursor = ix;
return true;
}
return false;
};
/**
* Play the timeline from the current cursor.
* @private
* @param {Function} onEnd - Callback to call when play finished. Does not
* override other onEnd callbacks.
*/
TimelinePath.prototype.play = function (onEnd) {
this.pause();
this.signalHandler.emitSignal('onStart');
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playEvents(1);
};
/**
* Play the timeline backwards from the current cursor.
* @private
* @param {Function} onEnd - Callback to call when play finished. Does not
* override other onEnd callbacks.
*/
TimelinePath.prototype.rewind = function (onEnd) {
this.pause();
this.signalHandler.emitSignal('onStart');
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playEvents(-1);
};
/**
* Reset the cursor to the beginning.
* @private
*/
TimelinePath.prototype.resetCursor = function () {
this.cursor = 0;
};
/**
* Reset the cursor to the end.
* @private
*/
TimelinePath.prototype.resetCursorEnd = function () {
this.cursor = this.events.length - 1;
};
/**
* Cancel current playing. Leaves the cursor intact.
* @private
* @param {boolean} [fadeOut=false] - Whether or not to fade out as we stop. If
* false, the path is cancelled synchronously.
*/
TimelinePath.prototype.pause = function (fadeOut) {
var timelinePath = this;
// Cancel next scheduled play
clearTimeout(timelinePath.nextScheduledPlay);
// Cancel currently playing events
Object.keys(timelinePath.eventsPlaying).forEach(function (id) {
if (timelinePath.eventsPlaying[id]) {
timelinePath.eventsPlaying[id].cancel(fadeOut);
}
});
timelinePath.eventsPlaying = {};
};
/**
* Play the events, starting from current cursor, and going in specified
* direction.
* @private
* @param {number} direction - The direction to play, 1 for forwards and -1 for
* backwards.
*/
TimelinePath.prototype.playEvents = function (direction) {
var timelinePath = this,
curEvent = timelinePath.events[this.cursor],
nextEvent = timelinePath.events[this.cursor + direction],
timeDiff,
onEnd = function (signalData) {
timelinePath.signalHandler.emitSignal(
'masterOnEnd', signalData
);
timelinePath.signalHandler.emitSignal(
'playOnEnd', signalData
);
};
// Store reference to path on event
curEvent.timelinePath = timelinePath;
// Emit event, cancel if returns false
if (
timelinePath.signalHandler.emitSignal(
'onEventStart', curEvent
) === false
) {
onEnd({
event: curEvent,
cancelled: true
});
return;
}
// Play the current event
timelinePath.eventsPlaying[curEvent.id] = curEvent;
curEvent.play({
onEnd: function (cancelled) {
var signalData = {
event: curEvent,
cancelled: !!cancelled
};
// Keep track of currently playing events for cancelling
delete timelinePath.eventsPlaying[curEvent.id];
// Handle onEventEnd
timelinePath.signalHandler.emitSignal('onEventEnd', signalData);
// Reached end of path?
if (!nextEvent) {
onEnd(signalData);
}
}
});
// Schedule next
if (nextEvent) {
timeDiff = Math.abs(nextEvent.time - curEvent.time);
if (timeDiff < 1) {
// Play immediately
timelinePath.cursor += direction;
timelinePath.playEvents(direction);
} else {
// Schedule after the difference in ms
this.nextScheduledPlay = setTimeout(function () {
timelinePath.cursor += direction;
timelinePath.playEvents(direction);
}, timeDiff);
}
}
};
/* ************************************************************************** *
* TIMELINE *
* ************************************************************************** */
/**
* A set of options for the Timeline class.
*
* @requires module:modules/sonification
*
* @private
* @interface Highcharts.TimelineOptionsObject
*//**
* List of TimelinePaths to play. Multiple paths can be grouped together and
* played simultaneously by supplying an array of paths in place of a single
* path.
* @name Highcharts.TimelineOptionsObject#paths
* @type {Array<Highcharts.TimelinePath|Array<Highcharts.TimelinePath>>}
*//**
* Callback function to call before a path plays.
* @name Highcharts.TimelineOptionsObject#onPathStart
* @type {Function|undefined}
*//**
* Callback function to call after a path has stopped playing.
* @name Highcharts.TimelineOptionsObject#onPathEnd
* @type {Function|undefined}
*//**
* Callback called when the whole path is finished.
* @name Highcharts.TimelineOptionsObject#onEnd
* @type {Function|undefined}
*/
/**
* The Timeline class. Represents a sonification timeline with a list of
* timeline paths with events to play at certain times relative to each other.
*
* @requires module:modules/sonification
*
* @private
* @class
* @name Highcharts.Timeline
*
* @param {Highcharts.TimelineOptionsObject} options
* Options for the Timeline.
*/
function Timeline(options) {
this.init(options || {});
}
Timeline.prototype.init = function (options) {
this.options = options;
this.cursor = 0;
this.paths = options.paths;
this.pathsPlaying = {};
this.signalHandler = new utilities.SignalHandler(
['playOnEnd', 'masterOnEnd', 'onPathStart', 'onPathEnd']
);
this.signalHandler.registerSignalCallbacks(
H.merge(options, { masterOnEnd: options.onEnd })
);
};
/**
* Play the timeline forwards from cursor.
* @private
* @param {Function} onEnd - Callback to call when play finished. Does not
* override other onEnd callbacks.
*/
Timeline.prototype.play = function (onEnd) {
this.pause();
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playPaths(1);
};
/**
* Play the timeline backwards from cursor.
* @private
* @param {Function} onEnd - Callback to call when play finished. Does not
* override other onEnd callbacks.
*/
Timeline.prototype.rewind = function (onEnd) {
this.pause();
this.signalHandler.clearSignalCallbacks(['playOnEnd']);
this.signalHandler.registerSignalCallbacks({ playOnEnd: onEnd });
this.playPaths(-1);
};
/**
* Play the timeline in the specified direction.
* @private
* @param {number} direction - Direction to play in. 1 for forwards, -1 for
* backwards.
*/
Timeline.prototype.playPaths = function (direction) {
var curPaths = splat(this.paths[this.cursor]),
nextPaths = this.paths[this.cursor + direction],
timeline = this,
signalHandler = this.signalHandler,
pathsEnded = 0,
// Play a path
playPath = function (path) {
// Emit signal and set playing state
signalHandler.emitSignal('onPathStart', path);
timeline.pathsPlaying[path.id] = path;
// Do the play
path[direction > 0 ? 'play' : 'rewind'](function (callbackData) {
// Play ended callback
// Data to pass to signal callbacks
var cancelled = callbackData && callbackData.cancelled,
signalData = {
path: path,
cancelled: cancelled
};
// Clear state and send signal
delete timeline.pathsPlaying[path.id];
signalHandler.emitSignal('onPathEnd', signalData);
// Handle next paths
pathsEnded++;
if (pathsEnded >= curPaths.length) {
// We finished all of the current paths for cursor.
if (nextPaths && !cancelled) {
// We have more paths, move cursor along
timeline.cursor += direction;
// Reset upcoming path cursors before playing
splat(nextPaths).forEach(function (nextPath) {
nextPath[
direction > 0 ? 'resetCursor' : 'resetCursorEnd'
]();
});
// Play next
timeline.playPaths(direction);
} else {
// If it is the last path in this direction, call onEnd
signalHandler.emitSignal('playOnEnd', signalData);
signalHandler.emitSignal('masterOnEnd', signalData);
}
}
});
};
// Go through the paths under cursor and play them
curPaths.forEach(function (path) {
if (path) {
// Store reference to timeline
path.timeline = timeline;
// Leave a timeout to let notes fade out before next play
setTimeout(function () {
playPath(path);
}, H.sonification.fadeOutTime);
}
});
};
/**
* Stop the playing of the timeline. Cancels all current sounds, but does not
* affect the cursor.
* @private
* @param {boolean} [fadeOut=false] - Whether or not to fade out as we stop. If
* false, the timeline is cancelled synchronously.
*/
Timeline.prototype.pause = function (fadeOut) {
var timeline = this;
// Cancel currently playing events
Object.keys(timeline.pathsPlaying).forEach(function (id) {
if (timeline.pathsPlaying[id]) {
timeline.pathsPlaying[id].pause(fadeOut);
}
});
timeline.pathsPlaying = {};
};
/**
* Reset the cursor to the beginning of the timeline.
* @private
*/
Timeline.prototype.resetCursor = function () {
this.paths.forEach(function (paths) {
splat(paths).forEach(function (path) {
path.resetCursor();
});
});
this.cursor = 0;
};
/**
* Reset the cursor to the end of the timeline.
* @private
*/
Timeline.prototype.resetCursorEnd = function () {
this.paths.forEach(function (paths) {
splat(paths).forEach(function (path) {
path.resetCursorEnd();
});
});
this.cursor = this.paths.length - 1;
};
/**
* Set the current TimelineEvent under the cursor. If multiple paths are being
* played at the same time, this function only affects a single path (the one
* that contains the eventId that is passed in).
* @private
* @param {string} eventId - The ID of the timeline event to set as current.
* @return {boolean} True if the cursor was set, false if no TimelineEvent was
* found for this ID.
*/
Timeline.prototype.setCursor = function (eventId) {
return this.paths.some(function (paths) {
return splat(paths).some(function (path) {
return path.setCursor(eventId);
});
});
};
/**
* Get the current TimelineEvents under the cursors. This function will return
* the event under the cursor for each currently playing path, as an object
* where the path ID is mapped to the TimelineEvent under that path's cursor.
* @private
* @return {object} The TimelineEvents under each path's cursors.
*/
Timeline.prototype.getCursor = function () {
return this.getCurrentPlayingPaths().reduce(function (acc, cur) {
acc[cur.id] = cur.getCursor();
return acc;
}, {});
};
/**
* Check if timeline is reset or at start.
* @private
* @return {boolean} True if timeline is at the beginning.
*/
Timeline.prototype.atStart = function () {
return !this.getCurrentPlayingPaths().some(function (path) {
return path.cursor;
});
};
/**
* Get the current TimelinePaths being played.
* @private
* @return {Array<Highcharts.TimelinePath>} The TimelinePaths currently being
* played.
*/
Timeline.prototype.getCurrentPlayingPaths = function () {
return splat(this.paths[this.cursor]);
};
// Export the classes
var timelineClasses = {
TimelineEvent: TimelineEvent,
TimelinePath: TimelinePath,
Timeline: Timeline
};
return timelineClasses;
});
_registerModule(_modules, 'modules/sonification/sonification.js', [_modules['parts/Globals.js'], _modules['modules/sonification/Instrument.js'], _modules['modules/sonification/instrumentDefinitions.js'], _modules['modules/sonification/Earcon.js'], _modules['modules/sonification/pointSonify.js'], _modules['modules/sonification/chartSonify.js'], _modules['modules/sonification/utilities.js'], _modules['modules/sonification/Timeline.js']], function (H, Instrument, instruments, Earcon, pointSonifyFunctions, chartSonifyFunctions, utilities, TimelineClasses) {
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Sonification module for Highcharts
*
* License: www.highcharts.com/license
*
* */
// Expose on the Highcharts object
/**
* Global classes and objects related to sonification.
*
* @requires module:modules/sonification
*
* @name Highcharts.sonification
* @type {Highcharts.SonificationObject}
*/
/**
* Global classes and objects related to sonification.
*
* @requires module:modules/sonification
*
* @interface Highcharts.SonificationObject
*//**
* Note fade-out-time in milliseconds. Most notes are faded out quickly by
* default if there is time. This is to avoid abrupt stops which will cause
* perceived clicks.
* @name Highcharts.SonificationObject#fadeOutDuration
* @type {number}
*//**
* Utility functions.
* @name Highcharts.SonificationObject#utilities
* @private
* @type {object}
*//**
* The Instrument class.
* @name Highcharts.SonificationObject#Instrument
* @type {Function}
*//**
* Predefined instruments, given as an object with a map between the instrument
* name and the Highcharts.Instrument object.
* @name Highcharts.SonificationObject#instruments
* @type {Object}
*//**
* The Earcon class.
* @name Highcharts.SonificationObject#Earcon
* @type {Function}
*//**
* The TimelineEvent class.
* @private
* @name Highcharts.SonificationObject#TimelineEvent
* @type {Function}
*//**
* The TimelinePath class.
* @private
* @name Highcharts.SonificationObject#TimelinePath
* @type {Function}
*//**
* The Timeline class.
* @private
* @name Highcharts.SonificationObject#Timeline
* @type {Function}
*/
H.sonification = {
fadeOutDuration: 20,
// Classes and functions
utilities: utilities,
Instrument: Instrument,
instruments: instruments,
Earcon: Earcon,
TimelineEvent: TimelineClasses.TimelineEvent,
TimelinePath: TimelineClasses.TimelinePath,
Timeline: TimelineClasses.Timeline
};
// Chart specific
H.Point.prototype.sonify = pointSonifyFunctions.pointSonify;
H.Point.prototype.cancelSonify = pointSonifyFunctions.pointCancelSonify;
H.Series.prototype.sonify = chartSonifyFunctions.seriesSonify;
H.extend(H.Chart.prototype, {
sonify: chartSonifyFunctions.chartSonify,
pauseSonify: chartSonifyFunctions.pause,
resumeSonify: chartSonifyFunctions.resume,
rewindSonify: chartSonifyFunctions.rewind,
cancelSonify: chartSonifyFunctions.cancel,
getCurrentSonifyPoints: chartSonifyFunctions.getCurrentPoints,
setSonifyCursor: chartSonifyFunctions.setCursor,
resetSonifyCursor: chartSonifyFunctions.resetCursor,
resetSonifyCursorEnd: chartSonifyFunctions.resetCursorEnd,
sonification: {}
});
});
_registerModule(_modules, 'masters/modules/sonification.src.js', [], function () {
});
})); | cdnjs/cdnjs | ajax/libs/highcharts/7.1.3/modules/sonification.src.js | JavaScript | mit | 131,540 |
'use strict';
var loMod = angular.module('loApp.services', []).value('version', '0.1');
/*
FileReader service, taken from:
http://odetocode.com/blogs/scott/archive/2013/07/03/building-a-filereader-service-for-angularjs-the-service.aspx
*/
loMod.factory('FileReader', function($q) {
var onLoad = function(reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.resolve(reader.result);
});
};
};
var onError = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.reject(reader.result);
});
};
};
var onProgress = function(reader, scope) {
return function (event) {
scope.$broadcast('fileProgress',
{
total: event.total,
loaded: event.loaded
});
};
};
var getReader = function(deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
reader.onprogress = onProgress(reader, scope);
return reader;
};
var readAsDataURL = function (file, scope) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
reader.readAsText(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
});
loMod.factory('LoStorage', function($resource) {
return $resource('/admin/applications/:appId/resources/:storageId', {
appId : '@appId',
storageId : '@storageId'
}, {
get : {
method : 'GET'
},
getList : {
method : 'GET',
params: { fields : '*(*)' }
},
create : {
method : 'POST',
params : { appId : '@appId'}
},
update : {
method : 'PUT',
params : { appId : '@appId', storageId : '@storageId'}
},
delete : {
method : 'DELETE',
params : { appId : '@appId', storageId : '@storageId'}
},
getDatastores : {
method : 'GET',
url: '/admin/system/mongo',
params: { fields : '*(*)' }
}
});
});
loMod.factory('LoCollection', function($resource) {
return $resource('/:appId/:storageId/:collectionId', {
appId : '@appId',
storageId : '@storageId',
collectionId : '@collectionId'
}, {
check : {
method : 'GET',
params: { appId : '@appId', storageId : '@storageId', collectionId: '@collectionId' }
},
get : {
method : 'GET',
params: { appId : '@appId', storageId : '@storageId', collectionId: '@collectionId', fields : '*(*)' }
},
getList : {
method : 'GET',
params: { fields : '*(*)' }
},
create : {
method : 'POST',
params : { appId : '@appId', storageId : '@storageId'}
},
update : {
method : 'PUT',
params : { appId : '@appId', storageId : '@storageId', collectionId: '@collectionId'}
},
delete : {
method : 'DELETE',
params : { appId : '@appId', storageId : '@storageId', collectionId: '@collectionId'}
}
});
});
loMod.factory('LoCollectionItem', function($resource) {
return $resource('/:appId/:storageId/:collectionId/:itemId', {
appId : '@appId',
storageId : '@storageId',
collectionId : '@collectionId'
}, {
get : {
method : 'GET',
params: { appId : '@appId', storageId : '@storageId', collectionId: '@collectionId', itemId: '@itemId' }
},
getList : {
method : 'GET',
params: { appId : '@appId', storageId : '@storageId', collectionId: '@collectionId', fields : '*(*)' }
},
create : {
method : 'POST',
params : { appId : '@appId', storageId : '@storageId', collectionId: '@collectionId'}
},
update : {
method : 'PUT',
params : { appId : '@appId', storageId : '@storageId', collectionId: '@collectionId', itemId: '@itemId'}
},
delete : {
method : 'DELETE',
params : { appId : '@appId', storageId : '@storageId', collectionId: '@collectionId', itemId: '@itemid'}
}
});
});
loMod.factory('LoApp', function($resource) {
return $resource('/admin/applications/:appId', {
appId : '@appId'
}, {
get : {
method : 'GET'
},
getList : {
method : 'GET',
params: { fields : '*(*)' }
},
create : {
method : 'POST',
url: '/admin/applications/'
},
save : {
method : 'PUT',
url: '/admin/applications/:appId'
},
addResource : {
method : 'PUT',
url: '/admin/applications/:appId/resources/:resourceId'
}
});
});
loMod.factory('LoStorageLoader', function(LoStorage, $route) {
return function() {
return LoStorage.get({
appId : $route.current.params.appId,
storageId: $route.current.params.storageId
}).$promise;
};
});
loMod.factory('LoStorageListLoader', function(LoStorage, $route) {
return function() {
return LoStorage.getList({
appId : $route.current.params.appId
}).$promise;
};
});
loMod.factory('LoCollectionListLoader', function(LoCollection, $route) {
return function() {
return LoCollection.get({
appId: $route.current.params.appId,
storageId: $route.current.params.storageId
}).$promise;
};
});
loMod.factory('LoPushLoader', function(LoPush, $route, $log) {
return function() {
return LoPush.get({
appId : $route.current.params.appId
},
function(httpResponse) {
$log.error(httpResponse);
return {
appId : $route.current.params.appId
};
}).$promise;
};
});
loMod.factory('LoAppLoader', function(LoApp, $route) {
return function() {
return LoApp.get({
appId : $route.current.params.appId
}).$promise;
};
});
loMod.factory('LoAppListLoader', function(LoApp) {
return function() {
return LoApp.getList().$promise;
};
});
loMod.factory('LoCollectionLoader', function(LoCollection) {
return function() {
return LoCollection.get().$promise;
};
});
loMod.factory('LoPush', function($resource) {
return $resource('/admin/applications/:appId/resources/push', {
appId : '@appId'
}, {
get : {
method : 'GET',
params : { appId : '@appId'}
},
update : {
method : 'PUT',
params : { appId : '@appId'}
},
create: {
method : 'POST',
url: '/admin/applications/:appId/resources/',
params : { appId : '@appId'}
},
delete : {
method : 'DELETE',
params : { appId : '@appId'}
},
ping : {
method : 'GET',
url : '/admin/applications/:appId/resources/push/ping'
}
});
});
loMod.factory('LoRealmApp', function($resource, LiveOak) {
return $resource(LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/applications/:appId', {
realmId : 'liveoak-apps',
appId: '@appId'
}, {
save: {
method: 'PUT'
},
create: {
method: 'POST'
},
delete: {
method: 'DELETE'
}
});
});
loMod.factory('LoRealmAppRoles', function($resource, LiveOak) {
return $resource(LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/applications/:appId/roles/:roleName', {
realmId : 'liveoak-apps',
appId: '@appId',
roleName: '@roleName'
});
});
loMod.factory('LoRealmRoles', function($resource, LiveOak) {
return $resource(LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/roles', {
realmId : 'liveoak-apps'
});
});
loMod.factory('LoRealmClientRoles', function($resource, LiveOak) {
return $resource(LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/applications/:appId/scope-mappings/realm', {
realmId: 'liveoak-apps',
appId: '@appId'
});
});
loMod.factory('LoRealmAppClientScopeMapping', function($resource, LiveOak) {
return $resource(LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/applications/:clientId/scope-mappings/applications/:appId', {
realmId: 'liveoak-apps',
appId : '@appId',
clientId : '@clientId'
});
});
loMod.factory('LoRealmAppClientScopeMappingLoader', function(LoRealmAppClientScopeMapping, $route) {
return function(){
return LoRealmAppClientScopeMapping.query({
realmId: 'liveoak-apps',
appId: $route.current.params.appId,
clientId: $route.current.params.clientId
}).$promise;
};
});
loMod.factory('LoRealmAppLoader', function(LoRealmApp, $route) {
return function(){
return LoRealmApp.get({
realmId: 'liveoak-apps',
appId : $route.current.params.appId
}).$promise;
};
});
loMod.factory('LoRealmRolesLoader', function(LoRealmRoles) {
return function(){
return LoRealmRoles.query({
realmId: 'liveoak-apps'
}).$promise;
};
});
loMod.factory('LoRealmAppListLoader', function(LoRealmApp) {
return function(){
return LoRealmApp.query({
realmId: 'liveoak-apps'
}).$promise;
};
});
loMod.factory('LoRealmAppRolesLoader', function(LoRealmAppRoles, $route) {
return function(){
return LoRealmAppRoles.query({
realmId: 'liveoak-apps',
appId : $route.current.params.appId
}).$promise;
};
});
loMod.factory('LoRealmClientRolesLoader', function(LoRealmClientRoles, $route) {
return function(){
return LoRealmClientRoles.query({
realmId: 'liveoak-apps',
appId : $route.current.params.appId
}).$promise;
};
});
loMod.factory('LoSecurityCollections', function($resource) {
return $resource('/:appId', {
appId : '@appId'
}, {
get : {
method: 'GET',
params: { fields : '*(*)' }
}
});
});
loMod.factory('LoSecurityCollectionsLoader', function(LoSecurityCollections, $route) {
return function(){
return LoSecurityCollections.get({
appId : $route.current.params.appId
}).$promise;
};
});
loMod.factory('LoSecurity', function($resource) {
return $resource('/admin/applications/:appId/resources/uri-policy', {
appId : '@appId'
}, {
create : {
method: 'PUT'
},
save : {
method: 'PUT'
}
});
});
loMod.factory('LoSecurityLoader', function(LoSecurity, $route) {
return function(){
return LoSecurity.get( {
appId : $route.current.params.appId
}).$promise;
};
});
loMod.factory('LoACL', function($resource) {
return $resource('/admin/applications/:appId/resources/acl-policy', {
appId : '@appId'
}, {
create : {
method: 'PUT'
},
save : {
method: 'PUT'
}
});
});
loMod.factory('LoACLLoader', function(LoACL, $route) {
return function(){
return LoACL.get({
appId : $route.current.params.appId
}).$promise;
};
});
loMod.factory('LoRealmUsers', function($resource, LiveOak) {
return $resource(LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/users/:userId', {
realmId : 'liveoak-apps',
userId : '@userId'
}, {
resetPassword : {
method: 'PUT',
url: LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/users/:userId/reset-password'
},
addRoles : {
method: 'POST',
url: LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/users/:userId/role-mappings/applications/:appId'
},
deleteRoles : {
method: 'DELETE',
url: LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/users/:userId/role-mappings/applications/:appId'
},
getRoles: {
method: 'GET',
url: LiveOak.getAuthServerUrl() + '/admin/realms/:realmId/users/:userId/role-mappings/applications/:appId/composite',
isArray: true
},
update: {
method: 'PUT'
}
});
});
loMod.factory('LoRealmUserLoader', function(LoRealmUsers, $route) {
return function(){
return LoRealmUsers.get({
userId : $route.current.params.userId
}).$promise;
};
});
loMod.factory('LoAppExamples', function($resource) {
return $resource('/admin/console/resources/example-applications.json',
{},
{
get: {
method: 'GET',
url: '/admin/console/resources/liveoak-examples/:parentId/:exampleId/application.json'
},
install: {
method : 'POST',
url: '/admin/applications/',
headers: {
'Content-Type':'application/vnd.liveoak.local-app+json'
}
},
importGit: {
method : 'POST',
url: '/admin/applications/',
headers: {
'Content-Type':'application/vnd.liveoak.git-app+json'
}
}
});
});
loMod.factory('LoClient', function($resource) {
return $resource('/admin/applications/:appId/resources/application-clients/:clientId', {
appId : '@appId',
clientId: '@clientId'
}, {
get : {
method : 'GET'
},
getList : {
method : 'GET',
params : { fields: '*(*)' }
},
update : {
method : 'PUT'
},
create : {
method : 'POST',
params : { appId : '@appId' }
},
createResource : {
method : 'POST',
url : '/admin/applications/:appId/resources',
params : { appId : '@appId' }
},
getResource : {
method : 'GET',
url: '/admin/applications/:appId/resources/application-clients',
params : { appId : '@appId' }
},
delete : {
method : 'DELETE'
}
});
});
loMod.factory('loPushPing', function($resource) {
return function(url){
return $resource('/admin/system/ups/module/ping', {}, {
ping : {
method : 'GET',
params : { url : url }
}
});
};
});
loMod.factory('LoBusinessLogicScripts', function($resource) {
return $resource('/admin/applications/:appId/resources/scripts/:type/:scriptId', {
appId : '@appId'
}, {
get : {
method : 'GET',
params : { fields: '*(*)' }
},
create: {
method: 'POST'
},
update: {
method: 'PUT'
},
getResource : {
method : 'GET',
url: '/admin/applications/:appId/resources/scripts/'
},
createResource : {
method : 'PUT',
url: '/admin/applications/:appId/resources/scripts',
params : { appId : '@appId'}
},
getSource : {
method : 'GET',
url: '/admin/applications/:appId/resources/scripts/:type/:scriptId/script'
},
setSource: {
method: 'POST',
headers: {
'Content-Type':'application/javascript'
}
}
});
});
loMod.service('loLiveLoader', function($q, $rootScope, $cacheFactory, loLiveSubscribe){
var liveCache = $cacheFactory('loLiveCache');
function interpretParameters(parameters){
var i;
if (parameters && angular.isFunction(parameters)) {
i = parameters();
} else if (parameters){
i = parameters;
} else {
i = {};
}
return i;
}
return function(resourceMethod, subscribeUrl, parameters){
var i = interpretParameters(parameters);
var defered = $q.defer(),
cacheKey = subscribeUrl+':'+i,
cachedObject = liveCache.get(cacheKey);
if(cachedObject){
defered.resolve(cachedObject);
return defered.promise;
}
var resource = resourceMethod(i),
deferedLive = $q.defer(),
output = {
resource: resource,
callbacks: resourceMethod.callbacks,
subscribeUrl: subscribeUrl,
parameters: i,
live: deferedLive.promise
};
resource.$promise.then(function(data) {
deferedLive.resolve(angular.copy(data));
output.subscribeId = loLiveSubscribe(output);
return output.subscribeId;
}).then(function(data){
output.subscribeId = data;
return deferedLive.promise;
}).then(function(data){
angular.extend(output.live, data);
defered.resolve(output);
liveCache.put(cacheKey, output);
return output.live.$promise;
});
return defered.promise;
};
});
loMod.factory('loLiveSubscribe', function($resource, LiveOak, $rootScope, $q) {
return function(liveObject){
var delay = $q.defer(),
callbacks = liveObject.callbacks;
function _callback(){
delay.resolve(LiveOak.subscribe(liveObject.subscribeUrl, function (data, action) {
$rootScope.$apply(function(){
if (callbacks[action]) {
liveObject.live.$promise.then(function(){
callbacks[action](data, liveObject.live);
});
}
});
}));
}
LiveOak.auth.updateToken(5).success(function() {
LiveOak.connect('Bearer', LiveOak.auth.token, _callback);
}).error(function() {
LiveOak.connect(_callback);
});
return delay.promise;
};
});
loMod.factory('LoLiveCollectionList', function($resource) {
var res = $resource('/:appId/:storageId', {
appId : '@appId',
storageId : '@storageId'
}, {
get : {
method : 'GET'
}
});
res.get.callbacks = {
create: function (data, liveObject) {
if(!liveObject.members) {
liveObject.members = [];
}
liveObject.members.push(data);
},
delete: function (data, liveObject) {
if(!liveObject.members) {
return liveObject;
}
for(var i = 0; i < liveObject.members.length; i++){
if (data.id === liveObject.members[i].id) {
liveObject.members.splice(i, 1);
break;
}
}
}
};
return res;
});
loMod.factory('LoLiveAppList', function($resource) {
var res = $resource('/admin/applications/', {}, {
getList: {
method: 'GET',
params: { fields: '*(*)' }
}
});
res.getList.callbacks = {
create: function (data, liveObject) {
if(!liveObject.members) {
liveObject.members = [];
}
liveObject.members.push(data);
},
delete: function (data, liveObject) {
if(!liveObject.members) {
return;
}
for(var i = 0; i < liveObject.members.length; i++){
if (data.id === liveObject.members[i].id) {
liveObject.members.splice(i, 1);
break;
}
}
}
};
return res;
});
loMod.provider('loRemoteCheck', function() {
this.delay = 300;
this.setDelay = function(customDelay) {
this.delay = customDelay;
};
this.$get = ['$rootScope', '$timeout', '$log', function($rootScope, $timeout) {
var delay = this.delay;
return function (timeoutPointer, resourceMethod, resourceParameters, callbacks) {
if (timeoutPointer){
$timeout.cancel(timeoutPointer);
}
var timeoutId = $timeout(function(){
resourceMethod(resourceParameters, function(data){
if (callbacks.success){
callbacks.success(data);
}
}, function(error){
if (callbacks.error){
callbacks.error(error);
}
});
}, delay);
return timeoutId;
};
}];
});
loMod.service('loJSON', function() {
this.toStringObject = function(jsonObject){
var stringObject = {};
for(var key in jsonObject){
var dType = typeof jsonObject[key];
if (dType === 'string'){
stringObject[key] = '"' + jsonObject[key] + '"';
} else {
stringObject[key] = angular.toJson(jsonObject[key]);
}
}
return stringObject;
};
this.parseJSON = function(stringObject){
var jsonObject = {};
// The doubled casting is to trim off angular stuff like the $$hashKey from properties
for(var key in angular.fromJson(angular.toJson(stringObject))){
var value = stringObject[key];
// If the value is empty then ignore
if(value === '') {
// If it's a string
} else if (value[0] === '"' && value[value.length - 1] === '"') {
jsonObject[key] = value.substr(1, value.length - 2);
// If it's a numbers
} else if (!isNaN(value)) {
jsonObject[key] = parseFloat(value);
// If it's a boolean
} else if (value === 'true' || value === 'false') {
jsonObject[key] = (value === 'true');
// If it's null
} else if (value === 'null') {
jsonObject[key] = null;
} else {
jsonObject[key] = JSON.parse(value);
}
}
return jsonObject;
};
this.isValidJSON = function(jsonObject) {
var valid = true;
try {
// The function is false only in case of error
JSON.parse(jsonObject);
} catch(e) {
valid = false;
}
return valid;
};
});
loMod.factory('LoMetrics', function($resource) {
return $resource('/rhq-metrics/:dataType', {
});
});
| ljshj/liveoak | console/src/main/resources/app/js/services.js | JavaScript | epl-1.0 | 20,221 |
(function ($) {
/**
* Attaches double-click behavior to toggle full path of Krumo elements.
*/
Drupal.behaviors.devel = {
attach: function (context, settings) {
// Add hint to footnote
$('.krumo-footnote .krumo-call').before('<img style="vertical-align: middle;" title="Click to expand. Double-click to show path." src="' + Drupal.settings.basePath + 'misc/help.png"/>');
var krumo_name = [];
var krumo_type = [];
function krumo_traverse(el) {
krumo_name.push($(el).html());
krumo_type.push($(el).siblings('em').html().match(/\w*/)[0]);
if ($(el).closest('.krumo-nest').length > 0) {
krumo_traverse($(el).closest('.krumo-nest').prev().find('.krumo-name'));
}
}
$('.krumo-child > div:first-child', context).dblclick(
function(e) {
if ($(this).find('> .krumo-php-path').length > 0) {
// Remove path if shown.
$(this).find('> .krumo-php-path').remove();
}
else {
// Get elements.
krumo_traverse($(this).find('> a.krumo-name'));
// Create path.
var krumo_path_string = '';
for (var i = krumo_name.length - 1; i >= 0; --i) {
// Start element.
if ((krumo_name.length - 1) == i)
krumo_path_string += '$' + krumo_name[i];
if (typeof krumo_name[(i-1)] !== 'undefined') {
if (krumo_type[i] == 'Array') {
krumo_path_string += "[";
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += krumo_name[(i-1)];
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += "]";
}
if (krumo_type[i] == 'Object')
krumo_path_string += '->' + krumo_name[(i-1)];
}
}
$(this).append('<div class="krumo-php-path" style="font-family: Courier, monospace; font-weight: bold;">' + krumo_path_string + '</div>');
// Reset arrays.
krumo_name = [];
krumo_type = [];
}
}
);
}
};
})(jQuery);
;/**/
(function ($) {
Drupal.behaviors.textarea = {
attach: function (context, settings) {
$('.form-textarea-wrapper.resizable', context).once('textarea', function () {
var staticOffset = null;
var textarea = $(this).addClass('resizable-textarea').find('textarea');
var grippie = $('<div class="grippie"></div>').mousedown(startDrag);
grippie.insertAfter(textarea);
function startDrag(e) {
staticOffset = textarea.height() - e.pageY;
textarea.css('opacity', 0.25);
$(document).mousemove(performDrag).mouseup(endDrag);
return false;
}
function performDrag(e) {
textarea.height(Math.max(32, staticOffset + e.pageY) + 'px');
return false;
}
function endDrag(e) {
$(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
textarea.css('opacity', 1);
}
});
}
};
})(jQuery);
;/**/
(function($) {
Drupal.admin = Drupal.admin || {};
Drupal.admin.behaviors = Drupal.admin.behaviors || {};
/**
* @ingroup admin_behaviors
* @{
*/
/**
* Apply active trail highlighting based on current path.
*
* @todo Not limited to toolbar; move into core?
*/
Drupal.admin.behaviors.toolbarActiveTrail = function (context, settings, $adminMenu) {
if (settings.admin_menu.toolbar && settings.admin_menu.toolbar.activeTrail) {
$adminMenu.find('> div > ul > li > a[href="' + settings.admin_menu.toolbar.activeTrail + '"]').addClass('active-trail');
}
};
/**
* @} End of "ingroup admin_behaviors".
*/
Drupal.admin.behaviors.shorcutcollapsed = function (context, settings, $adminMenu) {
// Create the dropdown base
$("<li class=\"label\"><a>"+Drupal.t('Shortcuts')+"</a></li>").prependTo("body.menu-render-collapsed div.toolbar-shortcuts ul");
}
Drupal.admin.behaviors.shorcutselect = function (context, settings, $adminMenu) {
// Create the dropdown base
$("<select id='shortcut-menu'/>").appendTo("body.menu-render-dropdown div.toolbar-shortcuts");
// Create default option "Select"
$("<option />", {
"selected" : "selected",
"value" : "",
"text" : Drupal.t('Shortcuts')
}).appendTo("body.menu-render-dropdown div.toolbar-shortcuts select");
// Populate dropdown with menu items
$("body.menu-render-dropdown div.toolbar-shortcuts a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("body.menu-render-dropdown div.toolbar-shortcuts select");
});
$("body.menu-render-dropdown div.toolbar-shortcuts select").change(function() {
window.location = $(this).find("option:selected").val();
});
$('body.menu-render-dropdown div.toolbar-shortcuts ul').remove();
};
})(jQuery);
;/**/
(function ($) {
/**
* A progressbar object. Initialized with the given id. Must be inserted into
* the DOM afterwards through progressBar.element.
*
* method is the function which will perform the HTTP request to get the
* progress bar state. Either "GET" or "POST".
*
* e.g. pb = new progressBar('myProgressBar');
* some_element.appendChild(pb.element);
*/
Drupal.progressBar = function (id, updateCallback, method, errorCallback) {
var pb = this;
this.id = id;
this.method = method || 'GET';
this.updateCallback = updateCallback;
this.errorCallback = errorCallback;
// The WAI-ARIA setting aria-live="polite" will announce changes after users
// have completed their current activity and not interrupt the screen reader.
this.element = $('<div class="progress" aria-live="polite"></div>').attr('id', id);
this.element.html('<div class="bar"><div class="filled"></div></div>' +
'<div class="percentage"></div>' +
'<div class="message"> </div>');
};
/**
* Set the percentage and status message for the progressbar.
*/
Drupal.progressBar.prototype.setProgress = function (percentage, message) {
if (percentage >= 0 && percentage <= 100) {
$('div.filled', this.element).css('width', percentage + '%');
$('div.percentage', this.element).html(percentage + '%');
}
$('div.message', this.element).html(message);
if (this.updateCallback) {
this.updateCallback(percentage, message, this);
}
};
/**
* Start monitoring progress via Ajax.
*/
Drupal.progressBar.prototype.startMonitoring = function (uri, delay) {
this.delay = delay;
this.uri = uri;
this.sendPing();
};
/**
* Stop monitoring progress via Ajax.
*/
Drupal.progressBar.prototype.stopMonitoring = function () {
clearTimeout(this.timer);
// This allows monitoring to be stopped from within the callback.
this.uri = null;
};
/**
* Request progress data from server.
*/
Drupal.progressBar.prototype.sendPing = function () {
if (this.timer) {
clearTimeout(this.timer);
}
if (this.uri) {
var pb = this;
// When doing a post request, you need non-null data. Otherwise a
// HTTP 411 or HTTP 406 (with Apache mod_security) error may result.
$.ajax({
type: this.method,
url: this.uri,
data: '',
dataType: 'json',
success: function (progress) {
// Display errors.
if (progress.status == 0) {
pb.displayError(progress.data);
return;
}
// Update display.
pb.setProgress(progress.percentage, progress.message);
// Schedule next timer.
pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay);
},
error: function (xmlhttp) {
pb.displayError(Drupal.ajaxError(xmlhttp, pb.uri));
}
});
}
};
/**
* Display errors on the page.
*/
Drupal.progressBar.prototype.displayError = function (string) {
var error = $('<div class="messages error"></div>').html(string);
$(this.element).before(error).hide();
if (this.errorCallback) {
this.errorCallback(this);
}
};
})(jQuery);
;/**/
/**
* JavaScript behaviors for the front-end display of webforms.
*/
(function ($) {
Drupal.behaviors.webform = Drupal.behaviors.webform || {};
Drupal.behaviors.webform.attach = function(context) {
// Calendar datepicker behavior.
Drupal.webform.datepicker(context);
// Conditional logic.
if (Drupal.settings.webform && Drupal.settings.webform.conditionals) {
Drupal.webform.conditional(context);
}
};
Drupal.webform = Drupal.webform || {};
Drupal.webform.datepicker = function(context) {
$('div.webform-datepicker').each(function() {
var $webformDatepicker = $(this);
var $calendar = $webformDatepicker.find('input.webform-calendar');
// Ensure the page we're on actually contains a datepicker.
if ($calendar.length == 0) {
return;
}
var startDate = $calendar[0].className.replace(/.*webform-calendar-start-(\d{4}-\d{2}-\d{2}).*/, '$1').split('-');
var endDate = $calendar[0].className.replace(/.*webform-calendar-end-(\d{4}-\d{2}-\d{2}).*/, '$1').split('-');
var firstDay = $calendar[0].className.replace(/.*webform-calendar-day-(\d).*/, '$1');
// Convert date strings into actual Date objects.
startDate = new Date(startDate[0], startDate[1] - 1, startDate[2]);
endDate = new Date(endDate[0], endDate[1] - 1, endDate[2]);
// Ensure that start comes before end for datepicker.
if (startDate > endDate) {
var laterDate = startDate;
startDate = endDate;
endDate = laterDate;
}
var startYear = startDate.getFullYear();
var endYear = endDate.getFullYear();
// Set up the jQuery datepicker element.
$calendar.datepicker({
dateFormat: 'yy-mm-dd',
yearRange: startYear + ':' + endYear,
firstDay: parseInt(firstDay),
minDate: startDate,
maxDate: endDate,
onSelect: function(dateText, inst) {
var date = dateText.split('-');
$webformDatepicker.find('select.year, input.year').val(+date[0]).trigger('change');
$webformDatepicker.find('select.month').val(+date[1]).trigger('change');
$webformDatepicker.find('select.day').val(+date[2]).trigger('change');
},
beforeShow: function(input, inst) {
// Get the select list values.
var year = $webformDatepicker.find('select.year, input.year').val();
var month = $webformDatepicker.find('select.month').val();
var day = $webformDatepicker.find('select.day').val();
// If empty, default to the current year/month/day in the popup.
var today = new Date();
year = year ? year : today.getFullYear();
month = month ? month : today.getMonth() + 1;
day = day ? day : today.getDate();
// Make sure that the default year fits in the available options.
year = (year < startYear || year > endYear) ? startYear : year;
// jQuery UI Datepicker will read the input field and base its date off
// of that, even though in our case the input field is a button.
$(input).val(year + '-' + month + '-' + day);
}
});
// Prevent the calendar button from submitting the form.
$calendar.click(function(event) {
$(this).focus();
event.preventDefault();
});
});
};
Drupal.webform.conditional = function(context) {
// Add the bindings to each webform on the page.
$.each(Drupal.settings.webform.conditionals, function(formKey, settings) {
var $form = $('.' + formKey + ':not(.webform-conditional-processed)');
$form.each(function(index, currentForm) {
var $currentForm = $(currentForm);
$currentForm.addClass('webform-conditional-processed');
$currentForm.bind('change', { 'settings': settings }, Drupal.webform.conditionalCheck);
// Trigger all the elements that cause conditionals on this form.
$.each(Drupal.settings.webform.conditionals[formKey]['sourceMap'], function(elementKey) {
$currentForm.find('.' + elementKey).find('input,select,textarea').filter(':first').trigger('change');
});
})
});
};
/**
* Event handler to respond to field changes in a form.
*
* This event is bound to the entire form, not individual fields.
*/
Drupal.webform.conditionalCheck = function(e) {
var $triggerElement = $(e.target).closest('.webform-component');
var $form = $triggerElement.closest('form');
var triggerElementKey = $triggerElement.attr('class').match(/webform-component--[^ ]+/)[0];
var settings = e.data.settings;
if (settings.sourceMap[triggerElementKey]) {
$.each(settings.sourceMap[triggerElementKey], function(n, rgid) {
var ruleGroup = settings.ruleGroups[rgid];
// Perform the comparison callback and build the results for this group.
var conditionalResult = true;
var conditionalResults = [];
$.each(ruleGroup['rules'], function(m, rule) {
var elementKey = rule['source'];
var element = $form.find('.' + elementKey)[0];
var existingValue = settings.values[elementKey] ? settings.values[elementKey] : null;
conditionalResults.push(window['Drupal']['webform'][rule.callback](element, existingValue, rule['value'] ));
});
// Filter out false values.
var filteredResults = [];
for (var i = 0; i < conditionalResults.length; i++) {
if (conditionalResults[i]) {
filteredResults.push(conditionalResults[i]);
}
}
// Calculate the and/or result.
if (ruleGroup['andor'] === 'or') {
conditionalResult = filteredResults.length > 0;
}
else {
conditionalResult = filteredResults.length === conditionalResults.length;
}
// Flip the result of the action is to hide.
var showComponent;
if (ruleGroup['action'] == 'hide') {
showComponent = !conditionalResult;
}
else {
showComponent = conditionalResult;
}
var $target = $form.find('.' + ruleGroup['target']);
var $targetElements;
if (showComponent) {
$targetElements = $target.find('.webform-conditional-disabled').removeClass('webform-conditional-disabled');
$.fn.prop ? $targetElements.prop('disabled', false) : $targetElements.removeAttr('disabled');
$target.show();
}
else {
$targetElements = $target.find(':input').addClass('webform-conditional-disabled');
$.fn.prop ? $targetElements.prop('disabled', true) : $targetElements.attr('disabled', true);
$target.hide();
}
});
}
};
Drupal.webform.conditionalOperatorStringEqual = function(element, existingValue, ruleValue) {
var returnValue = false;
var currentValue = Drupal.webform.stringValue(element, existingValue);
$.each(currentValue, function(n, value) {
if (value.toLowerCase() === ruleValue.toLowerCase()) {
returnValue = true;
return false; // break.
}
});
return returnValue;
};
Drupal.webform.conditionalOperatorStringNotEqual = function(element, existingValue, ruleValue) {
var found = false;
var currentValue = Drupal.webform.stringValue(element, existingValue);
$.each(currentValue, function(n, value) {
if (value.toLowerCase() === ruleValue.toLowerCase()) {
found = true;
}
});
return !found;
};
Drupal.webform.conditionalOperatorStringContains = function(element, existingValue, ruleValue) {
var returnValue = false;
var currentValue = Drupal.webform.stringValue(element, existingValue);
$.each(currentValue, function(n, value) {
if (value.toLowerCase().indexOf(ruleValue.toLowerCase()) > -1) {
returnValue = true;
return false; // break.
}
});
return returnValue;
};
Drupal.webform.conditionalOperatorStringDoesNotContain = function(element, existingValue, ruleValue) {
var found = false;
var currentValue = Drupal.webform.stringValue(element, existingValue);
$.each(currentValue, function(n, value) {
if (value.toLowerCase().indexOf(ruleValue.toLowerCase()) > -1) {
found = true;
}
});
return !found;
};
Drupal.webform.conditionalOperatorStringBeginsWith = function(element, existingValue, ruleValue) {
var returnValue = false;
var currentValue = Drupal.webform.stringValue(element, existingValue);
$.each(currentValue, function(n, value) {
if (value.toLowerCase().indexOf(ruleValue.toLowerCase()) === 0) {
returnValue = true;
return false; // break.
}
});
return returnValue;
};
Drupal.webform.conditionalOperatorStringEndsWith = function(element, existingValue, ruleValue) {
var returnValue = false;
var currentValue = Drupal.webform.stringValue(element, existingValue);
$.each(currentValue, function(n, value) {
if (value.toLowerCase().lastIndexOf(ruleValue.toLowerCase()) === value.length - ruleValue.length) {
returnValue = true;
return false; // break.
}
});
return returnValue;
};
Drupal.webform.conditionalOperatorStringEmpty = function(element, existingValue, ruleValue) {
var currentValue = Drupal.webform.stringValue(element, existingValue);
var returnValue = true;
$.each(currentValue, function(n, value) {
if (value !== '') {
returnValue = false;
return false; // break.
}
});
return returnValue;
};
Drupal.webform.conditionalOperatorStringNotEmpty = function(element, existingValue, ruleValue) {
return !Drupal.webform.conditionalOperatorStringEmpty(element, existingValue, ruleValue);
};
Drupal.webform.conditionalOperatorNumericEqual = function(element, existingValue, ruleValue) {
// See float comparison: http://php.net/manual/en/language.types.float.php
var currentValue = Drupal.webform.stringValue(element, existingValue);
var epsilon = 0.000001;
// An empty string does not match any number.
return currentValue[0] === '' ? false : (Math.abs(parseFloat(currentValue[0]) - parseFloat(ruleValue)) < epsilon);
};
Drupal.webform.conditionalOperatorNumericNotEqual = function(element, existingValue, ruleValue) {
// See float comparison: http://php.net/manual/en/language.types.float.php
var currentValue = Drupal.webform.stringValue(element, existingValue);
var epsilon = 0.000001;
// An empty string does not match any number.
return currentValue[0] === '' ? true : (Math.abs(parseFloat(currentValue[0]) - parseFloat(ruleValue)) >= epsilon);
};
Drupal.webform.conditionalOperatorNumericGreaterThan = function(element, existingValue, ruleValue) {
var currentValue = Drupal.webform.stringValue(element, existingValue);
return parseFloat(currentValue[0]) > parseFloat(ruleValue);
};
Drupal.webform.conditionalOperatorNumericLessThan = function(element, existingValue, ruleValue) {
var currentValue = Drupal.webform.stringValue(element, existingValue);
return parseFloat(currentValue[0]) < parseFloat(ruleValue);
};
Drupal.webform.conditionalOperatorDateEqual = function(element, existingValue, ruleValue) {
var currentValue = Drupal.webform.timeValue(element, existingValue);
return currentValue === ruleValue;
};
Drupal.webform.conditionalOperatorDateBefore = function(element, existingValue, ruleValue) {
var currentValue = Drupal.webform.dateValue(element, existingValue);
return (currentValue !== false) && currentValue < ruleValue;
};
Drupal.webform.conditionalOperatorDateAfter = function(element, existingValue, ruleValue) {
var currentValue = Drupal.webform.dateValue(element, existingValue);
return (currentValue !== false) && currentValue > ruleValue;
};
Drupal.webform.conditionalOperatorTimeEqual = function(element, existingValue, ruleValue) {
var currentValue = Drupal.webform.timeValue(element, existingValue);
return currentValue === ruleValue;
};
Drupal.webform.conditionalOperatorTimeBefore = function(element, existingValue, ruleValue) {
// Date and time operators intentionally exclusive for "before".
var currentValue = Drupal.webform.timeValue(element, existingValue);
return (currentValue !== false) && (currentValue < ruleValue);
};
Drupal.webform.conditionalOperatorTimeAfter = function(element, existingValue, ruleValue) {
// Date and time operators intentionally inclusive for "after".
var currentValue = Drupal.webform.timeValue(element, existingValue);
return (currentValue !== false) && (currentValue >= ruleValue);
};
/**
* Utility function to get a string value from a select/radios/text/etc. field.
*/
Drupal.webform.stringValue = function(element, existingValue) {
var value = [];
if (element) {
// Checkboxes and radios.
$(element).find('input[type=checkbox]:checked,input[type=radio]:checked').each(function() {
value.push(this.value);
});
// Select lists.
if (!value.length) {
var selectValue = $(element).find('select').val();
if (selectValue) {
value.push(selectValue);
}
}
// Simple text fields. This check is done last so that the select list in
// select-or-other fields comes before the "other" text field.
if (!value.length) {
$(element).find('input:not([type=checkbox],[type=radio]),textarea').each(function() {
value.push(this.value);
});
}
}
else if (existingValue) {
value = existingValue;
}
return value;
};
/**
* Utility function to calculate a millisecond timestamp from a time field.
*/
Drupal.webform.dateValue = function(element, existingValue) {
if (element) {
var day = $(element).find('[name*=day]').val();
var month = $(element).find('[name*=month]').val();
var year = $(element).find('[name*=year]').val();
// Months are 0 indexed in JavaScript.
if (month) {
month--;
}
return (year !== '' && month !== '' && day !== '') ? Date.UTC(year, month, day) : false;
}
else {
var existingValue = existingValue.length ? existingValue[0].split('-') : existingValue;
return existingValue.length ? Date.UTC(existingValue[0], existingValue[1], existingValue[2]) : false;
}
};
/**
* Utility function to calculate a millisecond timestamp from a time field.
*/
Drupal.webform.timeValue = function(element, existingValue) {
if (element) {
var hour = $(element).find('[name*=hour]').val();
var minute = $(element).find('[name*=minute]').val();
var ampm = $(element).find('[name*=ampm]:checked').val();
// Convert to integers if set.
hour = (hour === '') ? hour : parseInt(hour);
minute = (minute === '') ? minute : parseInt(minute);
if (hour !== '') {
hour = (hour < 12 && ampm == 'pm') ? hour + 12 : hour;
hour = (hour === 12 && ampm == 'am') ? 0 : hour;
}
return (hour !== '' && minute !== '') ? Date.UTC(1970, 0, 1, hour, minute) : false;
}
else {
var existingValue = existingValue.length ? existingValue[0].split(':') : existingValue;
return existingValue.length ? Date.UTC(1970, 0, 1, existingValue[0], existingValue[1]) : false;
}
};
})(jQuery);
;/**/
(function ($) {
Drupal.behaviors.colorboxNode = {
// Lets find our class name and change our URL to
// our defined menu path to open in a colorbox modal.
attach: function (context, settings) {
// Make sure colorbox exists.
if (!$.isFunction($.colorbox)) {
return;
}
// Mobile detection extracted from the colorbox module.
// If the mobile setting is turned on, it will turn off the colorbox modal for mobile devices.
if (settings.colorbox.mobiledetect && window.matchMedia) {
// Disable Colorbox for small screens.
mq = window.matchMedia("(max-device-width: " + settings.colorbox.mobiledevicewidth + ")");
if (mq.matches) {
return;
}
}
$('.colorbox-node', context).once('init-colorbox-node-processed', function () {
$(this).colorboxNode({'launch': false});
});
// When using contextual links and clicking from within the colorbox
// we need to close down colorbox when opening the built in overlay.
$('ul.contextual-links a', context).once('colorboxNodeContextual').click(function () {
$.colorbox.close();
});
}
};
// Bind our colorbox node functionality to an anchor
$.fn.colorboxNode = function (options) {
var settings = {
'launch': true
};
$.extend(settings, options);
var href = $(this).attr('data-href');
if (typeof href == 'undefined' || href == false) {
href = $(this).attr('href');
}
// Create an element so we can parse our a URL no matter if its internal or external.
var parse = document.createElement('a');
parse.href = href;
// Lets add our colorbox link after the base path if necessary.
var base_path = Drupal.settings.basePath;
var pathname = parse.pathname;
// Lets check to see if the pathname has a forward slash.
// This problem happens in IE7/IE8
if (pathname.charAt(0) != '/') {
pathname = '/' + parse.pathname;
}
// If clean URL's are not turned on, lets check for that.
var url = $.getParameterByName('q', href);
if (base_path != '/') {
if (url != '') {
var link = pathname.replace(base_path, base_path + '?q=colorbox/') + url;
} else {
console.log('check2');
var link = pathname.replace(base_path, base_path + 'colorbox/') + parse.search;
}
} else {
if (url != '') {
var link = base_path + '?q=colorbox' + pathname + url;
} else {
var link = base_path + 'colorbox' + pathname + parse.search;
}
}
// Bind Ajax behaviors to all items showing the class.
var element_settings = {};
// This removes any loading/progress bar on the clicked link
// and displays the colorbox loading screen instead.
element_settings.progress = { 'type': 'none' };
// For anchor tags, these will go to the target of the anchor rather
// than the usual location.
if (href) {
element_settings.url = link;
element_settings.event = 'click';
}
$(this).click(function () {
$this = $(this).clone();
// Clear out the rel to prevent any confusion if not using the gallery class.
if(!$this.hasClass('colorbox-node-gallery')) {
$this.attr('rel', '');
}
// Lets extract our width and height giving priority to the data attributes.
var innerWidth = $this.data('inner-width');
var innerHeight = $this.data('inner-height');
if (typeof innerWidth != 'undefined' && typeof innerHeight != 'undefined') {
var params = $.urlDataParams(innerWidth, innerHeight);
} else {
var params = $.urlParams(href);
}
params.html = '<div id="colorboxNodeLoading"></div>';
params.onComplete = function () {
$this.colorboxNodeGroup();
}
params.open = true;
// Launch our colorbox with the provided settings
$this.colorbox($.extend({}, Drupal.settings.colorbox, params));
});
// Log our click handler to our ajax object
var base = $(this).attr('id');
Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
// Default to auto click for manual call to this function.
if (settings.launch) {
Drupal.ajax[base].eventResponse(this, 'click');
$(this).click();
}
}
// Allow for grouping on links to showcase a gallery with left/right arrows.
// This function will find the next index of each link on the page by the rel
// and manually force a click on the link to call that AJAX and update the
// modal window.
$.fn.colorboxNodeGroup = function () {
// Lets do setup our gallery type of functions.
var $this = $(this);
var rel = $this.attr('rel');
if(rel && $this.hasClass('colorbox-node-gallery')) {
if ($('a.colorbox-node-gallery[rel="' + rel + '"]:not("#colorbox a[rel="' + rel + '"]")').length > 1) {
$related = $('a.colorbox-node-gallery[rel="' + rel + '"]:not("#colorbox a[rel="' + rel + '"]")');
// filter $related array by href, to have mutliple colorbox links to the same target
// appear as one item in the gallery only
var $related_unique = [];
$related.each(function() {
findHref($related_unique, this.href);
if (!findHref($related_unique, this.href).length) {
$related_unique.push(this);
}
});
// we have to get the actual used element from the filtered list in order to get it's relative index
var current = findHref($related_unique, $this.get(0).href);
$related = $($related_unique);
var idx = $related.index($(current));
var tot = $related.length;
// Show our gallery buttons
$('#cboxPrevious, #cboxNext').show();
$.colorbox.next = function () {
index = getIndex(1);
$related[index].click();
};
$.colorbox.prev = function () {
index = getIndex(-1);
$related[index].click();
};
// Setup our current HTML
$('#cboxCurrent').html(Drupal.settings.colorbox.current.replace('{current}', idx + 1).replace('{total}', tot)).show();
var prefix = 'colorbox';
// Remove Bindings and re-add
// @TODO: There must be a better way? If we don't remove it causes a memory to be exhausted.
$(document).unbind('keydown.' + prefix);
// Add Key Bindings
$(document).bind('keydown.' + prefix, function (e) {
var key = e.keyCode;
if ($related[1] && !e.altKey) {
if (key === 37) {
e.preventDefault();
$.colorbox.prev();
} else if (key === 39) {
e.preventDefault();
$.colorbox.next();
}
}
});
}
function getIndex(increment) {
var max = $related.length;
var newIndex = (idx + increment) % max;
return (newIndex < 0) ? max + newIndex : newIndex;
}
// Find a colorbox link by href in an array
function findHref(items, href){
return $.grep(items, function(n, i){
return n.href == href;
});
};
}
}
// Utility function to parse out our width/height from our url params
$.urlParams = function (url) {
var p = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) {
return decodeURIComponent(s.replace(a, ' '));
},
q = url.split('?');
while (e = r.exec(q[1])) {
e[1] = d(e[1]);
e[2] = d(e[2]);
switch (e[2].toLowerCase()) {
case 'true':
case 'yes':
e[2] = true;
break;
case 'false':
case 'no':
e[2] = false;
break;
}
if (e[1] == 'width') {
e[1] = 'innerWidth';
}
if (e[1] == 'height') {
e[1] = 'innerHeight';
}
p[e[1]] = e[2];
}
return p;
};
// Utility function to return our data attributes for width/height
$.urlDataParams = function (innerWidth, innerHeight) {
return {'innerWidth':innerWidth,'innerHeight':innerHeight};
};
$.getParameterByName = function(name, href) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexString = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexString);
var found = regex.exec(href);
if(found == null)
return "";
else
return decodeURIComponent(found[1].replace(/\+/g, " "));
}
})(jQuery);
;/**/
| ulearn/eidold | sites/default/files/advagg_js/js__3mpbjAkdOcIuSUZ_9LyCr_KTwM94J1pqJyL1Uxh1FqQ__XWprcViJmNYCdT5sTaW5I_7dbZSizWt8RP6cEJyzFAM__EBWH9cFDDFRncXGTPlGiSfnXM5oTMZR11Ss_cNF_Z5I.js | JavaScript | gpl-2.0 | 32,833 |
Type.registerNamespace("Sys.Extended.UI.HtmlEditor.ToolbarButtons");Sys.Extended.UI.HtmlEditor.ToolbarButtons.StrikeThrough=function(n){Sys.Extended.UI.HtmlEditor.ToolbarButtons.StrikeThrough.initializeBase(this,[n])};Sys.Extended.UI.HtmlEditor.ToolbarButtons.StrikeThrough.prototype={callMethod:function(){if(!Sys.Extended.UI.HtmlEditor.ToolbarButtons.StrikeThrough.callBaseMethod(this,"callMethod"))return!1;this._designPanel._execCommand("strikeThrough",!1,null)},checkState:function(){return Sys.Extended.UI.HtmlEditor.ToolbarButtons.StrikeThrough.callBaseMethod(this,"checkState")?this._designPanel._queryCommandState("strikeThrough"):!1}};Sys.Extended.UI.HtmlEditor.ToolbarButtons.StrikeThrough.registerClass("Sys.Extended.UI.HtmlEditor.ToolbarButtons.StrikeThrough",Sys.Extended.UI.HtmlEditor.ToolbarButtons.EditorToggleButton); | donghang11/Support-Page | packages/AjaxControlToolkit.StaticResources.15.1.3.0/Content/Scripts/AjaxControlToolkit/Release/HtmlEditor.ToolbarButtons.StrikeThrough.js | JavaScript | gpl-2.0 | 838 |
/**
* @license AngularJS v1.5.1-build.4606+sha.b8b5b88
* (c) 2010-2016 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'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');
/**
* @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">
<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>
*/
/**
* @ngdoc provider
* @name $sanitizeProvider
*
* @description
* Creates and configures {@link $sanitize} instance.
*/
function $SanitizeProvider() {
var svgEnabled = false;
this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
if (svgEnabled) {
angular.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=} regexp New regexp to whitelist urls with.
* @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called
* without an argument or self for chaining otherwise.
*/
this.enableSvg = function(enableSvg) {
if (angular.isDefined(enableSvg)) {
svgEnabled = enableSvg;
return this;
} else {
return svgEnabled;
}
};
}
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 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 = angular.extend({},
optionalEndTagInlineElements,
optionalEndTagBlockElements);
// Safe Block Elements - HTML5
var blockElements = angular.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 = angular.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 = angular.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 = angular.extend({},
uriAttrs,
svgAttrs,
htmlAttrs);
function toMap(str, lowercaseKeys) {
var obj = {}, items = str.split(','), i;
for (i = 0; i < items.length; i++) {
obj[lowercaseKeys ? angular.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 htmlParser(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 (document.documentMode <= 11) {
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 htmlSanitizeWriter(buf, uriValidator) {
var ignoreCurrentElement = false;
var out = angular.bind(buf, buf.push);
return {
start: function(tag, attrs) {
tag = angular.lowercase(tag);
if (!ignoreCurrentElement && blockedElements[tag]) {
ignoreCurrentElement = tag;
}
if (!ignoreCurrentElement && 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 (validAttrs[lkey] === true &&
(uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
out(' ');
out(key);
out('="');
out(encodeEntities(value));
out('"');
}
});
out('>');
}
},
end: function(tag) {
tag = angular.lowercase(tag);
if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) {
out('</');
out(tag);
out('>');
}
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 === 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.indexOf('ns1:') === 0) {
node.removeAttributeNode(attrNode);
i--;
l--;
}
}
}
var nextNode = node.firstChild;
if (nextNode) {
stripCustomNsAttrs(nextNode);
}
nextNode = node.nextSibling;
if (nextNode) {
stripCustomNsAttrs(nextNode);
}
}
// 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.
* @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">
<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 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 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;
html.push('<a ');
if (angular.isFunction(attributes)) {
attributes = attributes(url);
}
if (angular.isObject(attributes)) {
for (key in attributes) {
html.push(key + '="' + attributes[key] + '" ');
}
} else {
attributes = {};
}
if (angular.isDefined(target) && !('target' in attributes)) {
html.push('target="',
target,
'" ');
}
html.push('href="',
url.replace(/"/g, '"'),
'">');
addText(text);
html.push('</a>');
}
};
}]);
})(window, window.angular);
| ByteCodeTeam/BitAsean-Wallet | www/lib/thirdparty/angular-sanitize.js | JavaScript | gpl-3.0 | 25,678 |
const crypto = require('crypto')
const BN = require('bn.js')
const error = require('../constants.js').ERROR
const fees = require('ethereum-common')
module.exports = function (opts) {
var sha256 = crypto.createHash('SHA256')
var data = opts.data
var results = {}
var gasCost = fees.sha256Gas.v
results.gasUsed = gasCost
var dataGas = Math.ceil(data.length / 32) * fees.sha256WordGas.v
results.gasUsed += dataGas
results.gasUsed = new BN(results.gasUsed)
if (opts.gasLimit.cmp(new BN(gasCost + dataGas)) === -1) {
results.gasUsed = opts.gasLimit
results.exceptionError = error.OUT_OF_GAS
results.exception = 0 // 0 means VM fail (in this case because of OOG)
return results
}
hashStr = sha256.update(data).digest('hex')
results.return = new Buffer(hashStr, 'hex')
results.exception = 1;
return results;
}
| jpentland/BitBadge | node_modules/grunt-embark/node_modules/embark-framework/node_modules/ethersim/node_modules/ethereumjs-vm/lib/precompiled/02-sha256.js | JavaScript | gpl-3.0 | 852 |
var util = require("util");
var assert = require("assert");
var tools = require("../tools");
var base = Object;
module.exports = (function(target){
util.inherits(target, base);
target.prototype.categories = [];
target.prototype.onToken = function(token){
this.parser.unexpected(token);
};//onToken
target.prototype.echo = function(data, source){
this.parent && this.parent.echo(data, source || this);
};//echo
target.prototype.end = function(endToken){
this.echo(this.suffix, {});
endToken && (this.content += endToken[0]);
this.parent && (this.parent.content += this.content);
return this.parent;
};//end
return target;
})(function(parent, beginToken){
base.call(this);
this.parent = parent;
this.beginToken = beginToken;
this.parser = this.parser || this.parent.parser;
this.suffix = this.suffix || '';
this.content = this.content || '';
this.beginToken && (this.content += this.beginToken[0]);
});
| RubenEngels123/nodejs-website | node_modules/php/lib/php/ContextBase.js | JavaScript | gpl-3.0 | 947 |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'about', 'pt', {
copy: 'Direitos de Autor © $1. Todos os direitos reservados.',
dlgTitle: 'Sobre o CKEditor',
help: 'Doar $1 para ajudar.',
moreInfo: 'Para informação sobre licenciamento visite o nosso sítio web:',
title: 'Sobre o CKEditor',
userGuide: 'CKEditor - Guia do Utilizador'
} );
| igor-borisov/valamis | learn-portlet/src/main/webapp/js2.0/vendor/ckeditor/plugins/about/lang/pt.js | JavaScript | gpl-3.0 | 476 |
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Most likely it's depracated classes.
* Not used anywhere among pages.
*/
VarienForm = Class.create();
VarienForm.prototype = {
initialize: function(formId, firstFieldFocus){
this.form = $(formId);
if (!this.form) {
return;
}
this.cache = $A();
this.currLoader = false;
this.currDataIndex = false;
this.validator = new Validation(this.form);
this.elementFocus = this.elementOnFocus.bindAsEventListener(this);
this.elementBlur = this.elementOnBlur.bindAsEventListener(this);
this.childLoader = this.onChangeChildLoad.bindAsEventListener(this);
this.highlightClass = 'highlight';
this.extraChildParams = '';
this.firstFieldFocus= firstFieldFocus || false;
this.bindElements();
if(this.firstFieldFocus){
try{
Form.Element.focus(Form.findFirstElement(this.form))
}
catch(e){}
}
},
submit : function(url){
if(this.validator && this.validator.validate()){
this.form.submit();
}
return false;
},
bindElements:function (){
var elements = Form.getElements(this.form);
for (var row in elements) {
if (elements[row].id) {
Event.observe(elements[row],'focus',this.elementFocus);
Event.observe(elements[row],'blur',this.elementBlur);
}
}
},
elementOnFocus: function(event){
var element = Event.findElement(event, 'fieldset');
if(element){
Element.addClassName(element, this.highlightClass);
}
},
elementOnBlur: function(event){
var element = Event.findElement(event, 'fieldset');
if(element){
Element.removeClassName(element, this.highlightClass);
}
},
setElementsRelation: function(parent, child, dataUrl, first){
if (parent=$(parent)) {
// TODO: array of relation and caching
if (!this.cache[parent.id]){
this.cache[parent.id] = $A();
this.cache[parent.id]['child'] = child;
this.cache[parent.id]['dataUrl'] = dataUrl;
this.cache[parent.id]['data'] = $A();
this.cache[parent.id]['first'] = first || false;
}
Event.observe(parent,'change',this.childLoader);
}
},
onChangeChildLoad: function(event){
element = Event.element(event);
this.elementChildLoad(element);
},
elementChildLoad: function(element, callback){
this.callback = callback || false;
if (element.value) {
this.currLoader = element.id;
this.currDataIndex = element.value;
if (this.cache[element.id]['data'][element.value]) {
this.setDataToChild(this.cache[element.id]['data'][element.value]);
}
else{
new Ajax.Request(this.cache[this.currLoader]['dataUrl'],{
method: 'post',
parameters: {"parent":element.value},
onComplete: this.reloadChildren.bind(this)
});
}
}
},
reloadChildren: function(transport){
var data = eval('(' + transport.responseText + ')');
this.cache[this.currLoader]['data'][this.currDataIndex] = data;
this.setDataToChild(data);
},
setDataToChild: function(data){
if (data.length) {
var child = $(this.cache[this.currLoader]['child']);
if (child){
var html = '<select name="'+child.name+'" id="'+child.id+'" class="'+child.className+'" title="'+child.title+'" '+this.extraChildParams+'>';
if(this.cache[this.currLoader]['first']){
html+= '<option value="">'+this.cache[this.currLoader]['first']+'</option>';
}
for (var i in data){
if(data[i].value) {
html+= '<option value="'+data[i].value+'"';
if(child.value && (child.value == data[i].value || child.value == data[i].label)){
html+= ' selected';
}
html+='>'+data[i].label+'</option>';
}
}
html+= '</select>';
Element.insert(child, {before: html});
Element.remove(child);
}
}
else{
var child = $(this.cache[this.currLoader]['child']);
if (child){
var html = '<input type="text" name="'+child.name+'" id="'+child.id+'" class="'+child.className+'" title="'+child.title+'" '+this.extraChildParams+'>';
Element.insert(child, {before: html});
Element.remove(child);
}
}
this.bindElements();
if (this.callback) {
this.callback();
}
}
}
RegionUpdater = Class.create();
RegionUpdater.prototype = {
initialize: function (countryEl, regionTextEl, regionSelectEl, regions, disableAction, zipEl)
{
this.countryEl = $(countryEl);
this.regionTextEl = $(regionTextEl);
this.regionSelectEl = $(regionSelectEl);
this.zipEl = $(zipEl);
this.config = regions['config'];
delete regions.config;
this.regions = regions;
this.disableAction = (typeof disableAction=='undefined') ? 'hide' : disableAction;
this.zipOptions = (typeof zipOptions=='undefined') ? false : zipOptions;
if (this.regionSelectEl.options.length<=1) {
this.update();
}
Event.observe(this.countryEl, 'change', this.update.bind(this));
},
_checkRegionRequired: function()
{
var label, wildCard;
var elements = [this.regionTextEl, this.regionSelectEl];
var that = this;
if (typeof this.config == 'undefined') {
return;
}
var regionRequired = this.config.regions_required.indexOf(this.countryEl.value) >= 0;
elements.each(function(currentElement) {
Validation.reset(currentElement);
label = $$('label[for="' + currentElement.id + '"]')[0];
if (label) {
wildCard = label.down('em') || label.down('span.required');
if (!that.config.show_all_regions) {
if (regionRequired) {
label.up().show();
} else {
label.up().hide();
}
}
}
if (label && wildCard) {
if (!regionRequired) {
wildCard.hide();
if (label.hasClassName('required')) {
label.removeClassName('required');
}
} else if (regionRequired) {
wildCard.show();
if (!label.hasClassName('required')) {
label.addClassName('required')
}
}
}
if (!regionRequired) {
if (currentElement.hasClassName('required-entry')) {
currentElement.removeClassName('required-entry');
}
if ('select' == currentElement.tagName.toLowerCase() &&
currentElement.hasClassName('validate-select')) {
currentElement.removeClassName('validate-select');
}
} else {
if (!currentElement.hasClassName('required-entry')) {
currentElement.addClassName('required-entry');
}
if ('select' == currentElement.tagName.toLowerCase() &&
!currentElement.hasClassName('validate-select')) {
currentElement.addClassName('validate-select');
}
}
});
},
update: function()
{
if (this.regions[this.countryEl.value]) {
var i, option, region, def;
def = this.regionSelectEl.getAttribute('defaultValue');
if (this.regionTextEl) {
if (!def) {
def = this.regionTextEl.value.toLowerCase();
}
this.regionTextEl.value = '';
}
this.regionSelectEl.options.length = 1;
for (regionId in this.regions[this.countryEl.value]) {
region = this.regions[this.countryEl.value][regionId];
option = document.createElement('OPTION');
option.value = regionId;
option.text = region.name.stripTags();
option.title = region.name;
if (this.regionSelectEl.options.add) {
this.regionSelectEl.options.add(option);
} else {
this.regionSelectEl.appendChild(option);
}
if (regionId==def || (region.name && region.name.toLowerCase()==def) ||
(region.name && region.code.toLowerCase()==def)
) {
this.regionSelectEl.value = regionId;
}
}
if (this.disableAction=='hide') {
if (this.regionTextEl) {
this.regionTextEl.style.display = 'none';
}
this.regionSelectEl.style.display = '';
} else if (this.disableAction=='disable') {
if (this.regionTextEl) {
this.regionTextEl.disabled = true;
}
this.regionSelectEl.disabled = false;
}
this.setMarkDisplay(this.regionSelectEl, true);
} else {
this.regionSelectEl.options.length = 1;
if (this.disableAction=='hide') {
if (this.regionTextEl) {
this.regionTextEl.style.display = '';
}
this.regionSelectEl.style.display = 'none';
Validation.reset(this.regionSelectEl);
} else if (this.disableAction=='disable') {
if (this.regionTextEl) {
this.regionTextEl.disabled = false;
}
this.regionSelectEl.disabled = true;
} else if (this.disableAction=='nullify') {
this.regionSelectEl.options.length = 1;
this.regionSelectEl.value = '';
this.regionSelectEl.selectedIndex = 0;
this.lastCountryId = '';
}
this.setMarkDisplay(this.regionSelectEl, false);
}
this._checkRegionRequired();
// Make Zip and its label required/optional
var zipUpdater = new ZipUpdater(this.countryEl.value, this.zipEl);
zipUpdater.update();
},
setMarkDisplay: function(elem, display){
elem = $(elem);
var labelElement = elem.up(0).down('label > span.required') ||
elem.up(1).down('label > span.required') ||
elem.up(0).down('label.required > em') ||
elem.up(1).down('label.required > em');
if(labelElement) {
inputElement = labelElement.up().next('input');
if (display) {
labelElement.show();
if (inputElement) {
inputElement.addClassName('required-entry');
}
} else {
labelElement.hide();
if (inputElement) {
inputElement.removeClassName('required-entry');
}
}
}
}
}
ZipUpdater = Class.create();
ZipUpdater.prototype = {
initialize: function(country, zipElement)
{
this.country = country;
this.zipElement = $(zipElement);
},
update: function()
{
// Country ISO 2-letter codes must be pre-defined
if (typeof optionalZipCountries == 'undefined') {
return false;
}
// Ajax-request and normal content load compatibility
if (this.zipElement != undefined) {
this._setPostcodeOptional();
} else {
Event.observe(window, "load", this._setPostcodeOptional.bind(this));
}
},
_setPostcodeOptional: function()
{
this.zipElement = $(this.zipElement);
if (this.zipElement == undefined) {
return false;
}
// find label
var label = $$('label[for="' + this.zipElement.id + '"]')[0];
if (label != undefined) {
var wildCard = label.down('em') || label.down('span.required');
}
// Make Zip and its label required/optional
if (optionalZipCountries.indexOf(this.country) != -1) {
while (this.zipElement.hasClassName('required-entry')) {
this.zipElement.removeClassName('required-entry');
}
if (wildCard != undefined) {
wildCard.hide();
}
} else {
this.zipElement.addClassName('required-entry');
if (wildCard != undefined) {
wildCard.show();
}
}
}
}
| rajmahesh/magento2-master | vendor/magento/magento2-base/lib/web/varien/form.js | JavaScript | gpl-3.0 | 13,470 |
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.provide("erpnext.company");
frappe.ui.form.on("Company", {
setup: function(frm) {
erpnext.company.setup_queries(frm);
frm.set_query("hra_component", function(){
return {
filters: {"type": "Earning"}
}
});
frm.set_query("arrear_component", function(){
return {
filters: {"is_additional_component": 1}
}
});
},
company_name: function(frm) {
if(frm.doc.__islocal) {
let parts = frm.doc.company_name.split();
let abbr = $.map(parts, function (p) {
return p? p.substr(0, 1) : null;
}).join("");
frm.set_value("abbr", abbr);
}
},
date_of_commencement: function(frm) {
if(frm.doc.date_of_commencement<frm.doc.date_of_incorporation)
{
frappe.throw(__("Date of Commencement should be greater than Date of Incorporation"));
}
if(!frm.doc.date_of_commencement){
frm.doc.date_of_incorporation = ""
}
},
refresh: function(frm) {
if(frm.doc.abbr && !frm.doc.__islocal) {
frm.set_df_property("abbr", "read_only", 1);
}
frm.toggle_display('address_html', !frm.doc.__islocal);
if(!frm.doc.__islocal) {
frappe.contacts.render_address_and_contact(frm);
frappe.dynamic_link = {doc: frm.doc, fieldname: 'name', doctype: 'Company'}
frm.toggle_enable("default_currency", (frm.doc.__onload &&
!frm.doc.__onload.transactions_exist));
frm.add_custom_button(__('Make Tax Template'), function() {
frm.trigger("make_default_tax_template");
});
frm.add_custom_button(__('Cost Centers'), function() {
frappe.set_route('Tree', 'Cost Center', {'company': frm.doc.name})
}, __("View"));
frm.add_custom_button(__('Chart of Accounts'), function() {
frappe.set_route('Tree', 'Account', {'company': frm.doc.name})
}, __("View"));
frm.add_custom_button(__('Sales Tax Template'), function() {
frappe.set_route('List', 'Sales Taxes and Charges Template', {'company': frm.doc.name});
}, __("View"));
frm.add_custom_button(__('Purchase Tax Template'), function() {
frappe.set_route('List', 'Purchase Taxes and Charges Template', {'company': frm.doc.name});
}, __("View"));
frm.add_custom_button(__('Default Tax Template'), function() {
frm.trigger("make_default_tax_template");
}, __("Make"));
}
erpnext.company.set_chart_of_accounts_options(frm.doc);
},
make_default_tax_template: function(frm) {
frm.call({
method: "create_default_tax_template",
doc: frm.doc,
freeze: true,
callback: function() {
frappe.msgprint(__("Default tax templates for sales and purchase are created."));
}
})
},
onload_post_render: function(frm) {
if(frm.get_field("delete_company_transactions").$input)
frm.get_field("delete_company_transactions").$input.addClass("btn-danger");
},
country: function(frm) {
erpnext.company.set_chart_of_accounts_options(frm.doc);
},
delete_company_transactions: function(frm) {
frappe.verify_password(function() {
var d = frappe.prompt({
fieldtype:"Data",
fieldname: "company_name",
label: __("Please re-type company name to confirm"),
reqd: 1,
description: __("Please make sure you really want to delete all the transactions for this company. Your master data will remain as it is. This action cannot be undone.")
},
function(data) {
if(data.company_name !== frm.doc.name) {
frappe.msgprint(__("Company name not same"));
return;
}
frappe.call({
method: "erpnext.setup.doctype.company.delete_company_transactions.delete_company_transactions",
args: {
company_name: data.company_name
},
freeze: true,
callback: function(r, rt) {
if(!r.exc)
frappe.msgprint(__("Successfully deleted all transactions related to this company!"));
},
onerror: function() {
frappe.msgprint(__("Wrong Password"));
}
});
},
__("Delete all the Transactions for this Company"), __("Delete")
);
d.get_primary_btn().addClass("btn-danger");
});
}
});
erpnext.company.set_chart_of_accounts_options = function(doc) {
var selected_value = doc.chart_of_accounts;
if(doc.country) {
return frappe.call({
method: "erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts.get_charts_for_country",
args: {
"country": doc.country,
"with_standard": true
},
callback: function(r) {
if(!r.exc) {
set_field_options("chart_of_accounts", [""].concat(r.message).join("\n"));
if(in_list(r.message, selected_value))
cur_frm.set_value("chart_of_accounts", selected_value);
}
}
})
}
}
cur_frm.cscript.change_abbr = function() {
var dialog = new frappe.ui.Dialog({
title: "Replace Abbr",
fields: [
{"fieldtype": "Data", "label": "New Abbreviation", "fieldname": "new_abbr",
"reqd": 1 },
{"fieldtype": "Button", "label": "Update", "fieldname": "update"},
]
});
dialog.fields_dict.update.$input.click(function() {
var args = dialog.get_values();
if(!args) return;
frappe.show_alert(__("Update in progress. It might take a while."));
return frappe.call({
method: "erpnext.setup.doctype.company.company.enqueue_replace_abbr",
args: {
"company": cur_frm.doc.name,
"old": cur_frm.doc.abbr,
"new": args.new_abbr
},
callback: function(r) {
if(r.exc) {
frappe.msgprint(__("There were errors."));
return;
} else {
cur_frm.set_value("abbr", args.new_abbr);
}
dialog.hide();
cur_frm.refresh();
},
btn: this
})
});
dialog.show();
}
erpnext.company.setup_queries = function(frm) {
$.each([
["default_bank_account", {"account_type": "Bank"}],
["default_cash_account", {"account_type": "Cash"}],
["default_receivable_account", {"account_type": "Receivable"}],
["default_payable_account", {"account_type": "Payable"}],
["default_expense_account", {"root_type": "Expense"}],
["default_income_account", {"root_type": "Income"}],
["default_payroll_payable_account", {"root_type": "Liability"}],
["round_off_account", {"root_type": "Expense"}],
["write_off_account", {"root_type": "Expense"}],
["exchange_gain_loss_account", {"root_type": "Expense"}],
["unrealized_exchange_gain_loss_account", {"root_type": "Expense"}],
["accumulated_depreciation_account",
{"root_type": "Asset", "account_type": "Accumulated Depreciation"}],
["depreciation_expense_account", {"root_type": "Expense", "account_type": "Depreciation"}],
["disposal_account", {"report_type": "Profit and Loss"}],
["default_inventory_account", {"account_type": "Stock"}],
["cost_center", {}],
["round_off_cost_center", {}],
["depreciation_cost_center", {}],
["default_employee_advance_account", {"root_type": "Asset"}],
["expenses_included_in_asset_valuation", {"account_type": "Expenses Included In Asset Valuation"}],
["capital_work_in_progress_account", {"account_type": "Capital Work in Progress"}],
["asset_received_but_not_billed", {"account_type": "Asset Received But Not Billed"}]
], function(i, v) {
erpnext.company.set_custom_query(frm, v);
});
if (frm.doc.enable_perpetual_inventory) {
$.each([
["stock_adjustment_account",
{"root_type": "Expense", "account_type": "Stock Adjustment"}],
["expenses_included_in_valuation",
{"root_type": "Expense", "account_type": "Expenses Included in Valuation"}],
["stock_received_but_not_billed",
{"root_type": "Liability", "account_type": "Stock Received But Not Billed"}]
], function(i, v) {
erpnext.company.set_custom_query(frm, v);
});
}
}
erpnext.company.set_custom_query = function(frm, v) {
var filters = {
"company": frm.doc.name,
"is_group": 0
};
for (var key in v[1]) {
filters[key] = v[1][key];
}
frm.set_query(v[0], function() {
return {
filters: filters
}
});
}
| ESS-LLP/erpnext-medical | erpnext/setup/doctype/company/company.js | JavaScript | gpl-3.0 | 7,846 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: GPL 3.0
*
* The contents of this file are subject to the General Public License
* 3.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.gnu.org/licenses/gpl.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Author: Michel Verbraak (info@1st-setup.nl)
* Website: http://www.1st-setup.nl/
*
* This interface/service is used for loadBalancing Request to Exchange
*
* ***** BEGIN LICENSE BLOCK *****/
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
var Cr = Components.results;
var components = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
function mivExchangeAccountManager() {
this.prefs = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService)
.getBranch("extensions.exchangeWebServices.accounts."),
this.globalFunctions = Cc["@1st-setup.nl/global/functions;1"]
.getService(Ci.mivFunctions);
}
var mivExchangeAccountManagerGUID = "41397c22-bcea-4e98-a562-2f5f435c6111";
mivExchangeAccountManager.prototype = {
// methods from nsISupport
/* void QueryInterface(
in nsIIDRef uuid,
[iid_is(uuid),retval] out nsQIResult result
); */
QueryInterface: XPCOMUtils.generateQI([Ci.mivExchangeAccountManager,
Ci.nsISupports]),
// Attributes from nsIClassInfo
classDescription: "Exchange Account Manager.",
classID: components.ID("{"+mivExchangeAccountManagerGUID+"}"),
contractID: "@1st-setup.nl/exchange/accountmanager;1",
flags: Ci.nsIClassInfo.SINGLETON || Ci.nsIClassInfo.THREADSAFE,
implementationLanguage: Ci.nsIProgrammingLanguage.JAVASCRIPT,
// External methods
getAccountIds: function _getAccountIds()
{
var ids = this.globalFunctions.safeGetCharPref(this.prefs, "ids", "");
this.logInfo("ids:"+ids);
return ids.split(",");
},
getAccounts: function _getAccounts()
{
var result = {};
var ids = this.getAccountIds()
for each(var id in ids) {
if (id != "") {
this.logInfo("id:"+id);
var tmpResult = this.getAccountById(id);
if (tmpResult.result) {
result[id] = tmpResult.account;
}
}
}
return result;
},
getAccountById: function _getAccountById(aId)
{
var result = false;
var account = {};
this.logInfo("id:"+aId);
var children = this.prefs.getChildList(aId+".",{});
if (children.length > 0) {
result = true;
account["id"] = aId;
for (var index in children) {
var attribute = children[index].substr(children[index].indexOf(".")+1);
switch (this.prefs.getPrefType(children[index])) {
case this.prefs.PREF_STRING:
account[attribute] = { type: "string", value: this.prefs.getCharPref(children[index])};
break;
case this.prefs.PREF_INT:
account[attribute] = { type: "int", value: this.prefs.getIntPref(children[index])};
break;
case this.prefs.PREF_BOOL:
account[attribute] = { type: "bool", value: this.prefs.getBoolPref(children[index])};
break;
}
}
}
return { result:result, account: account };
},
getAccountByServer: function _getAccountByServer(aServer)
{
var accounts = this.getAccounts();
for each(var account in accounts) {
if ((account.server) && (account.server.value) && (account.server.value.toLowerCase() == aServer.toLowerCase())) {
return account;
}
}
return null;
},
saveAccount: function _saveAccount(aAccount)
{
for (var index in aAccount) {
if (index != "id") {
switch (aAccount[index].type) {
case "string":
this.prefs.setCharPref(aAccount.id+"."+index, aAccount[index].value);
break;
case "int":
this.prefs.setIntPref(aAccount.id+"."+index, aAccount[index].value);
break;
case "bool":
this.prefs.setBoolPref(aAccount.id+"."+index, aAccount[index].value);
break;
default:
this.logInfo("Unknown preference index:"+index+", value:"+aAccount[index].value+", type:"+aAccount[index].type);
}
}
}
// Check if the ids all ready exists. If not add it.
var ids = this.getAccountIds();
var idExists = false;
for (var index in ids) {
if (ids[index] == aAccount.id) {
idExists = true;
break;
}
}
if (!idExists) {
ids.push(aAccount.id);
ids = ids.join(",");
this.prefs.setCharPref("ids", ids);
}
},
removeAccount: function _removeAccount(aAccount)
{
if (aAccount.id) {
this.removeAccountById(aAccount.id);
}
},
removeAccountById: function _removeAccountById(aAccountId)
{
this.prefs.deleteBranch(aAccountId);
// Remove from ids list.
var oldIds = this.getAccountIds();
var newIds = [];
for (var index in oldIds) {
if (oldIds[index] != aAccountId) {
newIds.push(oldIds[index]);
}
}
if (newIds.length > 0) {
newIds = newIds.join(",");
}
else {
newIds = "";
}
this.prefs.setCharPref("ids", newIds);
},
// Internal methods
logInfo: function _logInfo(aMsg, aDebugLevel)
{
return;
if (!aDebugLevel) aDebugLevel = 1;
var prefB = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefBranch);
this.debugLevel = this.globalFunctions.safeGetBoolPref(prefB, "extensions.1st-setup.accounts.debuglevel", 0, true);
if (aDebugLevel <= this.debugLevel) {
this.globalFunctions.LOG("mivExchangeAccountManager: "+aMsg);
}
},
}
function NSGetFactory(cid) {
try {
if (!NSGetFactory.mivExchangeAccountManager) {
// Load main script from lightning that we need.
NSGetFactory.mivExchangeAccountManager = XPCOMUtils.generateNSGetFactory([mivExchangeAccountManager]);
}
} catch(e) {
Components.utils.reportError(e);
dump(e);
throw e;
}
return NSGetFactory.mivExchangeAccountManager(cid);
}
| o5carmartinezm/exchangecalendar | interfaces/exchangeAccountManager/mivExchangeAccountManager.js | JavaScript | gpl-3.0 | 5,997 |
import Mixin from '@ember/object/mixin';
import minimizeModel from 'consul-ui/utils/minimizeModel';
export default Mixin.create({
// TODO: what about update and create?
respondForQueryRecord: function(respond, query) {
return this._super(function(cb) {
return respond((headers, body) => {
body.Roles = typeof body.Roles === 'undefined' || body.Roles === null ? [] : body.Roles;
return cb(headers, body);
});
}, query);
},
respondForQuery: function(respond, query) {
return this._super(function(cb) {
return respond(function(headers, body) {
return cb(
headers,
body.map(function(item) {
item.Roles = typeof item.Roles === 'undefined' || item.Roles === null ? [] : item.Roles;
return item;
})
);
});
}, query);
},
serialize: function(snapshot, options) {
const data = this._super(...arguments);
data.Roles = minimizeModel(data.Roles);
return data;
},
});
| hashicorp/consul | ui/packages/consul-ui/app/mixins/role/as-many.js | JavaScript | mpl-2.0 | 1,008 |
odoo.define('mail/static/src/components/drop_zone/drop_zone.js', function (require) {
'use strict';
const useShouldUpdateBasedOnProps = require('mail/static/src/component_hooks/use_should_update_based_on_props/use_should_update_based_on_props.js');
const { Component, useState } = owl;
class DropZone extends Component {
/**
* @override
*/
constructor(...args) {
super(...args);
useShouldUpdateBasedOnProps();
this.state = useState({
/**
* Determine whether the user is dragging files over the dropzone.
* Useful to provide visual feedback in that case.
*/
isDraggingInside: false,
});
/**
* Counts how many drag enter/leave happened on self and children. This
* ensures the drop effect stays active when dragging over a child.
*/
this._dragCount = 0;
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* Returns whether the given node is self or a children of self.
*
* @param {Node} node
* @returns {boolean}
*/
contains(node) {
return this.el.contains(node);
}
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Making sure that dragging content is external files.
* Ignoring other content dragging like text.
*
* @private
* @param {DataTransfer} dataTransfer
* @returns {boolean}
*/
_isDragSourceExternalFile(dataTransfer) {
const dragDataType = dataTransfer.types;
if (dragDataType.constructor === window.DOMStringList) {
return dragDataType.contains('Files');
}
if (dragDataType.constructor === Array) {
return dragDataType.includes('Files');
}
return false;
}
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* Shows a visual drop effect when dragging inside the dropzone.
*
* @private
* @param {DragEvent} ev
*/
_onDragenter(ev) {
ev.preventDefault();
if (this._dragCount === 0) {
this.state.isDraggingInside = true;
}
this._dragCount++;
}
/**
* Hides the visual drop effect when dragging outside the dropzone.
*
* @private
* @param {DragEvent} ev
*/
_onDragleave(ev) {
this._dragCount--;
if (this._dragCount === 0) {
this.state.isDraggingInside = false;
}
}
/**
* Prevents default (from the template) in order to receive the drop event.
* The drop effect cursor works only when set on dragover.
*
* @private
* @param {DragEvent} ev
*/
_onDragover(ev) {
ev.preventDefault();
ev.dataTransfer.dropEffect = 'copy';
}
/**
* Triggers the `o-dropzone-files-dropped` event when new files are dropped
* on the dropzone, and then removes the visual drop effect.
*
* The parents should handle this event to process the files as they wish,
* such as uploading them.
*
* @private
* @param {DragEvent} ev
*/
_onDrop(ev) {
ev.preventDefault();
if (this._isDragSourceExternalFile(ev.dataTransfer)) {
this.trigger('o-dropzone-files-dropped', {
files: ev.dataTransfer.files,
});
}
this.state.isDraggingInside = false;
}
}
Object.assign(DropZone, {
props: {},
template: 'mail.DropZone',
});
return DropZone;
});
| rven/odoo | addons/mail/static/src/components/drop_zone/drop_zone.js | JavaScript | agpl-3.0 | 3,888 |
/*
* eyeos - The Open Source Cloud's Web Desktop
* Version 2.0
* Copyright (C) 2007 - 2010 eyeos Team
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation.
*
* 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.
*
* You should have received a copy of the GNU Affero General Public License
* version 3 along with this program in the file "LICENSE". If not, see
* <http://www.gnu.org/licenses/agpl-3.0.txt>.
*
* See www.eyeos.org for more details. All requests should be sent to licensing@eyeos.org
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* eyeos" logo and retain the original copyright notice. If the display of the
* logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices
* must display the words "Powered by eyeos" and retain the original copyright notice.
*/
/**
* This is the Item for Groups when the Groups Tab is selected
* and context = ADD
*/
qx.Class.define('eyeos.ui.tabs.GroupAdd', {
extend: eyeos.ui.tabs.Item,
statics : {
PRIVACY_OPEN: 0,
PRIVACY_ONREQUEST: 1,
PRIVACY_ONINVITATION: 2
},
properties: {
id: {
check: 'String'
},
tags: {
init: new Array()
},
privacy: {
check: [0, 1, 2],
init: 0
},
role: {
},
status: {
},
descriptionText: {
check: 'String'
}
},
construct: function (name, description, id, status, role, privacy, tags, page) {
this.base(arguments);
this.setPage(page);
if (description != null) {
this.setDescriptionText(description);
} else {
this.setDescriptionText('This workgroup has no description');
}
this.setStatus(status);
this.setPrivacy(privacy);
this.setName(name);
this.setNameTooltip(name);
this.setId(id);
this.setRole(role);
this.setImage('index.php?checknum=' + page.getChecknum() + '&message=__Workgroups_getWorkgroupPicture¶ms[workgroupId]=' + id);
if (tags != null) {
this.setTags(tags);
}
this.addListeners();
this._updateLayout();
},
members: {
_imagePlus: 'index.php?extern=images/new.png',
_imageAdded: 'index.php?extern=images/22x22/actions/dialog-ok-apply.png',
_imageDelete: 'index.php?extern=/images/16x16/actions/list-remove.png',
_imageJoin: 'index.php?extern=/images/16x16/actions/list-add.png',
_imagePending: 'index.php?extern=/images/user-away.png',
addListeners: function() {
var bus = eyeos.messageBus.getInstance();
bus.addListener('eyeos_NSGroup_userWorkgroupAssignationCreated', function () {
this.destroy();
}, this);
},
_updateLayout: function () {
switch (this.getStatus()) {
case eyeos.ui.tabs.GroupAll.STATUS_NOT_MEMBER:
this._showAsToAdd();
break;
case eyeos.ui.tabs.GroupAll.STATUS_MEMBER:
this._showAsMember();
break;
case eyeos.ui.tabs.GroupAll.STATUS_PENDING:
this._showAsPending();
break;
}
},
_showAsToAdd: function () {
this.setImageCommand(this._imagePlus);
this.setImageCommandFunction(this._joinGroup);
this.showAsNormal();
this.setDescription(this._createDescriptionText());
this.setDescriptionTooltip(this._createDescriptionText());
this.setDescriptionImage(this._updateDescriptionImage());
this.cleanContentListener();
this.cleanMenu();
/*
* Create the Menu in CommandBox
*/
var addMenu = new qx.ui.menu.Button('Join this group', this._imageJoin).set({
'backgroundColor': '#ffffff'
});
addMenu.addListener('execute', function(e) {
this._joinGroup();
}, this);
this.addToMenu(addMenu);
},
_showAsMember: function () {
this.setImageCommand(this._imagePlus)
this.showAsAdded(this._imageAdded);
this.setImageCommandFunction(this._functionNull);
this.setDescription(this._createDescriptionText());
this.setDescriptionTooltip(this._createDescriptionText());
this.setDescriptionImage(this._updateDescriptionImage());
this.cleanContentListener();
this.getContent().addListener('click', this._openShare, this);
this.cleanMenu();
var delMenu = new qx.ui.menu.Button('Leave/remove this workgroup', this._imageDelete).set({
backgroundColor: '#ffffff'
});
delMenu.addListener('execute', this._removeGroup, this);
this.addToMenu(delMenu);
},
_openShare: function () {
eyeos.execute('files', this.getPage().getChecknum(), ['workgroup://~' + this.getName()], null);
document.eyeDesktopTabs.hideContent();
},
_showAsPending: function () {
this.setImageCommand(this._imagePlus);
this.showAsAdded(this._imagePending);
this.setImageCommandFunction(this._functionNull);
this.setDescription(this._createDescriptionText());
this.setDescriptionTooltip(this._createDescriptionText());
this.setDescriptionImage(this._updateDescriptionImage());
this.cleanContentListener();
this.cleanMenu();
var delMenu = new qx.ui.menu.Button('Leave/remove this workgroup', this._imageDelete).set({
'backgroundColor': '#ffffff'
});
delMenu.addListener('execute', this._removeGroup, this);
this.addToMenu(delMenu);
},
/**
*Action executed when a user press the delete/remove Button
*/
_removeGroup: function () {
if (this.getRole() == eyeos.ui.tabs.GroupAll.ROLE_OWNER) {
this._deleteGroup();
} else {
this._leaveGroup();
}
},
/**
*Action executed when an Owner of a workgroup want to delete it
*/
_deleteGroup: function () {
var op = new eyeos.dialogs.OptionPane(
'Are you sure you want to delete this workgroup?',
eyeos.dialogs.OptionPane.QUESTION_MESSAGE,
eyeos.dialogs.OptionPane.YES_NO_OPTION);
op.createDialog(
null,
'Delete workgroup',
function (answer) {
if (answer == eyeos.dialogs.OptionPane.YES_OPTION) {
eyeos.callMessage(this.getPage().getChecknum(), '__Workgroups_deleteWorkgroup', {workgroupId: this.getId()}, function () {
var bus = eyeos.messageBus.getInstance();
bus.send('workgroup', 'deleteGroup', this.getId());
this.destroy();
}, this);
}
},
this, true
).open();
},
/**
*Action executed when someone want to leave the Group
*/
_leaveGroup: function () {
eyeos.callMessage(this.getPage().getChecknum(), 'getCurrentUserId', null, function (myId) {
var params = {
workgroupId: this.getId(),
userIds: [myId]
};
var op = new eyeos.dialogs.OptionPane(
'Are you sure you want to leave this workgroup?',
eyeos.dialogs.OptionPane.QUESTION_MESSAGE,
eyeos.dialogs.OptionPane.YES_NO_OPTION);
op.createDialog(null, 'Leave workgroup', function (answer) {
if (answer == eyeos.dialogs.OptionPane.YES_OPTION) {
eyeos.callMessage(this.getPage().getChecknum(), '__Workgroups_deleteMemberships', params, function (groups) {
this.setStatus(eyeos.ui.tabs.GroupAll.STATUS_NOT_MEMBER);
this._updateLayout();
var bus = eyeos.messageBus.getInstance();
bus.send('workgroup', 'leaveGroup', this.getId());
}, this);
}
},
this, true
).open();
}, this);
},
/**
* Add the Groups to the user Groups
*/
_joinGroup: function () {
var op = new eyeos.dialogs.OptionPane(
'Are you sure you want to join this workgroup?',
eyeos.dialogs.OptionPane.QUESTION_MESSAGE,
eyeos.dialogs.OptionPane.YES_NO_OPTION);
op.createDialog(
null,
'Join workgroup',
function (answer) {
if (answer == eyeos.dialogs.OptionPane.YES_OPTION) {
var params = {
workgroupId: this.getId()
};
eyeos.callMessage(this.getPage().getChecknum(), '__Workgroups_requestMembership', params, function (result) {
if (this.getPrivacy() == eyeos.ui.tabs.GroupAll.PRIVACY_OPEN){
this.setStatus(eyeos.ui.tabs.GroupAll.STATUS_MEMBER);
this.setRole(eyeos.ui.tabs.GroupAll.ROLE_VIEWER);
} else {
this.setStatus(eyeos.ui.tabs.GroupAll.STATUS_PENDING);
}
this._updateLayout();
var bus = eyeos.messageBus.getInstance();
bus.send('workgroup', 'joinGroup', [this.getName(), this.getId()]);
}, this);
}
},
this, true
).open();
},
/**
* Function for set name properties (Override)
*/
_applyName: function (newValue, oldValue) {
var myPrivacy;
switch (this.getPrivacy()) {
case eyeos.ui.tabs.GroupAll.PRIVACY_OPEN:
myPrivacy = '<span style="color: green; font-size: 12px">(open)</span>';
break;
case eyeos.ui.tabs.GroupAll.PRIVACY_ONREQUEST:
myPrivacy = '<span style="color: green; font-size: 12px">(via request)</span>';
break;
}
var value = '<b>' + newValue + '</b> ' + myPrivacy;
this._nameLabel.setValue(value);
},
_createDescriptionText: function () {
if (this.getStatus() == eyeos.ui.tabs.GroupAll.STATUS_NOT_MEMBER) {
return this.getDescriptionText();
} else if (this.getStatus() == eyeos.ui.tabs.GroupAll.STATUS_MEMBER){
switch (this.getRole()) {
case eyeos.ui.tabs.GroupAll.ROLE_VIEWER:
return 'Viewer';
break;
case eyeos.ui.tabs.GroupAll.ROLE_EDITOR:
return 'Editor';
break;
case eyeos.ui.tabs.GroupAll.ROLE_ADMIN:
return 'Admin';
break;
case eyeos.ui.tabs.GroupAll.ROLE_OWNER:
return 'Owner';
break;
}
} else if (this.getStatus() == eyeos.ui.tabs.GroupAll.STATUS_PENDING) {
return 'Pending';
}
},
_updateDescriptionImage: function () {
if (this.getRole() == eyeos.ui.tabs.GroupAll.ROLE_OWNER) {
return 'index.php?extern=/images/rate_on.png';
} else {
return '';
}
},
_functionNull: function () {
//Increase your Karma
}
}
});
| cloudspaces/eyeos-u1db | eyeos/extern/js/eyeos/ui/tabs/GroupAdd.js | JavaScript | agpl-3.0 | 10,327 |
// override saveSheet on jQuery.sheet for tiki specific export
menuRight = $(
($("#sheetTools").html() + "")
.replace(/sheetInstance/g, "$.sheet.instance[" + $.sheet.I() + "]")
);
menuRight.find(".qt-picker").attr("instance", $.sheet.I());
var jST = $.sheet.tikiSheet;
$.sheet = $.extend({
makeSmall: function() {
var jS = jST.getSheet();
if (jS.obj.fullScreen().is(':visible')) {
jS.toggleFullScreen();
}
},
view: function() {
var jS = jST.getSheet();
var url = "";
if (jST.id) {
url = "tiki-view_sheets.php?sheetId=" + jST.id;
} else {
url = "tiki-view_sheets.php?type=" + jST.type + "&file=" + jST.file;
}
document.location = url;
},
saveSheet: function( fn ) {
var jS = jST.getSheet();
$.sheet.makeSmall();
jS.evt.cellEditDone();
var sheetData = $.sheet.exportSheet(jS);
var url = "";
if (jST.id) {
url = "tiki-view_sheets.php?sheetId=" + jST.id;
} else {
url = "tiki-view_sheets.php?type=" + jST.type + "&file=" + jST.file;
}
jST.tikiModal(tr("Saving"));
$.post(url, {
s: $.toJSON(sheetData)
}, function(data) {
jS.setDirty(false);
if (fn) {
if($.isFunction(fn)) {
fn();
}
}
jST.tikiModal();
});
},
deleteSheet: function() {
var jS = jST.getSheet();
var id = jS.obj.sheet().data('id');
var type = jS.obj.sheet().data('type');
if (type == "tracker") {
$.post('tiki-view_sheets.php', {
sheetId: jST.id,
trackerId: id,
relate: 'remove'
}, function() {
jS.deleteSheet();
});
} else if (type == "file") {
$.post('tiki-view_sheets.php', {
sheetId: jST.id,
fileId: id,
relate: 'remove'
}, function() {
jS.deleteSheet();
});
} else if (type == "sheet") {
$.post('tiki-view_sheets.php', {
sheetId: jST.id,
childSheetId: id,
relate: 'remove'
}, function() {
jS.deleteSheet();
});
} else {
jS.deleteSheet();
}
},
exportSheet: function() {
var jS = jST.getSheet(),
tables = jS.tables(),
sheets = $.sheet.dts.fromTables.json(jS),
i;
var result = []; //documents
for (i in sheets) {
var table = $(tables[i]),
type = table.data('type'),
id = table.data("id"),
sheet = sheets[i];
if (type == "sheet" || !type) { //standard tiki sheet
sheet.id = id;
result.push(sheet); //append to documents
}
}
return result;
},
tikiOptions: {
buildSheet: true,
autoFiller: true,
menuRight: menuRight,
colMargin: 20, //beefed up colMargin because the default size was too small for font
minSize: {
rows: 1,
cols: 1
}
},
manageState: function(toggleEdit, parse) {
var jS = jST.getSheet();
parse = (parse ? parse : '');
var url = "";
if (jST.id) {
url = "tiki-view_sheets.php?sheetId=" + jST.id + "&sheetonly=y&parse=" + parse;
} else {
url = "tiki-view_sheets.php?type=" + jST.type + "&file=" + jST.file + "&sheetonly=y&parse=" + parse;
}
jS.saveSheet = function(){};
jST.tikiModal(tr("Updating"));
var i = jS.i;
jS.switchSpreadsheet(0);
$.get(url, function (o) {
if (!toggleEdit) {
jS.s.editable = !jS.s.editable;
}
jS.toggleState(o);
$.sheet.readyState();
jS.switchSpreadsheet(i);
jST.tikiModal();
});
},
readyState: function() {
var jS = jST.getSheet();
if (jS.s.editable) {
$("#jSheetControls").show();
$("#saveState").show();
$("#editState").hide();
} else {
$("#jSheetControls").hide();
$("#saveState").hide();
$("#editState").show();
}
},
dualFullScreenHelper: function(parent, reset) {
var container = $('#' + parent.attr('id') + '_fullscreen');
var sizeSet = false;
$($.sheet.instance).each(function(i) {
var jS = this;
var tikiSheet = jST.eq(i);
if (!reset) {
jS.sizeOriginal = {
height: tikiSheet.height(),
width: tikiSheet.width()
};
if (!container.length) {
container = $('<div style="left: 0px; top: 0px; z-index: 9999999;" data-parentid="" />')
.attr('id', parent.attr('id') + '_fullscreen')
.data('parentid', parent.attr('id'))
.css('position', 'fixed')
.addClass('ui-widget-content')
.width($(window).width())
.height($(window).height())
.html(parent.children())
.appendTo('body');
}
jS.s.width = $(window).width() / 2;
jS.s.height = $(window).height();
$('.sheet_sibling')
.add('.navbar')
.each(function() {
jS.s.height -= $(this).height();
});
} else {
if (parent.length) {
$('#' + parent.data('parentid')).html(parent.children());
parent.remove();
}
jS.s.width = jS.sizeOriginal.width;
jS.s.height = jS.sizeOriginal.height;
}
jS.sheetSyncSize();
});
},
setValuesForCompareSheet: function(value1, set1, value2, set2) {
value1 = (value1 ? ":eq(" + value1 + ")" : ":first");
value2 = (value2 ? ":eq(" + value2 + ")" : ":last");
$("input.compareSheet1").filter(value1).click();
$("input.compareSheet2").filter(value2).click();
this.compareSheetClick(set1, set2);
},
compareSheetClick: function(set1, set2) {
var checked1, checked2;
$(set1).each(function() {
if ($(this).is(':checked')) {
checked1 = $(this);
}
});
$(set2).each(function() {
if ($(this).is(':checked')) {
checked2 = $(this);
}
});
$(set1).removeAttr('disabled');
$(set2).removeAttr('disabled');
function disable(obj1, objIndex, obj2, after) {
for (var i = (after ? obj1.index(objIndex) : 0); i < (after ? obj1.length : obj1.index(objIndex) + 1); i++) {
obj2.eq(i).attr('disabled', 'true');
}
}
disable(set1, checked1, set2, true);
disable(set2, checked2, set1);
},
compareSheetsSubmitClick: function(o) {
var sheetId = $('#sheetId').val();
var sheetReadDates = 'idx_0=' + $('input.compareSheet1:checked').val() + '&idx_1=' + $('input.compareSheet2:checked').val() + '&';
window.location = "tiki-history_sheets.php?sheetId=" + sheetId + "&" + sheetReadDates;
return false;
},
link: {
setupUI: function() {
jST
.off("sheetSwitchSpreadsheet")
.on("sheetSwitchSpreadsheet", function(e, jS, i) {
if (i < 0) {
$.sheet.makeSmall();
var switchSheetMsg = $("div.switchSheet").first().clone();
var msg;
switchSheetMsg.find("input.newSpreadsheet").click(function() {
switchSheetMsg.dialog("close").remove();
jS.switchSpreadsheet(i);
});
switchSheetMsg.find("input.addSpreadsheet").click(function() {
switchSheetMsg.dialog("close").remove();
$.tikiModal(tr("Loading"));
msg = $("<div />").load("tiki-sheets.php #role_main .tabcontent:first table", function() {
$.tikiModal();
msg.dialog({
width: jST.width(),
height: jST.height(),
modal: true
});
msg.find("a.sheetLink").each(function() {
$(this).click(function() {
msg.dialog("close").remove();
$.sheet.link.make("spreadsheet", $(this).attr("sheetid"));
return false;
});
});
});
});
switchSheetMsg.find("input.addTracker").click(function() {
switchSheetMsg.dialog("close").remove();
$.tikiModal(tr("Loading"));
msg = $("<div />").load("tiki-list_trackers.php #role_main table", function() {
$.tikiModal();
var trackerList = $('<table><tr><td>' + tr('Id') + '</td><td>' + tr('Name') + '</td></tr></table>');
msg.find('td.id').each(function() {
var trackerId = $.trim($(this).text());
var trTrackerSelection = $('<tr><td>' + trackerId + '</td><td>' + $(this).next().text() + '</td></tr>')
.click(function() {
msg.dialog("close").remove();
$.sheet.link.make("tracker", trackerId);
})
.css('cursor', 'pointer');
trackerList.append(trTrackerSelection);
});
trackerList.dialog({
width: jST.width(),
height: jST.height(),
modal: true,
title: tr('Tracker')
});
});
});
switchSheetMsg.find("input.addFile").click(function() {
switchSheetMsg.dialog("close").remove();
$.tikiModal(tr("Loading"));
msg = $("<div />").load("tiki-list_file_gallery.php?find_fileType=csv #fgalform", function() {
$.tikiModal();
msg.dialog({
width: jST.width(),
height: jST.height(),
modal: true
});
msg.find("a.fileLink").each(function() {
$(this).click(function() {
msg.dialog("close").remove();
$.sheet.link.make("file", $(this).attr("fileId"));
return false;
});
});
});
});
switchSheetMsg
.dialog({
title: switchSheetMsg.attr("title"),
modal: true,
resizable: false
});
return false;
} else {
jS.switchSpreadsheet(i);
}
});
},
make: function(type, id) {
jST.tikiModal(tr('Updating'));
$.sheet.saveSheet(function() {
try {
switch (type) {
case "spreadsheet":
$.get("tiki-view_sheets.php", {
sheetId: jST.id,
childSheetId: id,
relate: "add"
}, function() {
$.sheet.manageState();
jST.tikiModal();
});
break;
case "file":
$.get("tiki-view_sheets.php", {
sheetId: jST.id,
fileId: id,
relate: "add"
}, function() {
$.sheet.manageState();
jST.tikiModal();
});
break;
case "tracker":
$.get("tiki-view_sheets.php", {
sheetId: jST.id,
trackerId: id,
relate: "add"
}, function() {
$.sheet.manageState();
jST.tikiModal();
});
break;
}
} catch(e) {}
});
return false;
}
}
}, $.sheet); | oregional/tiki | lib/sheet/grid.js | JavaScript | lgpl-2.1 | 9,937 |
define([
"./core",
"./common/runtime-bind",
"./common/validate/cldr",
"./common/validate/default-locale",
"./common/validate/parameter-presence",
"./common/validate/parameter-type/currency",
"./common/validate/parameter-type/number",
"./common/validate/parameter-type/plain-object",
"./currency/code-properties",
"./currency/formatter-fn",
"./currency/name-properties",
"./currency/symbol-properties",
"./util/object/omit",
"./number",
"cldr/event",
"cldr/supplemental"
], function( Globalize, runtimeBind, validateCldr, validateDefaultLocale, validateParameterPresence,
validateParameterTypeCurrency, validateParameterTypeNumber, validateParameterTypePlainObject,
currencyCodeProperties, currencyFormatterFn, currencyNameProperties, currencySymbolProperties,
objectOmit ) {
function validateRequiredCldr( path, value ) {
validateCldr( path, value, {
skip: [ /supplemental\/currencyData\/fractions\/[A-Za-z]{3}$/ ]
});
}
/**
* .currencyFormatter( currency [, options] )
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object]:
* - style: [String] "symbol" (default), "accounting", "code" or "name".
* - see also number/format options.
*
* Return a function that formats a currency according to the given options and default/instance
* locale.
*/
Globalize.currencyFormatter =
Globalize.prototype.currencyFormatter = function( currency, options ) {
var args, cldr, numberFormatter, pluralGenerator, properties, returnFn, style;
validateParameterPresence( currency, "currency" );
validateParameterTypeCurrency( currency, "currency" );
validateParameterTypePlainObject( options, "options" );
cldr = this.cldr;
options = options || {};
args = [ currency, options ];
style = options.style || "symbol";
validateDefaultLocale( cldr );
// Get properties given style ("symbol" default, "code" or "name").
cldr.on( "get", validateRequiredCldr );
properties = ({
accounting: currencySymbolProperties,
code: currencyCodeProperties,
name: currencyNameProperties,
symbol: currencySymbolProperties
}[ style ] )( currency, cldr, options );
cldr.off( "get", validateRequiredCldr );
// options = options minus style, plus raw pattern.
options = objectOmit( options, "style" );
options.raw = properties.pattern;
// Return formatter when style is "symbol" or "accounting".
if ( style === "symbol" || style === "accounting" ) {
numberFormatter = this.numberFormatter( options );
returnFn = currencyFormatterFn( numberFormatter );
runtimeBind( args, cldr, returnFn, [ numberFormatter ] );
// Return formatter when style is "code" or "name".
} else {
numberFormatter = this.numberFormatter( options );
pluralGenerator = this.pluralGenerator();
returnFn = currencyFormatterFn( numberFormatter, pluralGenerator, properties );
runtimeBind( args, cldr, returnFn, [ numberFormatter, pluralGenerator, properties ] );
}
return returnFn;
};
/**
* .currencyParser( currency [, options] )
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object] see currencyFormatter.
*
* Return the currency parser according to the given options and the default/instance locale.
*/
Globalize.currencyParser =
Globalize.prototype.currencyParser = function( /* currency, options */ ) {
// TODO implement parser.
};
/**
* .formatCurrency( value, currency [, options] )
*
* @value [Number] number to be formatted.
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object] see currencyFormatter.
*
* Format a currency according to the given options and the default/instance locale.
*/
Globalize.formatCurrency =
Globalize.prototype.formatCurrency = function( value, currency, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return this.currencyFormatter( currency, options )( value );
};
/**
* .parseCurrency( value, currency [, options] )
*
* @value [String]
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object]: See currencyFormatter.
*
* Return the parsed currency or NaN when value is invalid.
*/
Globalize.parseCurrency =
Globalize.prototype.parseCurrency = function( /* value, currency, options */ ) {
};
return Globalize;
});
| has191210/bdademo | src/main/resources/public/bower_components/globalize/src/currency.js | JavaScript | unlicense | 4,316 |
import $ from 'jquery';
import PublicationModel from '../../../../scripts/manager/models/PublicationModel';
import GeospatialView from '../../../../scripts/manager/views/GeospatialView';
describe('GeospatialView', function() {
var testView, testModel;
beforeEach(function() {
$('body').append('<div id="test-div"></div>');
testModel = new PublicationModel();
testView = new GeospatialView({
el : '#test-div',
model : testModel
});
testView.render();
});
afterEach(function() {
testView.remove();
$('#test-div').remove();
});
it('Expects that changes to the DOM inputs are reflected in the model', function() {
testView.$('#country-input').val('Country').trigger('change');
expect(testModel.get('country')).toEqual('Country');
testView.$('#state-input').val('State').trigger('change');
expect(testModel.get('state')).toEqual('State');
testView.$('#county-input').val('County').trigger('change');
expect(testModel.get('county')).toEqual('County');
testView.$('#city-input').val('City').trigger('change');
expect(testModel.get('city')).toEqual('City');
testView.$('#otherGeospatial-input').val('Other Geospatial').trigger('change');
expect(testModel.get('otherGeospatial')).toEqual('Other Geospatial');
testView.$('#geographicExtents-input').val('Geo Extents').trigger('change');
expect(testModel.get('geographicExtents')).toEqual('Geo Extents');
});
it('Expects that changes to the model properties are reflected in the DOM inputs', function() {
testModel.set('country', 'Country');
expect(testView.$('#country-input').val()).toEqual('Country');
testModel.set('state', 'State');
expect(testView.$('#state-input').val()).toEqual('State');
testModel.set('county', 'County');
expect(testView.$('#county-input').val()).toEqual('County');
testModel.set('city', 'City');
expect(testView.$('#city-input').val()).toEqual('City');
testModel.set('otherGeospatial', 'Other Geospatial');
expect(testView.$('#otherGeospatial-input').val()).toEqual('Other Geospatial');
testModel.set('geographicExtents', 'Geo Extents');
expect(testView.$('#geographicExtents-input').val()).toEqual('Geo Extents');
});
});
| ayan-usgs/PubsWarehouse_UI | assets/tests/js/manager/views/GeospatialViewSpec.js | JavaScript | unlicense | 2,406 |
({
insertEntity: "Vložiť symbol"
})
| sulistionoadi/belajar-springmvc-dojo | training-web/src/main/webapp/js/dojotoolkit/dojox/editor/plugins/nls/sk/InsertEntity.js | JavaScript | apache-2.0 | 40 |
//>>built
define(
"dojox/grid/enhanced/nls/ru/Pagination", //begin v1.x content
({
"descTemplate": "${2} - ${3} из ${1} ${0}",
"firstTip": "Первая страница",
"lastTip": "Последняя страница",
"nextTip": "Следующая страница",
"prevTip": "Предыдущая страница",
"itemTitle": "элементов",
"singularItemTitle": "элемент",
"pageStepLabelTemplate": "Страница ${0}",
"pageSizeLabelTemplate": "${0} элементов на странице",
"allItemsLabelTemplate": "Все элементы",
"gotoButtonTitle": "Перейти на определенную страницу",
"dialogTitle": "Перейти на страницу",
"dialogIndication": "Задайте номер страницы",
"pageCountIndication": " (${0} страниц)",
"dialogConfirm": "Перейти",
"dialogCancel": "Отмена",
"all": "все"
})
//end v1.x content
);
| cfxram/grails-dojo | web-app/js/dojo/1.7.2/dojox/grid/enhanced/nls/ru/Pagination.js | JavaScript | apache-2.0 | 956 |
/*!
* ${copyright}
*/
// Provides default renderer for control sap.ui.commons.FileUploader
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Renderer', 'sap/ui/unified/FileUploaderRenderer'],
function(jQuery, Renderer, FileUploaderRenderer1) {
"use strict";
var FileUploaderRenderer = Renderer.extend(FileUploaderRenderer1);
return FileUploaderRenderer;
}, /* bExport= */ true);
| SQCLabs/openui5 | src/sap.ui.commons/src/sap/ui/commons/FileUploaderRenderer.js | JavaScript | apache-2.0 | 389 |
var assert = require('assert'),
error = require('../../../lib/error/index'),
math = require('../../../index'),
bignumber = math.bignumber;
describe('diag', function() {
it('should return a diagonal matrix on the default diagonal', function() {
assert.deepEqual(math.diag([1,2,3]), [[1,0,0],[0,2,0],[0,0,3]]);
assert.deepEqual(math.diag([[1,2,3],[4,5,6]]), [1,5]);
});
it('should return a diagonal matrix on the default diagonal, dense matrix', function() {
assert.deepEqual(math.diag([1,2,3], 'dense'), math.matrix([[1,0,0],[0,2,0],[0,0,3]], 'dense'));
assert.deepEqual(math.diag(math.matrix([[1,2,3],[4,5,6]], 'dense')), math.matrix([1,5], 'dense'));
});
it('should return a diagonal matrix on the default diagonal, ccs matrix', function() {
assert.deepEqual(math.diag([1,2,3], 'ccs'), math.matrix([[1,0,0],[0,2,0],[0,0,3]], 'ccs'));
assert.deepEqual(math.diag(math.matrix([[1,2,3],[4,5,6]], 'ccs')), math.matrix([1,5], 'ccs'));
});
it('should return a diagonal matrix on the default diagonal, crs matrix', function() {
assert.deepEqual(math.diag([1,2,3], 'crs'), math.matrix([[1,0,0],[0,2,0],[0,0,3]], 'crs'));
assert.deepEqual(math.diag(math.matrix([[1,2,3],[4,5,6]], 'crs')), math.matrix([1,5], 'crs'));
});
it('should return a array output on array input', function() {
assert.deepEqual(math.diag([1,2]), [[1,0],[0,2]]);
});
it('should return a matrix output on matrix input', function() {
assert.deepEqual(math.diag(math.matrix([1,2])), math.matrix([[1,0],[0,2]]));
assert.deepEqual(math.diag(math.matrix([[1,2], [3,4]])), math.matrix([1,4]));
});
it('should put vector on given diagonal k in returned matrix', function() {
assert.deepEqual(math.diag([1,2,3], 1), [[0,1,0,0],[0,0,2,0],[0,0,0,3]]);
assert.deepEqual(math.diag([1,2,3], -1), [[0,0,0],[1,0,0],[0,2,0],[0,0,3]]);
});
it('should return diagonal k from a matrix', function() {
assert.deepEqual(math.diag([[1,2,3],[4,5,6]], 1), [2,6]);
assert.deepEqual(math.diag([[1,2,3],[4,5,6]],-1), [4]);
assert.deepEqual(math.diag([[1,2,3],[4,5,6]],-2), []);
});
it('should throw an error in case of invalid k', function() {
assert.throws(function () {math.diag([[1,2,3],[4,5,6]], 'a', '123');}, /Second parameter in function diag must be an integer/);
assert.throws(function () {math.diag([[1,2,3],[4,5,6]], 2.4);}, /Second parameter in function diag must be an integer/);
});
describe('bignumber', function () {
var array123 = [bignumber(1),bignumber(2),bignumber(3)];
var array123456 = [
[bignumber(1),bignumber(2),bignumber(3)],
[bignumber(4),bignumber(5),bignumber(6)]
];
it('should return a diagonal matrix on the default diagonal', function() {
assert.deepEqual(math.diag(array123),
[
[bignumber(1),bignumber(0),bignumber(0)],
[bignumber(0),bignumber(2),bignumber(0)],
[bignumber(0),bignumber(0),bignumber(3)]
]);
assert.deepEqual(math.diag(array123456), [bignumber(1),bignumber(5)]);
});
it('should return a array output on array input', function() {
assert.deepEqual(math.diag([bignumber(1),bignumber(2)]),
[
[bignumber(1),bignumber(0)],
[bignumber(0),bignumber(2)]
]);
});
it('should return a matrix output on matrix input', function() {
assert.deepEqual(math.diag(math.matrix([bignumber(1),bignumber(2)])),
math.matrix([
[bignumber(1),bignumber(0)],
[bignumber(0),bignumber(2)]
]));
assert.deepEqual(math.diag(math.matrix([
[bignumber(1),bignumber(2)],
[bignumber(3),bignumber(4)]
])), math.matrix([bignumber(1),bignumber(4)]));
});
it('should put vector on given diagonal k in returned matrix', function() {
assert.deepEqual(math.diag(array123, bignumber(1)), [
[bignumber(0),bignumber(1),bignumber(0),bignumber(0)],
[bignumber(0),bignumber(0),bignumber(2),bignumber(0)],
[bignumber(0),bignumber(0),bignumber(0),bignumber(3)]
]);
assert.deepEqual(math.diag(array123, bignumber(-1)), [
[bignumber(0),bignumber(0),bignumber(0)],
[bignumber(1),bignumber(0),bignumber(0)],
[bignumber(0),bignumber(2),bignumber(0)],
[bignumber(0),bignumber(0),bignumber(3)]
]);
});
it('should return diagonal k from a matrix', function() {
assert.deepEqual(math.diag(array123456, bignumber(1)), [bignumber(2),bignumber(6)]);
assert.deepEqual(math.diag(array123456, bignumber(-1)), [bignumber(4)]);
assert.deepEqual(math.diag(array123456, bignumber(-2)), []);
});
});
it('should throw an error of the input matrix is not valid', function() {
assert.throws(function () {math.diag([[[1],[2]],[[3],[4]]]);});
// TODO: test diag for all types of input (also scalar)
});
it('should throw an error in case of wrong number of arguments', function() {
assert.throws(function () {math.diag();}, error.ArgumentsError);
assert.throws(function () {math.diag([], 2, 3, 4);}, error.ArgumentsError);
});
it('should throw an error in case of invalid type of arguments', function() {
assert.throws(function () {math.diag(2);}, math.error.TypeError);
assert.throws(function () {math.diag([], 'a', 'str');}, math.error.TypeError);
});
it('should LaTeX diag', function () {
var expr1 = math.parse('diag([1,2,3])');
var expr2 = math.parse('diag([1,2,3],1)');
assert.equal(expr1.toTex(), '\\mathrm{diag}\\left(\\begin{bmatrix}1\\\\2\\\\3\\\\\\end{bmatrix}\\right)');
assert.equal(expr2.toTex(), '\\mathrm{diag}\\left(\\begin{bmatrix}1\\\\2\\\\3\\\\\\end{bmatrix},1\\right)');
});
});
| DenisGorbachev/mathjs | test/function/matrix/diag.test.js | JavaScript | apache-2.0 | 5,772 |
/*
* Copyright 2018-present Facebook, Inc.
*
* 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 reportError(message) {
alert(message);
}
if (typeof WebSocket === 'undefined') {
reportError('Your user agent does not support WebSockets. Lame.');
}
function establishConnection() {
var currentWebSocket = null;
var dataToSend = [];
var send = function(data) {
if (currentWebSocket) {
currentWebSocket.send(JSON.stringify(data));
} else {
console.log('Currently disconnected. Queueing request: ' + JSON.stringify(data));
dataToSend.push(data);
}
};
var connect = function() {
currentWebSocket = new WebSocket('ws://localhost:' + location.port + '/ws/build');
currentWebSocket.onopen = function() {
console.log('Connected!');
while (dataToSend.length) {
var data = dataToSend.shift();
send(data);
}
};
currentWebSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
console.log(data);
};
currentWebSocket.onclose = function() {
console.log('Disconnected. Trying to reconnect...');
currentWebSocket = null;
// Wait 1s before attempting to reconnect. If the connection fails,
// this method will be invoked again, scheduling another attempt.
setTimeout(connect, 1000);
};
};
// This will get queued so it is sent in onopen().
connect();
};
establishConnection();
| SeleniumHQ/buck | src/com/facebook/buck/httpserver/resources/static/test_websocket.js | JavaScript | apache-2.0 | 1,953 |
'use strict';
/**
* @ngdoc function
* @name openshiftConsole.controller:ProjectsController
* @description
* # ProjectsController
* Controller of the openshiftConsole
*/
angular.module('openshiftConsole')
.controller('ProjectsController', function ($scope, $route, $timeout, $filter, $location, DataService, AuthService, AlertMessageService, Logger, hashSizeFilter) {
$scope.projects = {};
$scope.alerts = $scope.alerts || {};
$scope.showGetStarted = false;
$scope.canCreate = undefined;
AlertMessageService.getAlerts().forEach(function(alert) {
$scope.alerts[alert.name] = alert.data;
});
AlertMessageService.clearAlerts();
$timeout(function() {
$('#openshift-logo').on('click.projectsPage', function() {
// Force a reload. Angular doesn't reload the view when the URL doesn't change.
$route.reload();
});
});
$scope.$on('deleteProject', function() {
loadProjects();
});
$scope.$on('$destroy', function(){
// The click handler is only necessary on the projects page.
$('#openshift-logo').off('click.projectsPage');
});
AuthService.withUser().then(function() {
loadProjects();
});
// Test if the user can submit project requests. Handle error notifications
// ourselves because 403 responses are expected.
DataService.get("projectrequests", null, $scope, { errorNotification: false})
.then(function() {
$scope.canCreate = true;
}, function(result) {
$scope.canCreate = false;
var data = result.data || {};
// 403 Forbidden indicates the user doesn't have authority.
// Any other failure status is an unexpected error.
if (result.status !== 403) {
var msg = 'Failed to determine create project permission';
if (result.status !== 0) {
msg += " (" + result.status + ")";
}
Logger.warn(msg);
return;
}
// Check if there are detailed messages. If there are, show them instead of our default message.
if (data.details) {
var messages = [];
_.forEach(data.details.causes || [], function(cause) {
if (cause.message) { messages.push(cause.message); }
});
if (messages.length > 0) {
$scope.newProjectMessage = messages.join("\n");
}
}
});
var loadProjects = function() {
DataService.list("projects", $scope, function(projects) {
$scope.projects = projects.by("metadata.name");
$scope.showGetStarted = hashSizeFilter($scope.projects) === 0;
});
};
});
| asiainfoLDP/datafactory | assets/app/scripts/controllers/projects.js | JavaScript | apache-2.0 | 2,609 |
import Color from 'color';
import patternReg from './patternReg';
export default function (colorOrBrush) {
/*eslint eqeqeq:0*/
if (colorOrBrush === 'none' || colorOrBrush == null) {
return null;
}
try {
let matched = colorOrBrush.match(patternReg);
// brush
if (matched) {
return [1, matched[1]];
//todo:
} else { // solid color
let c = new Color(colorOrBrush).rgbaArray();
return [0, c[0] / 255, c[1] / 255, c[2] / 255, c[3]];
}
} catch (err) {
console.warn(`"${colorOrBrush}" is not a valid color or brush`);
return null;
}
}
| MisterZhouZhou/ReactNativeLearing | node_modules/react-native-svg/lib/extract/extractBrush.js | JavaScript | apache-2.0 | 666 |
// Copyright 2012 Google Inc. 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.
/**
* @fileoverview Controllers for the Oppia feedback page.
*
* @author sll@google.com (Sean Lip)
*/
function Feedback($scope, $http, warningsData) {
$scope.currentPathname = window.location.pathname;
$scope.feedbackSubmitted = false;
$scope.submitFeedback = function(feedback) {
$http.post(
'/feedback/',
$scope.createRequest({
feedback: feedback,
url_params: $scope.getUrlParams()
}),
{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
).success(function(data) {
$scope.feedbackSubmitted = true;
})
.error(function(data) {
warningsData.addWarning(
data.error ||
'Oops, there was an error submitting your feedback. Sorry about this! ' +
'Please try adding an issue to our issue tracker instead.'
);
});
};
}
/**
* Injects dependencies in a way that is preserved by minification.
*/
Feedback.$inject = ['$scope', '$http', 'warningsData'];
| sunu/oppia-test-2 | templates/dev/head/js/controllers/feedback.js | JavaScript | apache-2.0 | 1,597 |
'use strict';
var assert = require('assert');
var _ = {
isNumber: require('lodash/isNumber'),
filter: require('lodash/filter'),
map: require('lodash/map'),
find: require('lodash/find'),
};
var Separator = require('./separator');
var Choice = require('./choice');
/**
* Choices collection
* Collection of multiple `choice` object
* @constructor
* @param {Array} choices All `choice` to keep in the collection
*/
module.exports = class Choices {
constructor(choices, answers) {
this.choices = choices.map((val) => {
if (val.type === 'separator') {
if (!(val instanceof Separator)) {
val = new Separator(val.line);
}
return val;
}
return new Choice(val, answers);
});
this.realChoices = this.choices
.filter(Separator.exclude)
.filter((item) => !item.disabled);
Object.defineProperty(this, 'length', {
get() {
return this.choices.length;
},
set(val) {
this.choices.length = val;
},
});
Object.defineProperty(this, 'realLength', {
get() {
return this.realChoices.length;
},
set() {
throw new Error('Cannot set `realLength` of a Choices collection');
},
});
}
/**
* Get a valid choice from the collection
* @param {Number} selector The selected choice index
* @return {Choice|Undefined} Return the matched choice or undefined
*/
getChoice(selector) {
assert(_.isNumber(selector));
return this.realChoices[selector];
}
/**
* Get a raw element from the collection
* @param {Number} selector The selected index value
* @return {Choice|Undefined} Return the matched choice or undefined
*/
get(selector) {
assert(_.isNumber(selector));
return this.choices[selector];
}
/**
* Match the valid choices against a where clause
* @param {Object} whereClause Lodash `where` clause
* @return {Array} Matching choices or empty array
*/
where(whereClause) {
return _.filter(this.realChoices, whereClause);
}
/**
* Pluck a particular key from the choices
* @param {String} propertyName Property name to select
* @return {Array} Selected properties
*/
pluck(propertyName) {
return _.map(this.realChoices, propertyName);
}
// Expose usual Array methods
indexOf() {
return this.choices.indexOf.apply(this.choices, arguments);
}
forEach() {
return this.choices.forEach.apply(this.choices, arguments);
}
filter() {
return this.choices.filter.apply(this.choices, arguments);
}
reduce() {
return this.choices.reduce.apply(this.choices, arguments);
}
find(func) {
return _.find(this.choices, func);
}
push() {
var objs = _.map(arguments, (val) => new Choice(val));
this.choices.push.apply(this.choices, objs);
this.realChoices = this.choices
.filter(Separator.exclude)
.filter((item) => !item.disabled);
return this.choices;
}
};
| GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/inquirer/lib/objects/choices.js | JavaScript | apache-2.0 | 3,015 |
define("dijit/TitlePane", ["dojo", "dijit", "text!dijit/templates/TitlePane.html", "dojo/fx", "dijit/_Templated", "dijit/layout/ContentPane", "dijit/_CssStateMixin"], function(dojo, dijit) {
dojo.declare(
"dijit.TitlePane",
[dijit.layout.ContentPane, dijit._Templated, dijit._CssStateMixin],
{
// summary:
// A pane with a title on top, that can be expanded or collapsed.
//
// description:
// An accessible container with a title Heading, and a content
// section that slides open and closed. TitlePane is an extension to
// `dijit.layout.ContentPane`, providing all the useful content-control aspects from it.
//
// example:
// | // load a TitlePane from remote file:
// | var foo = new dijit.TitlePane({ href: "foobar.html", title:"Title" });
// | foo.startup();
//
// example:
// | <!-- markup href example: -->
// | <div dojoType="dijit.TitlePane" href="foobar.html" title="Title"></div>
//
// example:
// | <!-- markup with inline data -->
// | <div dojoType="dijit.TitlePane" title="Title">
// | <p>I am content</p>
// | </div>
// title: String
// Title of the pane
title: "",
// open: Boolean
// Whether pane is opened or closed.
open: true,
// toggleable: Boolean
// Whether pane can be opened or closed by clicking the title bar.
toggleable: true,
// tabIndex: String
// Tabindex setting for the title (so users can tab to the title then
// use space/enter to open/close the title pane)
tabIndex: "0",
// duration: Integer
// Time in milliseconds to fade in/fade out
duration: dijit.defaultDuration,
// baseClass: [protected] String
// The root className to be placed on this widget's domNode.
baseClass: "dijitTitlePane",
templateString: dojo.cache("dijit", "templates/TitlePane.html"),
attributeMap: dojo.delegate(dijit.layout.ContentPane.prototype.attributeMap, {
title: { node: "titleNode", type: "innerHTML" },
tooltip: {node: "focusNode", type: "attribute", attribute: "title"}, // focusNode spans the entire width, titleNode doesn't
id:""
}),
buildRendering: function(){
this.inherited(arguments);
dojo.setSelectable(this.titleNode, false);
},
postCreate: function(){
this.inherited(arguments);
// Hover and focus effect on title bar, except for non-toggleable TitlePanes
// This should really be controlled from _setToggleableAttr() but _CssStateMixin
// doesn't provide a way to disconnect a previous _trackMouseState() call
if(this.toggleable){
this._trackMouseState(this.titleBarNode, "dijitTitlePaneTitle");
}
// setup open/close animations
var hideNode = this.hideNode, wipeNode = this.wipeNode;
this._wipeIn = dojo.fx.wipeIn({
node: this.wipeNode,
duration: this.duration,
beforeBegin: function(){
hideNode.style.display="";
}
});
this._wipeOut = dojo.fx.wipeOut({
node: this.wipeNode,
duration: this.duration,
onEnd: function(){
hideNode.style.display="none";
}
});
},
_setOpenAttr: function(/*Boolean*/ open, /*Boolean*/ animate){
// summary:
// Hook to make set("open", boolean) control the open/closed state of the pane.
// open: Boolean
// True if you want to open the pane, false if you want to close it.
dojo.forEach([this._wipeIn, this._wipeOut], function(animation){
if(animation && animation.status() == "playing"){
animation.stop();
}
});
if(animate){
var anim = this[open ? "_wipeIn" : "_wipeOut"];
anim.play();
}else{
this.hideNode.style.display = this.wipeNode.style.display = open ? "" : "none";
}
// load content (if this is the first time we are opening the TitlePane
// and content is specified as an href, or href was set when hidden)
if(this._started){
if(open){
this._onShow();
}else{
this.onHide();
}
}
this.arrowNodeInner.innerHTML = open ? "-" : "+";
dijit.setWaiState(this.containerNode,"hidden", open ? "false" : "true");
dijit.setWaiState(this.focusNode, "pressed", open ? "true" : "false");
this._set("open", open);
this._setCss();
},
_setToggleableAttr: function(/*Boolean*/ canToggle){
// summary:
// Hook to make set("toggleable", boolean) work.
// canToggle: Boolean
// True to allow user to open/close pane by clicking title bar.
dijit.setWaiRole(this.focusNode, canToggle ? "button" : "heading");
if(canToggle){
// TODO: if canToggle is switched from true to false shouldn't we remove this setting?
dijit.setWaiState(this.focusNode, "controls", this.id+"_pane");
dojo.attr(this.focusNode, "tabIndex", this.tabIndex);
}else{
dojo.removeAttr(this.focusNode, "tabIndex");
}
this._set("toggleable", canToggle);
this._setCss();
},
_setContentAttr: function(/*String|DomNode|Nodelist*/ content){
// summary:
// Hook to make set("content", ...) work.
// Typically called when an href is loaded. Our job is to make the animation smooth.
if(!this.open || !this._wipeOut || this._wipeOut.status() == "playing"){
// we are currently *closing* the pane (or the pane is closed), so just let that continue
this.inherited(arguments);
}else{
if(this._wipeIn && this._wipeIn.status() == "playing"){
this._wipeIn.stop();
}
// freeze container at current height so that adding new content doesn't make it jump
dojo.marginBox(this.wipeNode, { h: dojo.marginBox(this.wipeNode).h });
// add the new content (erasing the old content, if any)
this.inherited(arguments);
// call _wipeIn.play() to animate from current height to new height
if(this._wipeIn){
this._wipeIn.play();
}else{
this.hideNode.style.display = "";
}
}
},
toggle: function(){
// summary:
// Switches between opened and closed state
// tags:
// private
this._setOpenAttr(!this.open, true);
},
_setCss: function(){
// summary:
// Set the open/close css state for the TitlePane
// tags:
// private
var node = this.titleBarNode || this.focusNode;
var oldCls = this._titleBarClass;
this._titleBarClass = "dijit" + (this.toggleable ? "" : "Fixed") + (this.open ? "Open" : "Closed");
dojo.replaceClass(node, this._titleBarClass, oldCls || "");
this.arrowNodeInner.innerHTML = this.open ? "-" : "+";
},
_onTitleKey: function(/*Event*/ e){
// summary:
// Handler for when user hits a key
// tags:
// private
if(e.charOrCode == dojo.keys.ENTER || e.charOrCode == ' '){
if(this.toggleable){
this.toggle();
}
dojo.stopEvent(e);
}else if(e.charOrCode == dojo.keys.DOWN_ARROW && this.open){
this.containerNode.focus();
e.preventDefault();
}
},
_onTitleClick: function(){
// summary:
// Handler when user clicks the title bar
// tags:
// private
if(this.toggleable){
this.toggle();
}
},
setTitle: function(/*String*/ title){
// summary:
// Deprecated. Use set('title', ...) instead.
// tags:
// deprecated
dojo.deprecated("dijit.TitlePane.setTitle() is deprecated. Use set('title', ...) instead.", "", "2.0");
this.set("title", title);
}
});
return dijit.TitlePane;
});
| sulistionoadi/belajar-springmvc-dojo | training-web/src/main/webapp/js/dojotoolkit/dijit/TitlePane.js | JavaScript | apache-2.0 | 7,023 |
define(function(require) {
'use strict';
var Utility = require('common/utility');
var Tooltipable = require('foreground/view/behavior/tooltipable');
var TimeLabelAreaTemplate = require('text!template/streamControlBar/timeLabelArea.html');
var TimeLabelArea = Marionette.LayoutView.extend({
id: 'timeLabelArea',
template: _.template(TimeLabelAreaTemplate),
ui: {
elapsedTimeLabel: 'elapsedTimeLabel',
totalTimeLabel: 'totalTimeLabel'
},
behaviors: {
Tooltipable: {
behaviorClass: Tooltipable
}
},
events: {
'click @ui.elapsedTimeLabel': '_onClickElapsedTimeLabel'
},
modelEvents: {
'change:showRemainingTime': '_onChangeShowRemainingTime'
},
timeSlider: null,
timeSliderEvents: {
'change:currentTime': '_onTimeSliderChangeCurrentTime'
},
player: null,
playerEvents: {
'change:loadedVideo': '_onPlayerChangeLoadedVideo'
},
initialize: function(options) {
this.timeSlider = options.timeSlider;
this.player = options.player;
this.bindEntityEvents(this.timeSlider, this.timeSliderEvents);
this.bindEntityEvents(this.player, this.playerEvents);
},
onRender: function() {
var totalTime = this._getTotalTime(this.player.get('loadedVideo'));
this._setTotalTimeLabelText(totalTime);
this._setElapsedTimeLabelText(this.timeSlider.get('currentTime'));
this._setElapsedTimeLabelTooltipText(this.model.get('showRemainingTime'));
},
_onTimeSliderChangeCurrentTime: function(model, currentTime) {
this._setElapsedTimeLabelText(currentTime);
},
_onClickElapsedTimeLabel: function() {
this.model.toggleShowRemainingTime();
},
_onChangeShowRemainingTime: function(model, showRemainingTime) {
this._setElapsedTimeLabelTooltipText(showRemainingTime);
this._setElapsedTimeLabelText(this.timeSlider.get('currentTime'));
},
_onPlayerChangeLoadedVideo: function(model, loadedVideo) {
var totalTime = this._getTotalTime(loadedVideo);
this._setTotalTimeLabelText(totalTime);
// Since there's no loaded video the label could not possibly be anything other than 0.
// This is important if remaining time is being shown and timeSlider's currentTime is 0 since
// changing the loadedVideo to null won't trigger a change event on timerSlider's currentTime
if (_.isNull(loadedVideo)) {
this._setElapsedTimeLabelText(0);
}
},
_getTotalTime: function(loadedVideo) {
var totalTime = _.isNull(loadedVideo) ? 0 : loadedVideo.get('duration');
return totalTime;
},
// Update the tooltip's text to reflect whether remaining or elapsed time is being shown.
_setElapsedTimeLabelTooltipText: function(showRemainingTime) {
var tooltipText = chrome.i18n.getMessage(showRemainingTime ? 'remainingTime' : 'elapsedTime');
this.ui.elapsedTimeLabel.attr('data-tooltip-text', tooltipText);
},
// Update the value of elapsedTimeLabel to the timeSlider's current time or
// the difference between the total time and the current time.
// This value is not guaranteed to reflect the player's current time as the user could be
// dragging the time slider which will cause the label to represent a different value.
_setElapsedTimeLabelText: function(currentTime) {
var showRemainingTime = this.model.get('showRemainingTime');
var totalTime = this._getTotalTime(this.player.get('loadedVideo'));
var elapsedTime = this._getElapsedTime(currentTime, totalTime, showRemainingTime);
this.ui.elapsedTimeLabel.text(Utility.prettyPrintTime(elapsedTime));
},
_getElapsedTime: function(currentTime, totalTime, showRemainingTime) {
var elapsedTime = showRemainingTime ? totalTime - currentTime : currentTime;
return elapsedTime;
},
_setTotalTimeLabelText: function(totalTime) {
this.ui.totalTimeLabel.text(Utility.prettyPrintTime(totalTime));
}
});
return TimeLabelArea;
}); | trsouz/StreamusChromeExtension | src/js/foreground/view/streamControlBar/timeLabelAreaView.js | JavaScript | apache-2.0 | 4,059 |
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
var crypto = require('crypto');
exports.hex = function(str){
return crypto.createHash('md5').update(str).digest('hex');
}; | 3203317/h9n | web/lib/md5.js | JavaScript | artistic-2.0 | 8,697 |
// Copyright (C) 2017 Apple Inc. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-function-definitions-runtime-semantics-evaluation
description: Function declaration completion value is empty.
info: |
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
1. Return NormalCompletion(empty).
---*/
assert.sameValue(eval('function f() {}'), undefined);
assert.sameValue(eval('1; function f() {}'), 1);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/function/cptn-decl.js | JavaScript | bsd-2-clause | 501 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-throws.case
// - src/dstr-binding/error/async-gen-meth.template
/*---
description: Error thrown when evaluating the initializer (async generator method)
esid: sec-asyncgenerator-definitions-propertydefinitionevaluation
features: [async-iteration]
flags: [generated]
info: |
AsyncGeneratorMethod :
async [no LineTerminator here] * PropertyName ( UniqueFormalParameters )
{ AsyncGeneratorBody }
1. Let propKey be the result of evaluating PropertyName.
2. ReturnIfAbrupt(propKey).
3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true.
Otherwise let strict be false.
4. Let scope be the running execution context's LexicalEnvironment.
5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters,
AsyncGeneratorBody, scope, strict).
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
SingleNameBinding : BindingIdentifier Initializeropt
[...]
6. If Initializer is present and v is undefined, then
a. Let defaultValue be the result of evaluating Initializer.
b. Let v be GetValue(defaultValue).
c. ReturnIfAbrupt(v).
---*/
function thrower() {
throw new Test262Error();
}
var obj = {
async *method({ x = thrower() }) {
}
};
assert.throws(Test262Error, function() {
obj.method({});
});
| sebastienros/jint | Jint.Tests.Test262/test/language/expressions/object/dstr-async-gen-meth-obj-ptrn-id-init-throws.js | JavaScript | bsd-2-clause | 1,477 |