code
stringlengths 2
1.05M
|
---|
"use strict";
var Cylon = require("cylon");
Cylon
.robot()
.connection("arduino", { adaptor: "firmata", port: "/dev/ttyACM0" })
.device("bmp180", { driver: "bmp180" })
.on("ready", function(bot) {
bot.bmp180.getTemperature(function(err, val) {
if (err) {
console.log(err);
} else {
console.log("getTemperature call:");
console.log("\tTemp: " + val.temp + " C");
}
});
setTimeout(function() {
bot.bmp180.getPressure(1, function(err, val) {
if (err) {
console.log(err);
} else {
console.log("getPressure call:");
console.log("\tTemperature: " + val.temp + " C");
console.log("\tPressure: " + val.press + " Pa");
}
});
}, 1000);
setTimeout(function() {
bot.bmp180.getAltitude(1, null, function(err, val) {
if (err) {
console.log(err);
} else {
console.log("getAltitude call:");
console.log("\tTemperature: " + val.temp + " C");
console.log("\tPressure: " + val.press + " Pa");
console.log("\tAltitude: " + val.alt + " m");
}
});
}, 2000);
});
Cylon.start();
|
'use strict';
var _Object$assign = require('babel-runtime/core-js/object/assign')['default'];
var _getIterator = require('babel-runtime/core-js/get-iterator')['default'];
var fs = require('fs'),
path = require('path'),
resolve = require('resolve');
var CASE_INSENSITIVE = fs.existsSync(path.join(__dirname, 'reSOLVE.js'));
// http://stackoverflow.com/a/27382838
function fileExistsWithCaseSync(_x) {
var _again = true;
_function: while (_again) {
var filepath = _x;
dir = filenames = undefined;
_again = false;
// shortcut exit
if (!fs.existsSync(filepath)) return false;
var dir = path.dirname(filepath);
if (dir === '/' || dir === '.' || /^[A-Z]:\\$/.test(dir)) return true;
var filenames = fs.readdirSync(dir);
if (filenames.indexOf(path.basename(filepath)) === -1) {
return false;
}
_x = dir;
_again = true;
continue _function;
}
}
function fileExists(filepath) {
if (CASE_INSENSITIVE) {
return fileExistsWithCaseSync(filepath);
} else {
return fs.existsSync(filepath);
}
}
function opts(basedir, settings) {
// pulls all items from 'import/resolve'
return _Object$assign({}, settings['import/resolve'], { basedir: basedir });
}
/**
* wrapper around resolve
* @param {string} p - module path
* @param {object} context - ESLint context
* @return {string} - the full module filesystem path
*/
module.exports = function (p, context) {
function withResolver(resolver) {
// resolve just returns the core module id, which won't appear to exist
if (resolver.isCore(p)) return p;
try {
var file = resolver.sync(p, opts(path.dirname(context.getFilename()), context.settings));
if (!fileExists(file)) return null;
return file;
} catch (err) {
// probably want something more general here
if (err.message.indexOf('Cannot find module') === 0) {
return null;
}
throw err;
}
}
var resolvers = (context.settings['import/resolvers'] || ['resolve']).map(require);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = _getIterator(resolvers), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var resolver = _step.value;
var file = withResolver(resolver);
if (file) return file;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator['return']) {
_iterator['return']();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return null;
};
module.exports.relative = function (p, r, settings) {
try {
var file = resolve.sync(p, opts(path.dirname(r), settings));
if (!fileExists(file)) return null;
return file;
} catch (err) {
if (err.message.indexOf('Cannot find module') === 0) return null;
throw err; // else
}
}; |
(function(){
<?php
print (new \tomk79\pickles2\px2dthelper\main($px))->document_modules()->build_js();
?>
})(); |
//jshint strict: false
module.exports = function(config) {
config.set({
basePath: './app',
files: [
'bower_components/angular/angular.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'*.js'
],
autoWatch: true,
frameworks: ['jasmine'],
browsers: ['Chrome'],
plugins: [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter: {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
angular.module('umbraco').directive('maxlen', function () {
return {
require: 'ngModel',
link: function (scope, el, attrs, ctrl) {
var validate = false;
var length = 999999;
if (attrs.name === 'title') {
validate = scope.model.config.allowLongTitles !== '1';
length = scope.serpTitleLength;
} else if (attrs.name === 'description') {
validate = scope.model.config.allowLongDescriptions !== '1';
length = scope.serpDescriptionLength;
}
ctrl.$parsers.unshift(function (viewValue) {
if (validate && viewValue.length > length) {
ctrl.$setValidity('maxlen', false);
} else {
ctrl.$setValidity('maxlen', true);
}
return viewValue;
});
}
};
});
|
var nock = require('nock');
var Mockaroo = require('../lib/mockaroo');
require('chai').should();
describe('Client', function() {
describe('constructor', function() {
it('should require an api key', function() {
(function() {
new Mockaroo.Client({});
}).should.throw('apiKey is required');
});
});
describe('convertError', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
it('should convert Invalid API Key to InvalidApiKeyError', function() {
client.convertError({ data: { error: 'Invalid API Key' }}).should.be.a.instanceOf(Mockaroo.errors.InvalidApiKeyError)
});
it('should convert errors containing "limited" to UsageLimitExceededError', function() {
client.convertError({ data: { error: 'Silver plans are limited to 1,000,000 records per day.' }}).should.be.a.instanceOf(Mockaroo.errors.UsageLimitExceededError)
});
});
describe('getUrl', function() {
it('should default to https://mockaroo.com', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
client.getUrl().should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=1')
});
it('should allow you to change the port', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx',
secure: false,
port: 3000
});
client.getUrl().should.equal('http://mockaroo.com:3000/api/generate.json?client=node&key=xxx&count=1');
});
it('should use http when secure:false', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx',
secure: false
});
client.getUrl().should.equal('http://mockaroo.com/api/generate.json?client=node&key=xxx&count=1');
});
it('should allow you to set a count > 1', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx',
});
client.getUrl({count: 10}).should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=10');
});
it('should allow you to customize the host', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx',
host: 'foo'
});
client.getUrl().should.equal('https://foo/api/generate.json?client=node&key=xxx&count=1');
});
it('should include schema', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
client.getUrl({schema: 'MySchema'}).should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=1&schema=MySchema');
});
it('should allow you to generate csv', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
client.getUrl({format: 'csv'}).should.equal('https://mockaroo.com/api/generate.csv?client=node&key=xxx&count=1');
});
it('should allow you to remove the header from csv', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
client.getUrl({format: 'csv', header: false}).should.equal('https://mockaroo.com/api/generate.csv?client=node&key=xxx&count=1&header=false');
})
});
describe('generate', function() {
var client = new Mockaroo.Client({
secure: false,
apiKey: 'xxx'
});
it('should require fields or schema', function() {
(function() {
client.generate()
}).should.throw('Either fields or schema option must be specified');
});
describe('when successful', function() {
var api = nock('http://mockaroo.com')
.post('/api/generate.json?client=node&key=xxx&count=1')
.reply(200, JSON.stringify([{ foo: 'bar' }]))
it('should resolve', function() {
return client.generate({
fields: [{
name: 'foo',
type: 'Custom List',
values: ['bar']
}]
}).then(function(records) {
records.should.deep.equal([{ foo: 'bar' }]);
})
});
})
describe('when unsuccessful', function() {
var api = nock('http://mockaroo.com')
.post('/api/generate.json?client=node&key=xxx&count=1')
.reply(500, JSON.stringify({ error: 'Invalid API Key' }))
it('should handle errors', function() {
return client.generate({
fields: []
}).catch(function(error) {
error.should.be.instanceOf(Mockaroo.errors.InvalidApiKeyError)
})
});
});
it('should required fields to be an array', function() {
(function() {
client.generate({ fields: 'foo' })
}).should.throw('fields must be an array');
});
it('should required a name for each field', function() {
(function() {
client.generate({ fields: [{ type: 'Row Number' }] })
}).should.throw('each field must have a name');
});
it('should required a type for each field', function() {
(function() {
client.generate({ fields: [{ name: 'ID' }] })
}).should.throw('each field must have a type');
});
});
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M4 15h16v-2H4v2zm0 4h16v-2H4v2zm0-8h16V9H4v2zm0-6v2h16V5H4z"
}), 'ViewHeadlineSharp');
exports.default = _default; |
import React from 'react'
import Icon from 'react-icon-base'
const GoColorMode = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m5 5v30h30v-30h-30z m2.5 27.5v-25h25l-25 25z"/></g>
</Icon>
)
export default GoColorMode
|
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* openAUSIAS: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Java and jQuery
* openAUSIAS is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* 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';
moduloTipocompeticion.controller('TipocompeticionRemoveController', ['$scope', '$routeParams', 'serverService',
function ($scope, $routeParams, serverService) {
$scope.result = "";
$scope.back = function () {
window.history.back();
};
$scope.ob = 'tipocompeticion';
$scope.id = $routeParams.id;
$scope.title = "Borrado de un Tipo de Competicion";
$scope.icon = "fa-futbol-o";
serverService.getDataFromPromise(serverService.promise_getOne($scope.ob, $scope.id)).then(function (data) {
$scope.bean = data.message;
});
$scope.remove = function () {
serverService.getDataFromPromise(serverService.promise_removeOne($scope.ob, $scope.id)).then(function (data) {
$scope.result = data;
});
}
;
}]); |
/*
基本测试,ejs 模版 测试 例子
*/
var should = require('should');
var request = require('request');
var path = require('path');
var testconf = require('./testconf.js');
module.exports.rrestjsconfig = {
listenPort:3000,
tempSet:'ejs',
tempFolder :'/static',
baseDir: path.join(__dirname),
};
var chtml='';
var dhtml = '';
var fhtml = '';
var http = require('http'),
rrest = require('../'),
i=0,
server = http.createServer(function (req, res) {
var pname = req.pathname;
if(pname === '/a'){
res.render('/ejs');
}
else if(pname === '/b'){
res.render('/ejs.ejs', {"name":'hello world'});
}
else if(pname === '/c'){
res.render('/ejs',function(err, html){//测试不加后缀名是否可以render成功
chtml = html;
});
}
else if(pname === '/d'){
res.render('/ejs.ejs', {"name":'hello world'}, function(err, html){
dhtml = html;
});
}
else if(pname === '/e'){
res.render('/ejs.ejs', 1, {"usersex":'hello world'});
}
else if(pname === '/f'){
res.render('/ejs', 2, {}, function(err, html){
fhtml = html;
});
}
else if(pname === '/g'){
res.compiletemp('/ejs.ejs', function(err, html){
res.sendjson({'data':html});
});
}
else if(pname === '/h'){
res.compiletemp('/ejs.ejs', 3, {"name":'hello world'}, function(err, html){
res.sendjson({'data':html});
});
}
else if(pname === '/i'){
res.compiletemp('/ejs2', 3, {"name":'hello world'}, function(err, html){
res.sendjson({'data':html});
});
}
}).listen(rrest.config.listenPort);
//设置全局的模版option
rrest.tploption.userid = function(req,res){return req.ip};
rrest.tploption.name = 'rrestjs default';
rrest.tploption.usersex = 'male';
http.globalAgent.maxSockets = 10;
var i = 9;
var r = 0
var result = function(name){
var num = ++r;
console.log('%s test done, receive %d/%d', name, num, i);
if(num>=i){
console.log('ejs.js test done.')
process.exit();
}
}
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/a',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>')
result('/a request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/b',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>')
result('/b request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/c',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
setTimeout(function(){
should.strictEqual(chtml, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
result('/c request')
},100)
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/d',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
setTimeout(function(){
should.strictEqual(dhtml, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
result('/d request')
},100)
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/e',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>hello world</li><form></form>');
result('/e request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/f',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
setTimeout(function(){
should.strictEqual(fhtml, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
result('/f request')
},100)
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/g',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '{\"data\":\"<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}');
result('/g request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/h',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '{\"data\":\"<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}');
result('/h request')
});
setTimeout(function(){
rrest.ejs.open ='{{'
rrest.ejs.close ='}}'
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/i',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '{\"data\":\"<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}');
result('/h request')
});
},1000)
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M5 18h14V8H5v10zm3.82-6.42 2.12 2.12 4.24-4.24 1.41 1.41-5.66 5.66L7.4 13l1.42-1.42z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m16.6 10.88-1.42-1.42-4.24 4.25-2.12-2.13L7.4 13l3.54 3.54z"
}, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm0 14H5V8h14v10z"
}, "2")], 'DomainVerificationTwoTone');
exports.default = _default; |
var _ = require('lodash'),
Promise = require('bluebird'),
IndexMapGenerator = require('./index-generator'),
PagesMapGenerator = require('./page-generator'),
PostsMapGenerator = require('./post-generator'),
UsersMapGenerator = require('./user-generator'),
TagsMapGenerator = require('./tag-generator'),
SiteMapManager;
SiteMapManager = function (opts) {
opts = opts || {};
this.initialized = false;
this.pages = opts.pages || this.createPagesGenerator(opts);
this.posts = opts.posts || this.createPostsGenerator(opts);
this.authors = opts.authors || this.createUsersGenerator(opts);
this.tags = opts.tags || this.createTagsGenerator(opts);
this.index = opts.index || this.createIndexGenerator(opts);
};
_.extend(SiteMapManager.prototype, {
createIndexGenerator: function () {
return new IndexMapGenerator(_.pick(this, 'pages', 'posts', 'authors', 'tags'));
},
createPagesGenerator: function (opts) {
return new PagesMapGenerator(opts);
},
createPostsGenerator: function (opts) {
return new PostsMapGenerator(opts);
},
createUsersGenerator: function (opts) {
return new UsersMapGenerator(opts);
},
createTagsGenerator: function (opts) {
return new TagsMapGenerator(opts);
},
init: function () {
var self = this,
initOps = [
this.pages.init(),
this.posts.init(),
this.authors.init(),
this.tags.init()
];
return Promise.all(initOps).then(function () {
self.initialized = true;
});
},
getIndexXml: function () {
if (!this.initialized) {
return '';
}
return this.index.getIndexXml();
},
getSiteMapXml: function (type) {
if (!this.initialized || !this[type]) {
return null;
}
return this[type].siteMapContent;
},
pageAdded: function (page) {
if (!this.initialized) {
return;
}
if (page.get('status') !== 'published') {
return;
}
this.pages.addUrl(page.toJSON());
},
pageEdited: function (page) {
if (!this.initialized) {
return;
}
var pageData = page.toJSON(),
wasPublished = page.updated('status') === 'published',
isPublished = pageData.status === 'published';
// Published status hasn't changed and it's published
if (isPublished === wasPublished && isPublished) {
this.pages.updateUrl(pageData);
} else if (!isPublished && wasPublished) {
// Handle page going from published to draft
this.pageDeleted(page);
} else if (isPublished && !wasPublished) {
// ... and draft to published
this.pageAdded(page);
}
},
pageDeleted: function (page) {
if (!this.initialized) {
return;
}
this.pages.removeUrl(page.toJSON());
},
postAdded: function (post) {
if (!this.initialized) {
return;
}
if (post.get('status') !== 'published') {
return;
}
this.posts.addUrl(post.toJSON());
},
postEdited: function (post) {
if (!this.initialized) {
return;
}
var postData = post.toJSON(),
wasPublished = post.updated('status') === 'published',
isPublished = postData.status === 'published';
// Published status hasn't changed and it's published
if (isPublished === wasPublished && isPublished) {
this.posts.updateUrl(postData);
} else if (!isPublished && wasPublished) {
// Handle post going from published to draft
this.postDeleted(post);
} else if (isPublished && !wasPublished) {
// ... and draft to published
this.postAdded(post);
}
},
postDeleted: function (post) {
if (!this.initialized) {
return;
}
this.posts.removeUrl(post.toJSON());
},
userAdded: function (user) {
if (!this.initialized) {
return;
}
this.authors.addUrl(user.toJSON());
},
userEdited: function (user) {
if (!this.initialized) {
return;
}
var userData = user.toJSON();
this.authors.updateUrl(userData);
},
userDeleted: function (user) {
if (!this.initialized) {
return;
}
this.authors.removeUrl(user.toJSON());
},
tagAdded: function (tag) {
if (!this.initialized) {
return;
}
this.tags.addUrl(tag.toJSON());
},
tagEdited: function (tag) {
if (!this.initialized) {
return;
}
this.tags.updateUrl(tag.toJSON());
},
tagDeleted: function (tag) {
if (!this.initialized) {
return;
}
this.tags.removeUrl(tag.toJSON());
},
// TODO: Call this from settings model when it's changed
permalinksUpdated: function (permalinks) {
if (!this.initialized) {
return;
}
this.posts.updatePermalinksValue(permalinks.toJSON ? permalinks.toJSON() : permalinks);
},
_refreshAllPosts: _.throttle(function () {
this.posts.refreshAllPosts();
}, 3000, {
leading: false,
trailing: true
})
});
module.exports = SiteMapManager;
|
/**
* Draws rectangles
*/
Y.Rect = Y.Base.create("rect", Y.Shape, [], {
/**
* Indicates the type of shape
*
* @property _type
* @readOnly
* @type String
*/
_type: "rect",
/**
* @private
*/
_draw: function()
{
var x = this.get("x"),
y = this.get("y"),
w = this.get("width"),
h = this.get("height"),
fill = this.get("fill"),
stroke = this.get("stroke");
this.drawRect(x, y, w, h);
this._paint();
}
});
|
/**
* Test helpers for the tap tests that use material-ui as a front end
*/
import {saveToken, elements} from '../demo';
/**
*
* @param {object} aBrowser
* @param {string} accessToken
* @param {boolean} isOneOnOne
* @param {string} to
*/
export default function loginAndOpenWidget(aBrowser, accessToken, isOneOnOne, to) {
saveToken(aBrowser, accessToken);
if (isOneOnOne) {
aBrowser.element(elements.toPersonRadioButton).click();
aBrowser.element(elements.toPersonInput).setValue(to);
}
else {
aBrowser.element(elements.toSpaceRadioButton).click();
aBrowser.element(elements.toSpaceInput).setValue(to);
}
aBrowser.element(elements.openSpaceWidgetButton).click();
aBrowser.waitUntil(() => aBrowser.element(elements.spaceWidgetContainer).isVisible(), 3500, 'widget failed to open');
}
|
import browserColor from 'tap-browser-color';
browserColor();
import test from 'tape';
import React from 'react';
import universal from '../../client';
import routes from '../fixtures/routes';
import reducers from '../fixtures/reducers';
const app = universal({ React, routes, reducers });
const store = app();
test('Client app', nest => {
nest.test('...without Express instance', assert => {
const msg = 'should not return an Express instance';
const actual = typeof app.use;
const expected = 'undefined';
assert.equal(actual, expected, msg);
assert.end();
});
nest.test('...initalState', assert => {
const msg = 'should render initialState';
const text = 'Untitled';
const actual = document.querySelectorAll('.title')[0].innerHTML;
const expected = text;
assert.equal(actual, expected, msg);
assert.end();
});
nest.test('...client call', assert => {
const msg = 'should return store instance';
const actual = typeof store.dispatch;
const expected = 'function';
assert.equal(actual, expected, msg);
assert.end();
});
nest.test('...with dispatch', assert => {
const msg = 'should render new output';
const text = 'Client render';
store.dispatch({
type: 'SET_TITLE',
title: text
});
setTimeout(() => {
const actual = document.querySelectorAll('.title')[0].innerHTML;
const expected = text;
assert.equal(actual, expected, msg);
assert.end();
}, 100);
});
nest.test('...with second dispatch', assert => {
const msg = 'should render new output';
const text = 'Client render 2';
store.dispatch({
type: 'SET_TITLE',
title: text
});
setTimeout(() => {
const actual = document.querySelectorAll('.title')[0].innerHTML;
const expected = text;
assert.equal(actual, expected, msg);
assert.end();
}, 100);
});
});
|
import fs from "fs";
import { parse } from "babylon";
import CodeGenerator from "../CodeGenerator";
import processTokens from "../process-tokens";
import {timeLogStart, timeLog} from "../utils";
function parseText(text) {
timeLogStart("started parsing text");
let ast = parse(text, {
preserveParens: true,
sourceType: "module",
plugins: [ "*" ]
});
timeLog("parsed input");
let tokens = ast.tokens;
let semicolons = ast.tokens.filter(token => token.type.label === ";");
timeLogStart();
const modifiedTokens = processTokens(text, tokens, semicolons);
timeLog(`processed ${tokens.length} -> ${modifiedTokens.length} tokens`);
return { ast: ast.program, tokens: modifiedTokens, semicolons };
}
export function formatText(text) {
const { ast, tokens, semicolons } = parseText(text);
let generator = new CodeGenerator(ast, text, tokens, semicolons);
return generator.generate();
}
export function formatFile(filename) {
try {
timeLogStart();
const text = fs.readFileSync(filename).toString();
timeLog("finished reading file");
return formatText(text);
} catch (error) {
error.message = `${filename}: ${error.message}`;
throw error;
}
}
|
var Thoonk = require('../thoonk').Thoonk;
var thoonk = new Thoonk();
var jobs = {};
var stats = thoonk.feed('thoonk_job_stats');
thoonk.mredis.smembers('feeds', function(err, feeds) {
feeds.forEach(function(name) {
thoonk.mredis.hget('feed.config:' + name, 'type', function(err, reply) {
if(reply == 'job') {
jobs[name] = thoonk.job(name);
}
});
});
});
thoonk.on('create', function(name, instance) {
thoonk.mredis.hget('feed.config:' + name, 'type', function(err, reply) {
if(reply == 'job') {
jobs[name] = thoonk.job(name);
}
});
});
thoonk.on('delete', function(name, instance) {
if(jobs.hasOwnProperty(name)) {
jobs[name].quit();
delete jobs[name];
};
});
var update = function() {
for(key in jobs) { //function(job, key) {
(function(key, jobs) {
var multi = thoonk.mredis.multi();
multi.llen('feed.ids:' + key);
multi.getset('feed.publishes:' + key, '0');
multi.getset('feed.finishes:' + key, '0');
multi.zcount('feed.claimed:' + key,'0', '999999999999999');
multi.hlen('feed.items:' + key);
multi.exec(function(err, reply) {
console.log('----' + key + '----');
console.log('available:', reply[0]);
console.log('publishes:', reply[1]);
console.log('finishes:', reply[1]);
console.log('claimed:', reply[3]);
console.log('total:', reply[4]);
stats.publish(JSON.stringify({available: reply[0], publishes: reply[1], finishes: reply[2], claimed: reply[3], total:reply[4]}), key)
});
})(key, jobs);
}
setTimeout(update, 1000);
};
update();
var http = require('http');
var static = require('node-static');
var fileServer = new(static.Server)('./monitor-html');
var server = http.createServer(function(request, response) {
request.addListener('end', function () {
fileServer.serve(request, response);
});
});
server.listen(8000);
var io = require('socket.io').listen(8001);
io.sockets.on('connection', function (socket) {
var thissocket = socket;
var statupdate = function(feed, id, item) {
var uitem = JSON.parse(item);
uitem.id = id;
console.log('msg', feed, item, id);
socket.emit('message', uitem);
};
stats.subscribe({
edit: statupdate,
publish: statupdate
});
socket.once('disconnect', function() {
stats.unsubscribe({edit: statupdate, publish: statupdate});
});
});
|
import {writeArray} from 'event-stream';
import gulp from 'gulp';
import license from '../../tasks/helpers/license-helper';
describe('license', () => {
let result;
beforeEach(done => {
const licenseStream = gulp.src('src/pivotal-ui/components/alerts')
.pipe(license());
licenseStream.on('error', (error) => {
console.error(error);
callback();
});
licenseStream.pipe(writeArray((error, data) => {
result = data;
done();
}));
});
it('creates an MIT license for the component', () => {
expect(result[0].path).toEqual('alerts/LICENSE');
expect(result[0].contents.toString()).toContain('The MIT License');
});
});
|
/*globals define, _*/
/*jshint browser: true*/
/**
* @author rkereskenyi / https://github.com/rkereskenyi
*/
define(['js/KeyboardManager/IKeyTarget'], function (IKeyTarget) {
'use strict';
var DiagramDesignerWidgetKeyboard;
DiagramDesignerWidgetKeyboard = function () {
};
_.extend(DiagramDesignerWidgetKeyboard.prototype, IKeyTarget.prototype);
DiagramDesignerWidgetKeyboard.prototype.onKeyDown = function (eventArgs) {
var ret = true;
switch (eventArgs.combo) {
case 'del':
this.onSelectionDelete(this.selectionManager.getSelectedElements());
ret = false;
break;
case 'ctrl+a':
this.selectAll();
ret = false;
break;
case 'ctrl+q':
this.selectNone();
ret = false;
break;
case 'ctrl+i':
this.selectItems();
ret = false;
break;
case 'ctrl+u':
this.selectConnections();
ret = false;
break;
case 'ctrl+l':
this.selectInvert();
ret = false;
break;
case 'up':
this._moveSelection(0, -this.gridSize);
ret = false;
break;
case 'down':
this._moveSelection(0, this.gridSize);
ret = false;
break;
case 'left':
this._moveSelection(-this.gridSize, 0);
ret = false;
break;
case 'right':
this._moveSelection(this.gridSize, 0);
ret = false;
break;
case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_TOP:
this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_TOP);
ret = false;
break;
case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_BOTTOM:
this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_BOTTOM);
ret = false;
break;
case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_LEFT:
this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_LEFT);
ret = false;
break;
case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_RIGHT:
this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_RIGHT);
ret = false;
break;
default:
break;
/*case 'ctrl+c':
this.onClipboardCopy(this.selectionManager.getSelectedElements());
ret = false;
break;
case 'ctrl+v':
this.onClipboardPaste();
ret = false;
break;*/
}
return ret;
};
DiagramDesignerWidgetKeyboard.prototype.onKeyUp = function (eventArgs) {
var ret = true;
switch (eventArgs.combo) {
case 'up':
this._endMoveSelection();
ret = false;
break;
case 'down':
this._endMoveSelection();
ret = false;
break;
case 'left':
this._endMoveSelection();
ret = false;
break;
case 'right':
this._endMoveSelection();
ret = false;
break;
}
return ret;
};
DiagramDesignerWidgetKeyboard.prototype._moveSelection = function (dX, dY) {
if (!this._keyMoveDelta) {
this._keyMoveDelta = {x: 0, y: 0};
this.dragManager._initDrag(0, 0);
this.dragManager._startDrag(undefined);
}
this._keyMoveDelta.x += dX;
this._keyMoveDelta.y += dY;
this.dragManager._updateDraggedItemPositions(this._keyMoveDelta.x, this._keyMoveDelta.y);
};
DiagramDesignerWidgetKeyboard.prototype._endMoveSelection = function () {
if (this._keyMoveDelta) {
// reinitialize keyMove data
this._keyMoveDelta = undefined;
this.dragManager._endDragAction();
}
};
return DiagramDesignerWidgetKeyboard;
});
|
import "core-js/modules/web.dom.iterable";
import "core-js/modules/es6.promise";
var p = Promise.resolve(0);
Promise.all([p]).then(function (outcome) {
alert("OK");
});
|
fn() => x
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "12",
cy: "23",
r: "1"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "8",
cy: "23",
r: "1"
}, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "16",
cy: "23",
r: "1"
}, "2"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M13.41 10 17 6.42c.39-.39.39-1.02 0-1.42L12.21.21c-.14-.14-.32-.21-.5-.21-.39 0-.71.32-.71.71v6.88L7.11 3.71a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41L10.59 10 5.7 14.89c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L11 12.41v6.88c0 .39.32.71.71.71.19 0 .37-.07.5-.21L17 15c.39-.39.39-1.02 0-1.42L13.41 10zM13 3.83l1.88 1.88L13 7.59V3.83zm0 12.34v-3.76l1.88 1.88L13 16.17z"
}, "3")], 'SettingsBluetoothRounded');
exports.default = _default; |
'use strict';
module.exports = {
db: {
dbName:'sean-dev',
username : 'SeanDB',
password : 'HU7XQQBNWq',
dialect: "postgres", // 'sqlite', 'postgres', 'mariadb','mysql'
port : 5432 // 5432 for postgres, 3306 for mysql and mariaDB ,
},
app: {
title: 'SEAN - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
(function () {
'use strict';
angular
.module('nama.common')
.directive('namaNav', namaNav);
namaNav.$inject = [];
function namaNav() {
return {
restrict: 'E',
templateUrl: '/nama-framework/common/nav/nav.html',
controller: 'NavController',
controllerAs: 'vm',
bindToController: true,
scope: {
brand: '@'
}
};
}
}()); |
var module = angular.module("example", ["agGrid"]);
module.controller("exampleCtrl", function($scope, $http) {
var columnDefs = [
{headerName: "Gold", field: "gold", width: 100},
{headerName: "Silver", field: "silver", width: 100},
{headerName: "Bronze", field: "bronze", width: 100},
{headerName: "Total", field: "total", width: 100},
{headerName: "Age", field: "age", width: 90, checkboxSelection: true},
{headerName: "Country", field: "country", width: 120, rowGroupIndex: 0},
{headerName: "Year", field: "year", width: 90},
{headerName: "Date", field: "date", width: 110},
{headerName: "Sport", field: "sport", width: 110, rowGroupIndex: 1}
];
$scope.gridOptions = {
columnDefs: columnDefs,
rowData: null,
rowSelection: 'multiple',
groupAggFunction: groupAggFunction,
groupSelectsChildren: true,
suppressRowClickSelection: true,
groupColumnDef: {headerName: "Athlete", field: "athlete", width: 200,
cellRenderer: {
renderer: "group",
checkbox: true
}}
};
function groupAggFunction(rows) {
var sums = {
gold: 0,
silver: 0,
bronze: 0,
total: 0
};
rows.forEach(function(row) {
var data = row.data;
sums.gold += data.gold;
sums.silver += data.silver;
sums.bronze += data.bronze;
sums.total += data.total;
});
return sums;
}
$http.get("../olympicWinners.json")
.then(function(res){
$scope.gridOptions.api.setRowData(res.data);
});
});
|
import CalendarDayNamesHeader from "../base/CalendarDayNamesHeader.js";
import { template } from "../base/internal.js";
import { fragmentFrom } from "../core/htmlLiterals.js";
/**
* CalendarDayNamesHeader component in the Plain reference design system
*
* @inherits CalendarDayNamesHeader
*/
class PlainCalendarDayNamesHeader extends CalendarDayNamesHeader {
get [template]() {
const result = super[template];
result.content.append(
fragmentFrom.html`
<style>
:host {
font-size: smaller;
}
[part~="day-name"] {
padding: 0.3em;
text-align: center;
white-space: nowrap;
}
[weekend] {
color: gray;
}
</style>
`
);
return result;
}
}
export default PlainCalendarDayNamesHeader;
|
/*global describe, beforeEach, it*/
'use strict';
var assert = require('assert');
describe('video generator', function () {
it('can be imported without blowing up', function () {
var app = require('../app');
assert(app !== undefined);
});
});
|
'use strict';
module.exports = function modify(config) {
console.log('Razzle comes with React! This package is a stub.');
return config;
};
|
var path = require("path");
var webpack = require("webpack");
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var pkg = require(path.join(process.cwd(), 'package.json'));
var assetsPath = path.join(__dirname, "public","js");
var publicPath = "/public/";
var commonLoaders = [
{
test: /\.js$|\.jsx$/,
loaders: ["babel"],
include: path.join(__dirname, "app")
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
'css?sourceMap&-restructuring!' +
'autoprefixer-loader'
)
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract(
'css?sourceMap!' +
'autoprefixer-loader!' +
'less?{"sourceMap":true,"modifyVars":' + JSON.stringify(pkg.theme || {})+'}'
)
}
];
module.exports = {
// The configuration for the client
name: "browser",
/* The entry point of the bundle
* Entry points for multi page app could be more complex
* A good example of entry points would be:
* entry: {
* pageA: "./pageA",
* pageB: "./pageB",
* pageC: "./pageC",
* adminPageA: "./adminPageA",
* adminPageB: "./adminPageB",
* adminPageC: "./adminPageC"
* }
*
* We can then proceed to optimize what are the common chunks
* plugins: [
* new CommonsChunkPlugin("admin-commons.js", ["adminPageA", "adminPageB"]),
* new CommonsChunkPlugin("common.js", ["pageA", "pageB", "admin-commons.js"], 2),
* new CommonsChunkPlugin("c-commons.js", ["pageC", "adminPageC"]);
* ]
*/
context: path.join(__dirname, "app"),
entry: {
app: "./app.js"
},
output: {
// The output directory as absolute path
path: assetsPath,
// The filename of the entry chunk as relative path inside the output.path directory
filename: "bundle.js",
// The output path from the view of the Javascript
publicPath: publicPath
},
module: {
loaders: commonLoaders
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('ant.css', {
disable: false,
allChunks: true
}),
]
};
|
module.exports={A:{A:{"2":"H D G E A B EB"},B:{"2":"C p x J L N I"},C:{"2":"0 1 2 3 4 5 6 8 9 ZB BB F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y XB RB"},D:{"1":"8 9 LB GB FB bB a HB IB JB","2":"0 F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w","66":"1 2 3 4 5 6 y"},E:{"2":"F K H D G E A B C KB CB MB NB OB PB QB z SB"},F:{"1":"r s t u v w","2":"0 7 E B C J L N I O P Q R S T U V W X Y Z b c d e f g h i j TB UB VB WB z AB YB","66":"k l m n o M q"},G:{"2":"G CB aB DB cB dB eB fB gB hB iB jB kB lB"},H:{"2":"mB"},I:{"2":"BB F a nB oB pB qB DB rB sB"},J:{"2":"D A"},K:{"2":"7 A B C M z AB"},L:{"1":"a"},M:{"2":"y"},N:{"2":"A B"},O:{"2":"tB"},P:{"2":"F K uB vB"},Q:{"2":"wB"},R:{"2":"xB"}},B:7,C:"WebUSB"};
|
<Card>
<Card.Header>
<Nav variant="tabs" defaultActiveKey="#first">
<Nav.Item>
<Nav.Link href="#first">Active</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link href="#link">Link</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link href="#disabled" disabled>
Disabled
</Nav.Link>
</Nav.Item>
</Nav>
</Card.Header>
<Card.Body>
<Card.Title>Special title treatment</Card.Title>
<Card.Text>
With supporting text below as a natural lead-in to additional content.
</Card.Text>
<Button variant="primary">Go somewhere</Button>
</Card.Body>
</Card>;
|
'use strict';
/* global describe, it, beforeEach */
var jsdomHelper = require('../testHelpers/jsdomHelper');
var sinon = require('sinon');
var unexpected = require('unexpected');
var unexpectedDom = require('unexpected-dom');
var unexpectedSinon = require('unexpected-sinon');
var expect = unexpected
.clone()
.installPlugin(unexpectedDom)
.installPlugin(unexpectedSinon)
.installPlugin(require('../testHelpers/nodeListType'));
jsdomHelper();
var React = require('react');
var ReactDOM = require('react-dom');
var TestUtils = require('react-addons-test-utils');
var Select = require('../src/Select');
// The displayed text of the currently selected item, when items collapsed
var DISPLAYED_SELECTION_SELECTOR = '.Select-value';
var FORM_VALUE_SELECTOR = '.Select > input';
var PLACEHOLDER_SELECTOR = '.Select-placeholder';
class PropsWrapper extends React.Component {
constructor(props) {
super(props);
this.state = props || {};
}
setPropsForChild(props) {
this.setState(props);
}
getChild() {
return this.refs.child;
}
render() {
var Component = this.props.childComponent; // eslint-disable-line react/prop-types
return <Component {...this.state} ref="child" />;
}
}
describe('Select', () => {
var options, onChange, onInputChange;
var instance, wrapper;
var searchInputNode;
var getSelectControl = (instance) => {
return ReactDOM.findDOMNode(instance).querySelector('.Select-control');
};
var enterSingleCharacter = () =>{
TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 65, key: 'a' });
};
var pressEnterToAccept = () => {
TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 13, key: 'Enter' });
};
var pressTabToAccept = () => {
TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 9, key: 'Tab' });
};
var pressEscape = () => {
TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 27, key: 'Escape' });
};
var pressBackspace = () => {
TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 8, key: 'Backspace' });
};
var pressUp = () => {
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 38, key: 'ArrowUp' });
};
var pressDown = () => {
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' });
};
var typeSearchText = (text) => {
TestUtils.Simulate.change(searchInputNode, { target: { value: text } });
};
var clickArrowToOpen = () => {
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
TestUtils.Simulate.mouseDown(selectArrow);
};
var clickDocument = () => {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent('click', true, true);
document.dispatchEvent(clickEvent);
};
var findAndFocusInputControl = () => {
// Focus on the input, such that mouse events are accepted
var searchInstance = ReactDOM.findDOMNode(instance.refs.input);
searchInputNode = null;
if (searchInstance) {
searchInputNode = searchInstance.querySelector('input');
if (searchInputNode) {
TestUtils.Simulate.focus(searchInputNode);
}
}
};
var createControl = (props) => {
onChange = sinon.spy();
onInputChange = sinon.spy();
// Render an instance of the component
instance = TestUtils.renderIntoDocument(
<Select
onChange={onChange}
onInputChange={onInputChange}
{...props}
/>
);
findAndFocusInputControl();
return instance;
};
var createControlWithWrapper = (props) => {
onChange = sinon.spy();
onInputChange = sinon.spy();
wrapper = TestUtils.renderIntoDocument(
<PropsWrapper
childComponent={Select}
onChange={onChange}
onInputChange={onInputChange}
{...props}
/>
);
instance = wrapper.getChild();
findAndFocusInputControl();
return wrapper;
};
var defaultOptions = [
{ value: 'one', label: 'One' },
{ value: 'two', label: '222' },
{ value: 'three', label: 'Three' },
{ value: 'four', label: 'AbcDef' }
];
describe('with simple options', () => {
beforeEach(() => {
options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three' }
];
instance = createControl({
name: 'form-field-name',
value: 'one',
options: options,
simpleValue: true,
});
});
it('should assign the given name', () => {
var selectInputElement = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input')[0];
expect(ReactDOM.findDOMNode(selectInputElement).name, 'to equal', 'form-field-name');
});
it('should show the options on mouse click', function () {
TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-control'));
var node = ReactDOM.findDOMNode(instance);
expect(node, 'queried for', '.Select-option', 'to have length', 3);
});
it('should display the labels on mouse click', () => {
TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-control'));
var node = ReactDOM.findDOMNode(instance);
expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'One');
expect(node, 'queried for', '.Select-option:nth-child(2)', 'to have items satisfying', 'to have text', 'Two');
expect(node, 'queried for', '.Select-option:nth-child(3)', 'to have items satisfying', 'to have text', 'Three');
});
it('should filter after entering some text', () => {
typeSearchText('T');
var node = ReactDOM.findDOMNode(instance);
expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'Two');
expect(node, 'queried for', '.Select-option:nth-child(2)', 'to have items satisfying', 'to have text', 'Three');
expect(node, 'queried for', '.Select-option', 'to have length', 2);
});
it('should pass input value when entering text', () => {
typeSearchText('a');
enterSingleCharacter('a');
expect(onInputChange, 'was called with', 'a');
});
it('should filter case insensitively', () => {
typeSearchText('t');
var node = ReactDOM.findDOMNode(instance);
expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'Two');
expect(node, 'queried for', '.Select-option:nth-child(2)', 'to have items satisfying', 'to have text', 'Three');
expect(node, 'queried for', '.Select-option', 'to have length', 2);
});
it('should filter using "contains"', () => {
// Search 'h', should only show 'Three'
typeSearchText('h');
var node = ReactDOM.findDOMNode(instance);
expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'Three');
expect(node, 'queried for', '.Select-option', 'to have length', 1);
});
it('should accept when enter is pressed', () => {
// Search 'h', should only show 'Three'
typeSearchText('h');
pressEnterToAccept();
expect(onChange, 'was called with', 'three');
});
it('should accept when tab is pressed', () => {
// Search 'h', should only show 'Three'
typeSearchText('h');
pressTabToAccept();
expect(onChange, 'was called with', 'three');
});
describe('pressing escape', () => {
beforeEach(() => {
typeSearchText('h');
pressTabToAccept();
expect(onChange, 'was called with', 'three');
onChange.reset();
pressEscape();
});
it('should call onChange with a empty value', () => {
expect(onChange, 'was called with', null);
});
it('should clear the display', () => {
expect(ReactDOM.findDOMNode(instance), 'queried for', PLACEHOLDER_SELECTOR,
'to have text', 'Select...');
});
});
it('should focus the first value on mouse click', () => {
TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-control'));
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'One');
});
it('should move the focused value to the second value when down pressed', () => {
var selectControl = getSelectControl(instance);
TestUtils.Simulate.mouseDown(selectControl);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' });
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'Two');
});
it('should move the focused value to the second value when down pressed', () => {
var selectControl = getSelectControl(instance);
TestUtils.Simulate.mouseDown(selectControl);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' });
TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' });
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'Three');
});
it('should loop round to top item when down is pressed on the last item', () => {
var selectControl = getSelectControl(instance);
TestUtils.Simulate.mouseDown(selectControl);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' });
TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' });
TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' });
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'One');
});
it('should loop round to bottom item when up is pressed on the first item', () => {
var selectControl = getSelectControl(instance);
TestUtils.Simulate.mouseDown(selectControl);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' });
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'Three');
});
it('should move the focused value to the second item when up pressed twice', () => {
var selectControl = getSelectControl(instance);
TestUtils.Simulate.mouseDown(selectControl);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' });
TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' });
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'Two');
});
it('should clear the selection on escape', () => {
var selectControl = getSelectControl(instance);
TestUtils.Simulate.mouseDown(selectControl);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 27, key: 'Escape' });
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option');
});
it('should open the options on arrow down with the top option focused, when the options are closed', () => {
var selectControl = getSelectControl(instance);
var domNode = ReactDOM.findDOMNode(instance);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowDown' });
expect(domNode, 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'One');
});
it('should open the options on arrow up with the top option focused, when the options are closed', () => {
var selectControl = getSelectControl(instance);
var domNode = ReactDOM.findDOMNode(instance);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' });
expect(domNode, 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'One');
});
it('should close the options one the second click on the arrow', () => {
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
TestUtils.Simulate.mouseDown(selectArrow);
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'), 'to have length', 3);
TestUtils.Simulate.mouseDown(selectArrow);
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option');
});
it('should ignore a right mouse click on the arrow', () => {
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
TestUtils.Simulate.mouseDown(selectArrow, { type: 'mousedown', button: 1 });
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option');
});
describe('after mouseEnter and leave of an option', () => {
// TODO: this behaviour has changed, and we no longer lose option focus on mouse out
return;
beforeEach(() => {
// Show the options
var selectControl = getSelectControl(instance);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' });
var optionTwo = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1];
TestUtils.SimulateNative.mouseOver(optionTwo);
TestUtils.SimulateNative.mouseOut(optionTwo);
});
it('should have no focused options', () => {
var domNode = ReactDOM.findDOMNode(instance);
expect(domNode, 'to contain no elements matching', '.Select-option.is-focused');
});
it('should focus top option after down arrow pressed', () => {
var selectControl = getSelectControl(instance);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' });
var domNode = ReactDOM.findDOMNode(instance);
expect(domNode, 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'One');
});
it('should focus last option after up arrow pressed', () => {
var selectControl = getSelectControl(instance);
TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' });
var domNode = ReactDOM.findDOMNode(instance);
expect(domNode, 'queried for', '.Select-option.is-focused',
'to have items satisfying',
'to have text', 'Three');
});
});
});
describe('with values as numbers', () => {
beforeEach(() => {
options = [
{ value: 0, label: 'Zero' },
{ value: 1, label: 'One' },
{ value: 2, label: 'Two' },
{ value: 3, label: 'Three' }
];
wrapper = createControlWithWrapper({
value: 2,
name: 'field',
options: options,
simpleValue: true,
});
});
it('selects the initial value', () => {
expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR,
'to have text', 'Two');
});
it('set the initial value of the hidden input control', () => {
return; // TODO; broken test?
expect(ReactDOM.findDOMNode(wrapper).querySelector(FORM_VALUE_SELECTOR).value, 'to equal', '2' );
});
it('updates the value when the value prop is set', () => {
wrapper.setPropsForChild({ value: 3 });
expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR,
'to have text', 'Three');
});
it('updates the value of the hidden input control after new value prop', () => {
return; // TODO; broken test?
wrapper.setPropsForChild({ value: 3 });
expect(ReactDOM.findDOMNode(wrapper).querySelector(FORM_VALUE_SELECTOR).value, 'to equal', '3' );
});
it('calls onChange with the new value as a number', () => {
clickArrowToOpen();
pressDown();
pressEnterToAccept();
expect(onChange, 'was called with', 3);
});
it('supports setting the value to 0 via prop', () => {
wrapper.setPropsForChild({ value: 0 });
expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR,
'to have text', 'Zero');
});
it('supports selecting the zero value', () => {
clickArrowToOpen();
pressUp();
pressUp();
pressEnterToAccept();
expect(onChange, 'was called with', 0);
});
describe('with multi=true', () => {
beforeEach(() => {
options = [
{ value: 0, label: 'Zero' },
{ value: 1, label: 'One' },
{ value: 2, label: 'Two' },
{ value: 3, label: 'Three' },
{ value: 4, label: 'Four' }
];
wrapper = createControlWithWrapper({
value: '2,1',
options: options,
multi: true,
searchable: true
});
});
it('selects the initial value', () => {
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-value .Select-value-label',
'to satisfy', [
expect.it('to have text', 'Two'),
expect.it('to have text', 'One')
]);
});
it('calls onChange with the correct value when 1 option is selected', () => {
var removeIcons = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value .Select-value-icon');
TestUtils.Simulate.click(removeIcons[0]);
// For multi-select, the "value" (first arg) to onChange is always a string
expect(onChange, 'was called with', '1', [{ value: 1, label: 'One' }]);
});
it('supports updating the values via props', () => {
wrapper.setPropsForChild({
value: '3,4'
});
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-value .Select-value-label',
'to satisfy', [
expect.it('to have text', 'Three'),
expect.it('to have text', 'Four')
]);
});
it('supports updating the value to 0', () => {
// This test is specifically in case there's a "if (value) {... " somewhere
wrapper.setPropsForChild({
value: 0
});
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-value .Select-value-label',
'to satisfy', [
expect.it('to have text', 'Zero')
]);
});
it('calls onChange with the correct values when multiple options are selected', () => {
typeSearchText('fo');
pressEnterToAccept(); // Select 'Four'
expect(onChange, 'was called with', '2,1,4', [
{ value: 2, label: 'Two' },
{ value: 1, label: 'One' },
{ value: 4, label: 'Four' }
]);
});
});
describe('searching', () => {
let searchOptions = [
{ value: 1, label: 'One' },
{ value: 2, label: 'Two' },
{ value: 10, label: 'Ten' },
{ value: 20, label: 'Twenty' },
{ value: 21, label: 'Twenty-one' },
{ value: 34, label: 'Thirty-four' },
{ value: 54, label: 'Fifty-four' }
];
describe('with matchPos=any and matchProp=any', () => {
beforeEach(() => {
instance = createControl({
matchPos: 'any',
matchProp: 'any',
options: searchOptions
});
});
it('finds text anywhere in value', () => {
typeSearchText('1');
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to satisfy', [
expect.it('to have text', 'One'),
expect.it('to have text', 'Ten'),
expect.it('to have text', 'Twenty-one')
]);
});
it('finds text at end', () => {
typeSearchText('4');
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to satisfy', [
expect.it('to have text', 'Thirty-four'),
expect.it('to have text', 'Fifty-four')
]);
});
});
describe('with matchPos=start and matchProp=any', () => {
beforeEach(() => {
instance = createControl({
matchPos: 'start',
matchProp: 'any',
options: searchOptions
});
});
it('finds text at the start of the value', () => {
typeSearchText('1');
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to satisfy', [
expect.it('to have text', 'One'),
expect.it('to have text', 'Ten')
]);
});
it('does not match text at end', () => {
typeSearchText('4');
expect(ReactDOM.findDOMNode(instance), 'to contain elements matching',
'.Select-noresults');
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching',
'.Select-option');
});
});
describe('with matchPos=any and matchProp=value', () => {
beforeEach(() => {
instance = createControl({
matchPos: 'any',
matchProp: 'value',
options: searchOptions
});
});
it('finds text anywhere in value', () => {
typeSearchText('1');
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to satisfy', [
expect.it('to have text', 'One'),
expect.it('to have text', 'Ten'),
expect.it('to have text', 'Twenty-one')
]);
});
it('finds text at end', () => {
typeSearchText('4');
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to satisfy', [
expect.it('to have text', 'Thirty-four'),
expect.it('to have text', 'Fifty-four')
]);
});
});
describe('with matchPos=start and matchProp=value', () => {
beforeEach(() => {
instance = createControl({
matchPos: 'start',
matchProp: 'value',
options: searchOptions
});
});
it('finds text at the start of the value', () => {
typeSearchText('1');
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to satisfy', [
expect.it('to have text', 'One'),
expect.it('to have text', 'Ten')
]);
});
it('does not match text at end', () => {
typeSearchText('4');
expect(ReactDOM.findDOMNode(instance), 'to contain elements matching',
'.Select-noresults');
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching',
'.Select-option');
});
});
});
});
describe('with options and value', () => {
beforeEach(() => {
options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three' }
];
// Render an instance of the component
wrapper = createControlWithWrapper({
value: 'one',
options: options,
searchable: true
});
});
it('starts with the given value', () => {
var node = ReactDOM.findDOMNode(instance);
expect(node, 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'One');
});
it('supports setting the value via prop', () => {
wrapper.setPropsForChild({
value: 'three'
});
expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'Three');
});
it('sets the value of the hidden form node', () => {
wrapper.setPropsForChild({
value: 'three'
});
expect(ReactDOM.findDOMNode(wrapper).querySelector(FORM_VALUE_SELECTOR).value, 'to equal', 'three' );
});
it('display the raw value if the option is not available', () => {
wrapper.setPropsForChild({
value: 'something new'
});
expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'something new');
});
it('updates the display text if the option appears later', () => {
wrapper.setPropsForChild({
value: 'new'
});
wrapper.setPropsForChild({
options: [
{ value: 'one', label: 'One' },
{ value: 'two', labal: 'Two' },
{ value: 'new', label: 'New item in the options' },
{ value: 'three', label: 'Three' }
]
});
expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'New item in the options');
});
});
describe('with a disabled option', () => {
beforeEach(() => {
options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two', disabled: true },
{ value: 'three', label: 'Three' }
];
wrapper = createControlWithWrapper({
options: options,
searchable: true
});
});
it('adds the is-disabled class to the disabled option', () => {
clickArrowToOpen();
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1],
'to have attributes', {
class: 'is-disabled'
});
});
it('is not selectable by clicking', () => {
clickArrowToOpen();
TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1]);
expect(onChange, 'was not called');
expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR,
'to have text', 'Select...');
});
it('is not selectable by keyboard', () => {
clickArrowToOpen();
// Press down to get to the second option
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' });
// Check the disable option is not focused
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option.is-disabled.is-focused');
});
it('jumps over the disabled option', () => {
clickArrowToOpen();
// Press down to get to the second option
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' });
// Check the focused option is the one after the disabled option
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused',
'to have text', 'Three');
});
it('jumps back to beginning when disabled option is last option', () => {
wrapper = createControlWithWrapper({
options: [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three', disabled: true }
]
});
clickArrowToOpen();
// Down twice
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' });
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' });
// Selected option should be back to 'One'
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused',
'to have text', 'One');
});
it('skips over last option when looping round when last option is disabled', () => {
wrapper = createControlWithWrapper({
options: [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three', disabled: true }
]
});
clickArrowToOpen();
// Press up, should skip the bottom entry 'Three'...
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 38, key: 'ArrowUp' });
// ... and land on 'Two'
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused',
'to have text', 'Two');
});
it('focuses initially on the second option when the first is disabled', () => {
wrapper = createControlWithWrapper({
options: [
{ value: 'one', label: 'One', disabled: true },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three' }
]
});
clickArrowToOpen();
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused',
'to have text', 'Two');
});
it('doesn\'t focus anything when all options are disabled', () => {
wrapper = createControlWithWrapper({
options: [
{ value: 'one', label: 'One', disabled: true },
{ value: 'two', label: 'Two', disabled: true },
{ value: 'three', label: 'Three', disabled: true }
]
});
clickArrowToOpen();
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' });
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option.is-focused');
});
it('doesn\'t select anything when all options are disabled and enter is pressed', () => {
wrapper = createControlWithWrapper({
options: [
{ value: 'one', label: 'One', disabled: true },
{ value: 'two', label: 'Two', disabled: true },
{ value: 'three', label: 'Three', disabled: true }
]
});
clickArrowToOpen();
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 13, key: 'Enter' });
expect(onChange, 'was not called');
expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR,
'to have text', 'Select...');
});
it("doesn't select anything when a disabled option is the only item in the list after a search", () => {
typeSearchText('tw'); // Only 'two' in the list
pressEnterToAccept();
expect(onChange, 'was not called');
// And the menu is still open
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', DISPLAYED_SELECTION_SELECTOR);
expect(ReactDOM.findDOMNode(instance), 'queried for' , '.Select-option',
'to satisfy', [
expect.it('to have text', 'Two')
]);
});
it("doesn't select anything when a disabled option value matches the entered text", () => {
typeSearchText('two'); // Matches value
pressEnterToAccept();
expect(onChange, 'was not called');
// And the menu is still open
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', DISPLAYED_SELECTION_SELECTOR);
expect(ReactDOM.findDOMNode(instance), 'queried for' , '.Select-option',
'to satisfy', [
expect.it('to have text', 'Two')
]);
});
it("doesn't select anything when a disabled option label matches the entered text", () => {
typeSearchText('Two'); // Matches label
pressEnterToAccept();
expect(onChange, 'was not called');
// And the menu is still open
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', DISPLAYED_SELECTION_SELECTOR);
expect(ReactDOM.findDOMNode(instance), 'queried for' , '.Select-option',
'to satisfy', [
expect.it('to have text', 'Two')
]);
});
it('shows disabled results in a search', () => {
typeSearchText('t');
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options[0], 'to have text', 'Two');
expect(options[0], 'to have attributes', {
class: 'is-disabled'
});
expect(options[1], 'to have text', 'Three');
});
it('is does not close menu when disabled option is clicked', () => {
clickArrowToOpen();
TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1]);
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options.length, 'to equal', 3);
});
});
describe('with styled options', () => {
beforeEach(() => {
options = [
{ value: 'one', label: 'One', className: 'extra-one', title: 'Eins' },
{ value: 'two', label: 'Two', className: 'extra-two', title: 'Zwei' },
{ value: 'three', label: 'Three', style: { fontSize: 25 } }
];
wrapper = createControlWithWrapper({
options: options
});
});
it('uses the given className for an option', () => {
clickArrowToOpen();
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[0], 'to have attributes',
{
class: 'extra-one'
});
});
it('uses the given style for an option', () => {
clickArrowToOpen();
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[2], 'to have attributes',
{
style: { 'font-size': '25px' }
});
});
it('uses the given title for an option', () => {
clickArrowToOpen();
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1], 'to have attributes',
{
title: 'Zwei'
});
});
it('uses the given className for a single selection', () => {
typeSearchText('tw');
pressEnterToAccept();
expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR,
'to have attributes', {
class: 'extra-two'
});
});
it('uses the given style for a single selection', () => {
typeSearchText('th');
pressEnterToAccept();
expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR,
'to have attributes', {
style: {
'font-size': '25px'
}
});
});
it('uses the given title for a single selection', () => {
typeSearchText('tw');
pressEnterToAccept();
expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR,
'to have attributes', {
title: 'Zwei'
});
});
describe('with multi', () => {
beforeEach(() => {
wrapper.setPropsForChild({ multi: true });
});
it('uses the given className for a selected value', () => {
typeSearchText('tw');
pressEnterToAccept();
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-value',
'to have attributes', {
class: 'extra-two'
});
});
it('uses the given style for a selected value', () => {
typeSearchText('th');
pressEnterToAccept();
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-value',
'to have attributes', {
style: {
'font-size': '25px'
}
});
});
it('uses the given title for a selected value', () => {
typeSearchText('tw');
pressEnterToAccept();
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-value',
'to have attributes', {
title: 'Zwei'
});
});
});
});
describe('with allowCreate=true', () => {
// TODO: allowCreate hasn't been implemented yet in 1.x
return;
beforeEach(() => {
options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'got spaces', label: 'Label for spaces' },
{ value: 'gotnospaces', label: 'Label for gotnospaces' },
{ value: 'abc 123', label: 'Label for abc 123' },
{ value: 'three', label: 'Three' },
{ value: 'zzzzz', label: 'test value' }
];
// Render an instance of the component
wrapper = createControlWithWrapper({
value: 'one',
options: options,
allowCreate: true,
searchable: true,
addLabelText: 'Add {label} to values?'
});
});
it('has an "Add xyz" option when entering xyz', () => {
typeSearchText('xyz');
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-menu .Select-option',
'to have items satisfying', 'to have text', 'Add xyz to values?');
});
it('fires an onChange with the new value when selecting the Add option', () => {
typeSearchText('xyz');
TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-menu .Select-option'));
expect(onChange, 'was called with', 'xyz');
});
it('allows updating the options with a new label, following the onChange', () => {
typeSearchText('xyz');
TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-menu .Select-option'));
expect(onChange, 'was called with', 'xyz');
// Now the client adds the option, with a new label
wrapper.setPropsForChild({
options: [
{ value: 'one', label: 'One' },
{ value: 'xyz', label: 'XYZ Label' }
],
value: 'xyz'
});
expect(ReactDOM.findDOMNode(instance).querySelector(DISPLAYED_SELECTION_SELECTOR),
'to have text', 'XYZ Label');
});
it('displays an add option when a value with spaces is entered', () => {
typeSearchText('got');
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0],
'to have text', 'Add got to values?');
});
it('displays an add option when a value with spaces is entered', () => {
typeSearchText('got');
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0],
'to have text', 'Add got to values?');
});
it('displays an add option when a label with spaces is entered', () => {
typeSearchText('test');
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0],
'to have text', 'Add test to values?');
});
it('does not display the option label when an existing value is entered', () => {
typeSearchText('zzzzz');
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'),
'to have length', 1);
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-menu .Select-option',
'to have text', 'Add zzzzz to values?');
});
it('renders the existing option and an add option when an existing display label is entered', () => {
typeSearchText('test value');
// First item should be the add option (as the "value" is not in the collection)
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0],
'to have text', 'Add test value to values?');
// Second item should be the existing option with the matching label
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[1],
'to have text', 'test value');
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'),
'to have length', 2);
});
});
describe('with async options', () => {
// TODO: Need to use the new Select.Async control for this
return;
var asyncOptions;
beforeEach(() => {
asyncOptions = sinon.stub();
asyncOptions.withArgs('te').callsArgWith(1, null, {
options: [
{ value: 'test', label: 'TEST one' },
{ value: 'test2', label: 'TEST two' },
{ value: 'tell', label: 'TELL three' }
]
});
asyncOptions.withArgs('tes').callsArgWith(1, null, {
options: [
{ value: 'test', label: 'TEST one' },
{ value: 'test2', label: 'TEST two' }
]
});
});
describe('with autoload=true', () => {
beforeEach(() => {
// Render an instance of the component
wrapper = createControlWithWrapper({
value: '',
asyncOptions: asyncOptions,
autoload: true
});
});
it('calls the asyncOptions initially with autoload=true', () => {
expect(asyncOptions, 'was called with', '');
});
it('calls the asyncOptions again when the input changes', () => {
typeSearchText('ab');
expect(asyncOptions, 'was called twice');
expect(asyncOptions, 'was called with', 'ab');
});
it('shows the returned options after asyncOptions calls back', () => {
typeSearchText('te');
var optionList = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option');
expect(optionList, 'to have length', 3);
expect(optionList[0], 'to have text', 'TEST one');
expect(optionList[1], 'to have text', 'TEST two');
expect(optionList[2], 'to have text', 'TELL three');
});
it('uses the options cache when the same text is entered again', () => {
typeSearchText('te');
typeSearchText('tes');
expect(asyncOptions, 'was called times', 3);
typeSearchText('te');
expect(asyncOptions, 'was called times', 3);
});
it('displays the correct options from the cache after the input is changed back to a previous value', () => {
typeSearchText('te');
typeSearchText('tes');
typeSearchText('te');
// Double check the options list is still correct
var optionList = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option');
expect(optionList, 'to have length', 3);
expect(optionList[0], 'to have text', 'TEST one');
expect(optionList[1], 'to have text', 'TEST two');
expect(optionList[2], 'to have text', 'TELL three');
});
it('re-filters an existing options list if complete:true is provided', () => {
asyncOptions.withArgs('te').callsArgWith(1, null, {
options: [
{ value: 'test', label: 'TEST one' },
{ value: 'test2', label: 'TEST two' },
{ value: 'tell', label: 'TELL three' }
],
complete: true
});
typeSearchText('te');
expect(asyncOptions, 'was called times', 2);
typeSearchText('tel');
expect(asyncOptions, 'was called times', 2);
var optionList = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option');
expect(optionList, 'to have length', 1);
expect(optionList[0], 'to have text', 'TELL three');
});
it('rethrows the error if err is set in the callback', () => {
asyncOptions.withArgs('tes').callsArgWith(1, new Error('Something\'s wrong jim'), {
options: [
{ value: 'test', label: 'TEST one' },
{ value: 'test2', label: 'TEST two' }
]
});
expect(() => {
typeSearchText('tes');
}, 'to throw exception', new Error('Something\'s wrong jim'));
});
it('calls the asyncOptions function when the value prop changes', () => {
expect(asyncOptions, 'was called once');
wrapper.setPropsForChild({ value: 'test2' });
expect(asyncOptions, 'was called twice');
});
});
describe('with autoload=false', () => {
beforeEach(() => {
// Render an instance of the component
instance = createControl({
value: '',
asyncOptions: asyncOptions,
autoload: false
});
});
it('does not initially call asyncOptions', () => {
expect(asyncOptions, 'was not called');
});
it('calls the asyncOptions on first key entry', () => {
typeSearchText('a');
expect(asyncOptions, 'was called with', 'a');
});
});
describe('with cacheAsyncResults=false', () => {
beforeEach(() => {
// Render an instance of the component
wrapper = createControlWithWrapper({
value: '',
asyncOptions: asyncOptions,
cacheAsyncResults: false
});
// Focus on the input, such that mouse events are accepted
searchInputNode = ReactDOM.findDOMNode(instance.getInputNode()).querySelector('input');
TestUtils.Simulate.focus(searchInputNode);
});
it('does not use cache when the same text is entered again', () => {
typeSearchText('te');
typeSearchText('tes');
expect(asyncOptions, 'was called times', 3);
typeSearchText('te');
expect(asyncOptions, 'was called times', 4);
});
it('updates the displayed value after changing value and refreshing from asyncOptions', () => {
asyncOptions.reset();
asyncOptions.callsArgWith(1, null, {
options: [
{ value: 'newValue', label: 'New Value from Server' },
{ value: 'test', label: 'TEST one' }
]
});
wrapper.setPropsForChild({ value: 'newValue' });
expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR,
'to have text', 'New Value from Server');
});
});
});
describe('with async options (using promises)', () => {
var asyncOptions, callCount, callInput;
beforeEach(() => {
asyncOptions = sinon.spy((input) => {
const options = [
{ value: 'test', label: 'TEST one' },
{ value: 'test2', label: 'TEST two' },
{ value: 'tell', label: 'TELL three' }
].filter((elm) => {
return (elm.value.indexOf(input) !== -1 || elm.label.indexOf(input) !== -1);
});
return new Promise((resolve, reject) => {
input === '_FAIL'? reject('nope') : resolve({options: options});
})
});
});
describe('[mocked promise]', () => {
beforeEach(() => {
// Render an instance of the component
wrapper = createControlWithWrapper({
value: '',
asyncOptions: asyncOptions,
autoload: true
});
});
it('should fulfill asyncOptions promise', () => {
return expect(instance.props.asyncOptions(''), 'to be fulfilled');
});
it('should fulfill with 3 options when asyncOptions promise with input = "te"', () => {
return expect(instance.props.asyncOptions('te'), 'to be fulfilled with', {
options: [
{ value: 'test', label: 'TEST one' },
{ value: 'test2', label: 'TEST two' },
{ value: 'tell', label: 'TELL three' }
]
});
});
it('should fulfill with 2 options when asyncOptions promise with input = "tes"', () => {
return expect(instance.props.asyncOptions('tes'), 'to be fulfilled with', {
options: [
{ value: 'test', label: 'TEST one' },
{ value: 'test2', label: 'TEST two' }
]
});
});
it('should reject when asyncOptions promise with input = "_FAIL"', () => {
return expect(instance.props.asyncOptions('_FAIL'), 'to be rejected');
});
});
describe('with autoload=true', () => {
beforeEach(() => {
// Render an instance of the component
wrapper = createControlWithWrapper({
value: '',
asyncOptions: asyncOptions,
autoload: true
});
});
it('should be called once at the beginning', () => {
expect(asyncOptions, 'was called');
});
it('calls the asyncOptions again when the input changes', () => {
typeSearchText('ab');
expect(asyncOptions, 'was called twice');
expect(asyncOptions, 'was called with', 'ab');
});
it('shows the returned options after asyncOptions promise is resolved', (done) => {
typeSearchText('te');
return asyncOptions.secondCall.returnValue.then(() => {
setTimeout(() => {
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to satisfy', [
expect.it('to have text', 'TEST one'),
expect.it('to have text', 'TEST two'),
expect.it('to have text', 'TELL three')
]);
done();
});
});
});
it('doesn\'t update the returned options when asyncOptions is rejected', (done) => {
typeSearchText('te');
expect(asyncOptions, 'was called with', 'te');
asyncOptions.secondCall.returnValue.then(() => {
setTimeout(() => {
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to satisfy', [
expect.it('to have text', 'TEST one'),
expect.it('to have text', 'TEST two'),
expect.it('to have text', 'TELL three')
]);
// asyncOptions mock is set to reject the promise when invoked with '_FAIL'
typeSearchText('_FAIL');
expect(asyncOptions, 'was called with', '_FAIL');
asyncOptions.thirdCall.returnValue.then(null, () => {
setTimeout(() => {
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to satisfy', [
expect.it('to have text', 'TEST one'),
expect.it('to have text', 'TEST two'),
expect.it('to have text', 'TELL three')
]);
done();
});
});
});
});
});
});
describe('with autoload=false', () => {
beforeEach(() => {
// Render an instance of the component
instance = createControl({
value: '',
asyncOptions: asyncOptions,
autoload: false
});
});
it('does not initially call asyncOptions', () => {
expect(asyncOptions, 'was not called');
});
it('calls the asyncOptions on first key entry', () => {
typeSearchText('a');
expect(asyncOptions, 'was called once');
expect(asyncOptions, 'was called with', 'a');
});
});
});
describe('with multi-select', () => {
beforeEach(() => {
options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three' },
{ value: 'four', label: 'Four' }
];
// Render an instance of the component
wrapper = createControlWithWrapper({
value: '',
options: options,
searchable: true,
allowCreate: true,
multi: true
});
});
it('selects a single option on enter', () => {
typeSearchText('fo');
pressEnterToAccept();
expect(onChange, 'was called with', 'four', [{ label: 'Four', value: 'four' }]);
});
it('selects a second option', () => {
typeSearchText('fo');
pressEnterToAccept();
typeSearchText('th');
onChange.reset(); // Ignore previous onChange calls
pressEnterToAccept();
expect(onChange, 'was called with', 'four,three',
[{ label: 'Four', value: 'four' }, { label: 'Three', value: 'three' }]);
});
it('displays both selected options', () => {
typeSearchText('fo');
pressEnterToAccept();
typeSearchText('th');
pressEnterToAccept();
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label')[0],
'to have text', 'Four');
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label')[1],
'to have text', 'Three');
});
it('filters the existing selections from the options', () => {
wrapper.setPropsForChild({
value: 'four,three'
});
typeSearchText('o');
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options[0], 'to have text', 'Add "o"?');
expect(options[1], 'to have text', 'One');
expect(options[2], 'to have text', 'Two');
expect(options, 'to have length', 3); // No "Four", as already selected
});
it('removes the last selected option with backspace', () => {
typeSearchText('fo');
pressEnterToAccept();
typeSearchText('th');
pressEnterToAccept();
onChange.reset(); // Ignore previous onChange calls
pressBackspace();
expect(onChange, 'was called with', 'four', [{ label: 'Four', value: 'four' }]);
});
it('does not remove the last selected option with backspace when backspaceRemoves=false', () => {
// Disable backspace
wrapper.setPropsForChild({
backspaceRemoves: false
});
typeSearchText('fo');
pressEnterToAccept();
typeSearchText('th');
pressEnterToAccept();
onChange.reset(); // Ignore previous onChange calls
pressBackspace();
expect(onChange, 'was not called');
var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label');
expect(items[0], 'to have text', 'Four');
expect(items[1], 'to have text', 'Three');
});
it('removes an item when clicking on the X', () => {
typeSearchText('fo');
pressEnterToAccept();
typeSearchText('th');
pressEnterToAccept();
typeSearchText('tw');
pressEnterToAccept();
onChange.reset(); // Ignore previous onChange calls
var threeDeleteButton = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-icon')[1];
TestUtils.Simulate.click(threeDeleteButton);
expect(onChange, 'was called with', 'four,two', [
{ label: 'Four', value: 'four' },
{ label: 'Two', value: 'two' }
]);
});
it('uses the selected text as an item when comma is pressed', () => {
typeSearchText('fo');
pressEnterToAccept();
typeSearchText('new item');
onChange.reset();
TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 188, key: ',' });
expect(onChange, 'was called with', 'four,new item', [
{ value: 'four', label: 'Four' },
{ value: 'new item', label: 'new item' }
]);
});
describe('with late options', () => {
beforeEach(() => {
wrapper = createControlWithWrapper({
multi: true,
options: options,
value: 'one,two'
});
});
it('updates the label when the options are updated', () => {
wrapper.setPropsForChild({
options: [
{ value: 'one', label: 'new label for One' },
{ value: 'two', label: 'new label for Two' },
{ value: 'three', label: 'new label for Three' }
]
});
var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value');
expect(items[0], 'queried for', '.Select-value-label',
'to have items satisfying',
'to have text', 'new label for One');
expect(items[1], 'queried for', '.Select-value-label',
'to have items satisfying',
'to have text', 'new label for Two');
});
});
});
describe('with multi=true and searchable=false', () => {
beforeEach(() => {
options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three' },
{ value: 'four', label: 'Four' }
];
// Render an instance of the component
wrapper = createControlWithWrapper({
value: '',
options: options,
searchable: false,
multi: true
});
// We need a hack here.
// JSDOM (at least v3.x) doesn't appear to support div's with tabindex
// This just hacks that we are focused
// This is (obviously) implementation dependent, and may need to change
instance.setState({
isFocused: true
});
});
it('selects multiple options', () => {
clickArrowToOpen();
var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
TestUtils.Simulate.mouseDown(items[1]);
// The menu is now closed, click the arrow to open it again
clickArrowToOpen();
items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
TestUtils.Simulate.mouseDown(items[0]);
var selectedItems = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label');
expect(selectedItems[0], 'to have text', 'Two');
expect(selectedItems[1], 'to have text', 'One');
expect(selectedItems, 'to have length', 2);
});
it('calls onChange when each option is selected', () => {
clickArrowToOpen();
// First item
var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
TestUtils.Simulate.mouseDown(items[1]);
expect(onChange, 'was called once');
expect(onChange, 'was called with', 'two', [{ value: 'two', label: 'Two' }]);
// Second item
// The menu is now closed, click the arrow to open it again
clickArrowToOpen();
items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
TestUtils.Simulate.mouseDown(items[0]);
expect(onChange, 'was called twice');
});
it('removes the selected options from the menu', () => {
clickArrowToOpen();
var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
// Click the option "Two" to select it
expect(items[1], 'to have text', 'Two');
TestUtils.Simulate.mouseDown(items[1]);
expect(onChange, 'was called times', 1);
// Now get the list again,
// The menu is now closed, click the arrow to open it again
clickArrowToOpen();
items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(items[0], 'to have text', 'One');
expect(items[1], 'to have text', 'Three');
expect(items[2], 'to have text', 'Four');
expect(items, 'to have length', 3);
// Click first item, 'One'
TestUtils.Simulate.mouseDown(items[0]);
expect(onChange, 'was called times', 2);
// The menu is now closed, click the arrow to open it again
clickArrowToOpen();
items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(items[0], 'to have text', 'Three');
expect(items[1], 'to have text', 'Four');
expect(items, 'to have length', 2);
// Click second item, 'Four'
TestUtils.Simulate.mouseDown(items[1]);
expect(onChange, 'was called times', 3);
// The menu is now closed, click the arrow to open it again
clickArrowToOpen();
items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(items[0], 'to have text', 'Three');
expect(items, 'to have length', 1);
});
});
describe('with props', () => {
describe('className', () => {
it('assigns the className to the outer-most element', () => {
var instance = createControl({ className: 'test-class' });
expect(ReactDOM.findDOMNode(instance), 'to have attributes', {
class: 'test-class'
});
});
});
describe('clearable=true', () => {
beforeEach(() => {
var instance = createControl({
clearable: true,
options: defaultOptions,
value: 'three'
});
expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'Three');
});
describe('on pressing escape', () => {
beforeEach(() => {
pressEscape();
});
it('calls onChange with empty', () => {
expect(onChange, 'was called with', '');
});
it('resets the display value', () => {
expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'Select...');
});
it('resets the control value', () => {
expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', '');
});
});
describe('on clicking `clear`', () => {
beforeEach(() => {
TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-clear'));
});
it('calls onChange with empty', () => {
expect(onChange, 'was called with', '');
});
it('resets the display value', () => {
expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'Select...');
});
it('resets the control value', () => {
expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', '');
});
});
});
describe('clearable=false', () => {
beforeEach(() => {
var instance = createControl({
clearable: false,
options: defaultOptions,
value: 'three'
});
expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'Three');
});
it('does not render a clear button', () => {
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-clear');
});
describe('on escape', () => {
beforeEach(() => {
pressEscape();
});
it('does not call onChange', () => {
expect(onChange, 'was not called');
});
it('does not reset the display value', () => {
expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'Three');
});
it('does not reset the control value', () => {
expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', 'three');
});
});
describe('when open', () => {
beforeEach(() => {
typeSearchText('abc');
});
describe('on escape', () => {
beforeEach(() => {
pressEscape();
});
it('closes the menu', () => {
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-menu');
});
it('resets the control value to the original', () => {
expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', 'three');
});
it('renders the original display label', () => {
expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR,
'to have items satisfying', 'to have text', 'Three');
});
});
});
});
describe('clearAllText', () => {
beforeEach(() => {
instance = createControl({
multi: true,
clearable: true,
value: 'three',
clearAllText: 'Remove All Items Test Title',
clearValueText: 'Remove Value Test Title', // Should be ignored, multi=true
options: defaultOptions
});
});
it('uses the prop as the title for clear', () => {
expect(ReactDOM.findDOMNode(instance).querySelector('.Select-clear-zone'), 'to have attributes', {
title: 'Remove All Items Test Title'
});
});
});
describe('clearValueText', () => {
beforeEach(() => {
instance = createControl({
multi: false,
clearable: true,
value: 'three',
clearAllText: 'Remove All Items Test Title', // Should be ignored, multi=false
clearValueText: 'Remove Value Test Title',
options: defaultOptions
});
});
it('uses the prop as the title for clear', () => {
expect(ReactDOM.findDOMNode(instance).querySelector('.Select-clear-zone'), 'to have attributes', {
title: 'Remove Value Test Title'
});
});
});
describe('delimiter', () => {
describe('is ;', () => {
beforeEach(() => {
instance = createControl({
multi: true,
value: 'four;three',
delimiter: ';',
options: defaultOptions
});
});
it('interprets the initial options correctly', () => {
var values = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value');
expect(values[0], 'queried for', '.Select-value-label', 'to have items satisfying',
'to have text', 'AbcDef');
expect(values[1], 'queried for', '.Select-value-label', 'to have items satisfying',
'to have text', 'Three');
expect(values, 'to have length', 2);
});
it('adds an additional option with the correct delimiter', () => {
typeSearchText('one');
pressEnterToAccept();
expect(onChange, 'was called with', 'four;three;one', [
{ value: 'four', label: 'AbcDef' },
{ value: 'three', label: 'Three' },
{ value: 'one', label: 'One' }
]);
});
});
describe('is a multi-character string (`==XXX==`)', () => {
beforeEach(() => {
instance = createControl({
multi: true,
value: 'four==XXX==three',
delimiter: '==XXX==',
options: defaultOptions
});
});
it('interprets the initial options correctly', () => {
var values = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value');
expect(values[0], 'queried for', '.Select-value-label', 'to have items satisfying',
'to have text', 'AbcDef');
expect(values[1], 'queried for', '.Select-value-label', 'to have items satisfying',
'to have text', 'Three');
expect(values, 'to have length', 2);
});
it('adds an additional option with the correct delimiter', () => {
typeSearchText('one');
pressEnterToAccept();
expect(onChange, 'was called with', 'four==XXX==three==XXX==one', [
{ value: 'four', label: 'AbcDef' },
{ value: 'three', label: 'Three' },
{ value: 'one', label: 'One' }
]);
});
});
});
describe('disabled=true', () => {
beforeEach(() => {
instance = createControl({
options: defaultOptions,
value: 'three',
disabled: true,
searchable: true
});
});
it('does not render an input search control', () => {
expect(searchInputNode, 'to be null');
});
it('does not react to keyDown', () => {
TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' });
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option');
});
it('does not respond to mouseDown', () => {
TestUtils.Simulate.mouseDown(getSelectControl(instance));
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option');
});
it('does not respond to mouseDown on the arrow', () => {
TestUtils.Simulate.mouseDown(getSelectControl(instance).querySelector('.Select-arrow'));
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option');
});
it('renders the given value', () => {
expect(ReactDOM.findDOMNode(instance).querySelector(DISPLAYED_SELECTION_SELECTOR), 'to have text', 'Three');
});
});
describe('custom filterOption function', () => {
// Custom function returns true only for value "four"
var filterOption = (option) => {
if (option.value === 'four') {
return true;
}
return false;
};
var spyFilterOption;
beforeEach(() => {
spyFilterOption = sinon.spy(filterOption);
instance = createControl({
options: defaultOptions,
filterOption: spyFilterOption
});
});
it('calls the filter with each option', () => {
expect(spyFilterOption, 'was called times', 4);
expect(spyFilterOption, 'was called with', defaultOptions[0], '');
expect(spyFilterOption, 'was called with', defaultOptions[1], '');
expect(spyFilterOption, 'was called with', defaultOptions[2], '');
expect(spyFilterOption, 'was called with', defaultOptions[3], '');
});
describe('when entering text', () => {
beforeEach(() => {
spyFilterOption.reset();
typeSearchText('xyz');
});
it('calls the filterOption function for each option', () => {
expect(spyFilterOption, 'was called times', 4);
expect(spyFilterOption, 'was called with', defaultOptions[0], 'xyz');
expect(spyFilterOption, 'was called with', defaultOptions[1], 'xyz');
expect(spyFilterOption, 'was called with', defaultOptions[2], 'xyz');
expect(spyFilterOption, 'was called with', defaultOptions[3], 'xyz');
});
it('only shows the filtered option', () => {
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'),
'to have length', 1);
expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'),
'to have items satisfying',
'to have text', 'AbcDef');
});
});
});
describe('custom filterOptions function', () => {
var spyFilterOptions;
beforeEach(() => {
spyFilterOptions = sinon.stub();
spyFilterOptions.returns([
{ label: 'Return One', value: 'one' },
{ label: 'Return Two', value: 'two' }
]);
instance = createControl({
options: defaultOptions,
filterOptions: spyFilterOptions,
searchable: true
});
});
it('calls the filterOptions function initially', () => {
expect(spyFilterOptions, 'was called');
});
it('calls the filterOptions function initially with the initial options', () => {
expect(spyFilterOptions, 'was called with', defaultOptions, '');
});
it('uses the returned options', () => {
TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'));
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options[0], 'to have text', 'Return One');
expect(options[1], 'to have text', 'Return Two');
expect(options, 'to have length', 2);
});
it('calls the filterOptions function on text change', () => {
typeSearchText('xyz');
expect(spyFilterOptions, 'was called with', defaultOptions, 'xyz');
});
it('uses new options after text change', () => {
spyFilterOptions.returns([
{ value: 'abc', label: 'AAbbcc' },
{ value: 'def', label: 'DDeeff' }
]);
typeSearchText('xyz');
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options[0], 'to have text', 'AAbbcc');
expect(options[1], 'to have text', 'DDeeff');
expect(options, 'to have length', 2);
});
});
describe('ignoreCase=false', () => {
beforeEach(() => {
instance = createControl({
searchable: true,
ignoreCase: false,
options: defaultOptions
});
});
it('does not find options in a different case', () => {
typeSearchText('def');
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option');
});
it('finds options in the same case', () => {
typeSearchText('Def');
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options[0], 'to have text', 'AbcDef');
expect(options, 'to have length', 1);
});
});
describe('inputProps', () => {
beforeEach(() => {
instance = createControl({
searchable: true,
inputProps: {
inputClassName: 'extra-input-class',
className: 'extra-class-name',
id: 'search-input-id'
},
options: defaultOptions
});
});
it('passes id through to the search input box', () => {
expect(searchInputNode, 'to have attributes', {
id: 'search-input-id'
});
});
it('passes the inputClassName to the search input box', () => {
expect(searchInputNode, 'to have attributes', {
class: 'extra-input-class'
});
});
it('adds the className on to the auto-size input', () => {
expect(ReactDOM.findDOMNode(instance.getInputNode()),
'to have attributes', {
class: ['extra-class-name', 'Select-input']
});
});
describe('and not searchable', () => {
beforeEach(() => {
instance = createControl({
searchable: false,
inputProps: {
inputClassName: 'extra-input-class',
className: 'extra-class-name',
id: 'search-input-id'
},
options: defaultOptions
});
});
it('sets the className and id on the placeholder for the input', () => {
expect(ReactDOM.findDOMNode(instance).querySelector('.extra-class-name'),
'to have attributes', {
id: 'search-input-id'
});
});
});
describe('and disabled', () => {
beforeEach(() => {
instance = createControl({
searchable: true,
disabled: true,
inputProps: {
inputClassName: 'extra-input-class',
className: 'extra-class-name',
id: 'search-input-id'
},
options: defaultOptions
});
});
it('doesn\'t pass the inputProps through', () => {
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.extra-class-name');
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '#search-input-id');
});
});
});
describe('matchPos=start', () => {
beforeEach(() => {
instance = createControl({
searchable: true,
matchPos: 'start',
options: defaultOptions
});
});
it('searches only at the start', () => {
typeSearchText('o');
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options[0], 'to have text', 'One');
expect(options, 'to have length', 1);
});
});
describe('matchProp=value', () => {
beforeEach(() => {
instance = createControl({
searchable: true,
matchProp: 'value',
options: [
{ value: 'aaa', label: '111' },
{ value: 'bbb', label: '222' },
{ value: 'ccc', label: 'Three' },
{ value: 'four', label: 'Abcaaa' }
]
});
});
it('searches only the value', () => {
typeSearchText('aa'); // Matches value "three", and label "AbcDef"
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options, 'to have length', 1);
expect(options[0], 'to have text', '111');
});
});
describe('matchProp=label', () => {
beforeEach(() => {
instance = createControl({
searchable: true,
matchProp: 'label',
options: [
{ value: 'aaa', label: 'bbb' },
{ value: 'bbb', label: '222' },
{ value: 'ccc', label: 'Three' },
{ value: 'four', label: 'Abcaaa' }
]
});
});
it('searches only the value', () => {
typeSearchText('bb'); // Matches value "three", and label "AbcDef"
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options, 'to have length', 1);
expect(options[0], 'to have text', 'bbb');
});
});
describe('matchPos=start and matchProp=value', () => {
beforeEach(() => {
instance = createControl({
searchable: true,
matchProp: 'value',
matchPos: 'start',
options: [
{ value: 'aaa', label: '111' },
{ value: 'bbb', label: '222' },
{ value: 'cccaa', label: 'Three' },
{ value: 'four', label: 'aaAbca' }
]
});
});
it('searches only the value', () => {
typeSearchText('aa'); // Matches value "three", and label "AbcDef"
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options, 'to have length', 1);
expect(options[0], 'to have text', '111');
});
});
describe('matchPos=start and matchProp=label', () => {
beforeEach(() => {
instance = createControl({
searchable: true,
matchProp: 'label',
matchPos: 'start',
options: [
{ value: 'aaa', label: 'bbb' },
{ value: 'bbb', label: '222' },
{ value: 'cccbbb', label: 'Three' },
{ value: 'four', label: 'Abcbbb' }
]
});
});
it('searches only the label', () => {
typeSearchText('bb'); // Matches value "three", and label "AbcDef"
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options, 'to have length', 1);
expect(options[0], 'to have text', 'bbb');
});
});
describe('noResultsText', () => {
beforeEach(() => {
wrapper = createControlWithWrapper({
searchable: true,
options: defaultOptions,
noResultsText: 'No results unit test'
});
});
it('displays the text when no results are found', () => {
typeSearchText('DOES NOT EXIST');
expect(ReactDOM.findDOMNode(instance).querySelector('.Select-menu'),
'to have text', 'No results unit test');
});
it('supports updating the text', () => {
wrapper.setPropsForChild({
noResultsText: 'Updated no results text'
});
typeSearchText('DOES NOT EXIST');
expect(ReactDOM.findDOMNode(instance).querySelector('.Select-menu'),
'to have text', 'Updated no results text');
});
});
describe('onBlur', () => {
var onBlur;
it('calls the onBlur prop when blurring the input', () => {
onBlur = sinon.spy();
instance = createControl({
options: defaultOptions,
onBlur: onBlur
});
TestUtils.Simulate.blur(searchInputNode);
expect(onBlur, 'was called once');
});
});
describe('onFocus', () => {
var onFocus;
beforeEach(() => {
onFocus = sinon.spy();
instance = createControl({
options: defaultOptions,
onFocus: onFocus
});
});
it('calls the onFocus prop when focusing the control', () => {
expect(onFocus, 'was called once');
});
});
describe('onValueClick', () => {
var onValueClick;
beforeEach(() => {
onValueClick = sinon.spy();
instance = createControl({
options: defaultOptions,
multi: true,
value: 'two,one',
onValueClick: onValueClick
});
});
it('calls the function when clicking on a label', () => {
TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-value-label a'));
expect(onValueClick, 'was called once');
});
it('calls the function with the value', () => {
TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label a')[0]);
expect(onValueClick, 'was called with', { value: 'two', label: '222' });
});
});
describe('optionRenderer', () => {
var optionRenderer;
beforeEach(() => {
optionRenderer = (option) => {
return (
<span id={'TESTOPTION_' + option.value}>{option.label.toUpperCase()}</span>
);
};
optionRenderer = sinon.spy(optionRenderer);
instance = createControl({
options: defaultOptions,
optionRenderer: optionRenderer
});
});
it('renders the options using the optionRenderer', () => {
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
TestUtils.Simulate.mouseDown(selectArrow);
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
expect(options[0].querySelector('span'), 'to have attributes', {
id: 'TESTOPTION_one'
});
expect(options[0].querySelector('span'), 'to have text', 'ONE');
expect(options[1].querySelector('span'), 'to have attributes', {
id: 'TESTOPTION_two'
});
expect(options[1].querySelector('span'), 'to have text', '222');
});
it('calls the renderer exactly once for each option', () => {
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
TestUtils.Simulate.mouseDown(selectArrow);
expect(optionRenderer, 'was called times', 4);
});
});
describe('optionRendererDisabled', () => {
var optionRenderer;
var renderLink = (props) => {
return <a {...props} >Upgrade here!</a>;
};
var links = [
{ href: '/link' },
{ href: '/link2', target: '_blank' }
];
var ops = [
{ label: 'Disabled', value: 'disabled', disabled: true, link: renderLink(links[0]) },
{ label: 'Disabled 2', value: 'disabled_2', disabled: true, link: renderLink(links[1]) },
{ label: 'Enabled', value: 'enabled' }
];
/**
* Since we don't have access to an actual Location object,
* this method will test a string (path) by the end of global.window.location.href
* @param {string} path Ending href path to check
* @return {Boolean} Whether the location is at the path
*/
var isNavigated = (path) => {
var window_location = global.window.location.href;
return window_location.indexOf(path, window_location.length - path.length) !== -1;
};
var startUrl = 'http://dummy/startLink';
beforeEach(() => {
window.location.href = startUrl;
optionRenderer = (option) => {
return (
<span>{option.label} {option.link} </span>
);
};
optionRenderer = sinon.spy(optionRenderer);
instance = createControl({
options: ops,
optionRenderer: optionRenderer
});
});
it('disabled option link is still clickable', () => {
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
TestUtils.Simulate.mouseDown(selectArrow);
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
var link = options[0].querySelector('a');
expect(link, 'to have attributes', {
href: links[0].href
});
expect(isNavigated(links[0].href), 'to be false');
TestUtils.Simulate.click(link);
expect(isNavigated(links[0].href), 'to be true');
});
it('disabled option link with target doesn\'t navigate the current window', () => {
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
TestUtils.Simulate.mouseDown(selectArrow);
var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option');
var link = options[1].querySelector('a');
expect(link, 'to have attributes', {
href: links[1].href,
target: '_blank'
});
expect(isNavigated(startUrl), 'to be true');
TestUtils.Simulate.click(link);
expect(isNavigated(links[1].href), 'to be false');
});
});
describe('placeholder', () => {
beforeEach(() => {
wrapper = createControlWithWrapper({
value: null,
options: defaultOptions,
placeholder: 'Choose Option Placeholder test'
});
});
it('uses the placeholder initially', () => {
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder',
'to have items satisfying',
'to have text', 'Choose Option Placeholder test');
});
it('displays a selected value', () => {
wrapper.setPropsForChild({
value: 'three'
});
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder',
'to have items satisfying',
'to have text', 'Three');
});
it('returns to the default placeholder when value is cleared', () => {
wrapper.setPropsForChild({
value: 'three'
});
wrapper.setPropsForChild({
value: null
});
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder',
'to have items satisfying',
'to have text', 'Choose Option Placeholder test');
});
it('allows changing the placeholder via props', () => {
wrapper.setPropsForChild({
placeholder: 'New placeholder from props'
});
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder',
'to have items satisfying',
'to have text', 'New placeholder from props');
});
it('allows setting the placeholder to the selected value', () => {
/* This is an unlikely scenario, but given that the current
* implementation uses the placeholder to display the selected value,
* it seems prudent to check that this obscure case still works
*
* We set the value via props, then change the placeholder to the
* same as the display label for the chosen option, then reset
* the value (to null).
*
* The expected result is that the display does NOT change, as the
* placeholder is now the same as label.
*/
wrapper.setPropsForChild({
value: 'three'
});
wrapper.setPropsForChild({
placeholder: 'Three' // Label for value 'three'
});
wrapper.setPropsForChild({
value: null
});
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder',
'to have items satisfying',
'to have text', 'Three');
});
});
describe('searchingText', () => {
// TODO: Need to use the new Select.Async control for this
return;
var asyncOptions;
var asyncOptionsCallback;
beforeEach(() => {
asyncOptions = sinon.spy();
instance = createControl({
asyncOptions: asyncOptions,
autoload: false,
searchingText: 'Testing async loading...',
noResultsText: 'Testing No results found',
searchPromptText: 'Testing enter search query'
});
});
it('uses the searchingText whilst the asyncOptions are loading', () => {
clickArrowToOpen();
expect(asyncOptions, 'was not called');
typeSearchText('abc');
expect(asyncOptions, 'was called');
expect(ReactDOM.findDOMNode(instance), 'to contain elements matching', '.Select-loading');
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-searching',
'to have text', 'Testing async loading...');
});
it('clears the searchingText when results arrive', () => {
clickArrowToOpen();
typeSearchText('abc');
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-searching',
'to have text', 'Testing async loading...');
asyncOptions.args[0][1](null, {
options: [{ value: 'abc', label: 'Abc' }]
});
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-noresults');
});
it('switches the searchingText to noResultsText when options arrive, but empty', () => {
clickArrowToOpen();
typeSearchText('abc');
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-searching',
'to have text', 'Testing async loading...');
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-noresults');
asyncOptions.args[0][1](null, {
options: []
});
expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-noresults',
'to have text', 'Testing No results found');
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-searching');
});
});
describe('searchPromptText', () => {
// TODO: Need to use the new Select.Async control for this
return;
var asyncOptions;
beforeEach(() => {
asyncOptions = sinon.stub();
instance = createControl({
asyncOptions: asyncOptions,
autoload: false,
searchPromptText: 'Unit test prompt text'
});
});
it('uses the searchPromptText before text is entered', () => {
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
TestUtils.Simulate.mouseDown(selectArrow);
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-search-prompt',
'to have items satisfying',
'to have text', 'Unit test prompt text');
});
it('clears the searchPromptText when results arrive', () => {
asyncOptions.callsArgWith(1, null, {
options: [{ value: 'abcd', label: 'ABCD' }]
});
var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow');
TestUtils.Simulate.mouseDown(selectArrow);
typeSearchText('abc');
expect(asyncOptions, 'was called once');
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-prompt');
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-noresults');
});
});
describe('valueRenderer', () => {
var valueRenderer;
beforeEach(() => {
valueRenderer = (option) => {
return (
<span id={'TESTOPTION_' + option.value}>{option.label.toUpperCase()}</span>
);
};
valueRenderer = sinon.spy(valueRenderer);
instance = createControl({
options: defaultOptions,
value: 'three',
valueRenderer: valueRenderer
});
});
it('renders the value using the provided renderer', () => {
var labelNode = ReactDOM.findDOMNode(instance).querySelector('.Select-value span');
expect(labelNode, 'to have text', 'THREE');
expect(labelNode, 'to have attributes', {
id: 'TESTOPTION_three'
});
});
});
describe('valueRenderer and multi=true', () => {
var valueRenderer;
beforeEach(() => {
valueRenderer = (option) => {
return (
<span id={'TESTOPTION_' + option.value}>{option.label.toUpperCase()}</span>
);
};
valueRenderer = sinon.spy(valueRenderer);
instance = createControl({
options: defaultOptions,
value: 'three,two',
multi: true,
valueRenderer: valueRenderer
});
});
it('renders the values using the provided renderer', () => {
var labelNode = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label span');
expect(labelNode[0], 'to have text', 'THREE');
expect(labelNode[0], 'to have attributes', {
id: 'TESTOPTION_three'
});
expect(labelNode[1], 'to have text', '222');
expect(labelNode[1], 'to have attributes', {
id: 'TESTOPTION_two'
});
});
});
});
describe('clicking outside', () => {
beforeEach(() => {
instance = createControl({
options: defaultOptions
});
});
it('closes the menu', () => {
TestUtils.Simulate.mouseDown(getSelectControl(instance));
expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option',
'to have length', 4);
clickDocument();
expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option');
});
});
});
|
import markdownIt from 'markdown-it';
import _ from 'lodash';
import footnotes from 'markdown-it-footnote';
export default function (opts) {
const mergedOpts = _.assign({}, opts, { html: true, linkify: true });
const md = markdownIt(mergedOpts).use(footnotes);
if (mergedOpts.openLinksExternally) {
// Remember old renderer, if overriden, or proxy to default renderer
const defaultRender = md.renderer.rules.link_open || function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options);
};
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
const aIndex = tokens[idx].attrIndex('target');
if (aIndex < 0) {
tokens[idx].attrPush(['target', '_blank']); // add new attribute
} else {
tokens[idx].attrs[aIndex][1] = '_blank'; // replace value of existing attr
}
// pass token to default renderer.
return defaultRender(tokens, idx, options, env, self);
};
}
return md;
}
|
angular.module('app', [])
.controller('Controller', function($scope) {
$scope.hi = 'world';
});
|
'use strict';
var setPrototypeOf = require('es5-ext/object/set-prototype-of')
, mixin = require('es5-ext/object/mixin-prototypes')
, iterator = require('es6-iterator/valid-iterable')
, forOf = require('es6-iterator/for-of')
, toArray = require('es5-ext/array/to-array')
, Set = require('es6-set')
, d = require('d')
, validObservableSet = require('observable-set/valid-observable-set')
, defineProperty = Object.defineProperty, getPrototypeOf = Object.getPrototypeOf
, add = Set.prototype.add, clear = Set.prototype.clear, del = Set.prototype.delete
, SetsSet;
module.exports = SetsSet = function (multiSet, iterable) {
var sets, set;
if (!(this instanceof SetsSet)) throw new TypeError('Constructor requires \'new\'');
if (iterable != null) {
iterator(iterable);
sets = [];
forOf(iterable, function (value) {
sets.push(validObservableSet(value));
});
}
set = new Set(sets);
if (setPrototypeOf) setPrototypeOf(set, getPrototypeOf(this));
else mixin(set, getPrototypeOf(this));
defineProperty(set, '__master__', d('', multiSet));
return set;
};
if (setPrototypeOf) setPrototypeOf(SetsSet, Set);
SetsSet.prototype = Object.create(Set.prototype, {
constructor: d(SetsSet),
add: d(function (set) {
if (this.has(validObservableSet(set))) return this;
add.call(this, set);
this.__master__._onSetAdd(set);
return this;
}),
clear: d(function () {
var sets;
if (!this.size) return;
sets = toArray(this);
clear.call(this);
this.__master__._onSetsClear(sets);
}),
delete: d(function (set) {
if (!this.has(set)) return false;
del.call(this, set);
this.__master__._onSetDelete(set);
return true;
})
});
|
var gulp = require('gulp');
var argv = require('yargs').argv;
var config = require('../config.js');
var dist = config.release = !!argv.dist;
console.log('_________________________________________');
console.log('');
console.log(' Building for distribution: ' + dist);
console.log('');
gulp.task('default', ['images', 'lib', 'sass', 'watch', 'code', 'html']); |
var routes = {
"index" : {
title : "",
url : "/",
controller : main
},
"404" : {
title : "404",
url : "/404",
controller : fourohfour
}
}; |
;(function(Form) {
/**
* List editor
*
* An array editor. Creates a list of other editor items.
*
* Special options:
* @param {String} [options.schema.itemType] The editor type for each item in the list. Default: 'Text'
* @param {String} [options.schema.confirmDelete] Text to display in a delete confirmation dialog. If falsey, will not ask for confirmation.
*/
Form.editors.List = Form.editors.Base.extend({
events: {
'click [data-action="add"]': function(event) {
event.preventDefault();
this.addItem(null, true);
}
},
initialize: function(options) {
options = options || {};
var editors = Form.editors;
editors.Base.prototype.initialize.call(this, options);
var schema = this.schema;
if (!schema) throw new Error("Missing required option 'schema'");
this.template = options.template || this.constructor.template;
//Determine the editor to use
this.Editor = (function() {
var type = schema.itemType;
//Default to Text
if (!type) return editors.Text;
//Use List-specific version if available
if (editors.List[type]) return editors.List[type];
//Or whichever was passed
return editors[type];
})();
this.items = [];
},
render: function() {
var self = this,
value = this.value || [],
$ = Backbone.$;
//Create main element
var $el = $($.trim(this.template()));
//Store a reference to the list (item container)
this.$list = $el.is('[data-items]') ? $el : $el.find('[data-items]');
//Add existing items
if (value.length) {
_.each(value, function(itemValue) {
self.addItem(itemValue);
});
}
//If no existing items create an empty one, unless the editor specifies otherwise
else {
if (!this.Editor.isAsync) this.addItem();
}
this.setElement($el);
this.$el.attr('id', this.id);
this.$el.attr('name', this.key);
if (this.hasFocus) this.trigger('blur', this);
return this;
},
/**
* Add a new item to the list
* @param {Mixed} [value] Value for the new item editor
* @param {Boolean} [userInitiated] If the item was added by the user clicking 'add'
*/
addItem: function(value, userInitiated) {
var self = this,
editors = Form.editors;
//Create the item
var item = new this.constructor.Item({
list: this,
form: this.form,
schema: this.schema,
value: value,
Editor: this.Editor,
key: this.key
}).render();
var _addItem = function() {
self.items.push(item);
self.$list.append(item.el);
item.editor.on('all', function(event) {
if (event === 'change') return;
// args = ["key:change", itemEditor, fieldEditor]
var args = _.toArray(arguments);
args[0] = 'item:' + event;
args.splice(1, 0, self);
// args = ["item:key:change", this=listEditor, itemEditor, fieldEditor]
editors.List.prototype.trigger.apply(this, args);
}, self);
item.editor.on('change', function() {
if (!item.addEventTriggered) {
item.addEventTriggered = true;
this.trigger('add', this, item.editor);
}
this.trigger('item:change', this, item.editor);
this.trigger('change', this);
}, self);
item.editor.on('focus', function() {
if (this.hasFocus) return;
this.trigger('focus', this);
}, self);
item.editor.on('blur', function() {
if (!this.hasFocus) return;
var self = this;
setTimeout(function() {
if (_.find(self.items, function(item) { return item.editor.hasFocus; })) return;
self.trigger('blur', self);
}, 0);
}, self);
if (userInitiated || value) {
item.addEventTriggered = true;
}
if (userInitiated) {
self.trigger('add', self, item.editor);
self.trigger('change', self);
}
};
//Check if we need to wait for the item to complete before adding to the list
if (this.Editor.isAsync) {
item.editor.on('readyToAdd', _addItem, this);
}
//Most editors can be added automatically
else {
_addItem();
item.editor.focus();
}
return item;
},
/**
* Remove an item from the list
* @param {List.Item} item
*/
removeItem: function(item) {
//Confirm delete
var confirmMsg = this.schema.confirmDelete;
if (confirmMsg && !confirm(confirmMsg)) return;
var index = _.indexOf(this.items, item);
this.items[index].remove();
this.items.splice(index, 1);
if (item.addEventTriggered) {
this.trigger('remove', this, item.editor);
this.trigger('change', this);
}
if (!this.items.length && !this.Editor.isAsync) this.addItem();
},
getValue: function() {
var values = _.map(this.items, function(item) {
return item.getValue();
});
//Filter empty items
return _.without(values, undefined, '');
},
setValue: function(value) {
this.value = value;
this.render();
},
focus: function() {
if (this.hasFocus) return;
if (this.items[0]) this.items[0].editor.focus();
},
blur: function() {
if (!this.hasFocus) return;
var focusedItem = _.find(this.items, function(item) { return item.editor.hasFocus; });
if (focusedItem) focusedItem.editor.blur();
},
/**
* Override default remove function in order to remove item views
*/
remove: function() {
_.invoke(this.items, 'remove');
Form.editors.Base.prototype.remove.call(this);
},
/**
* Run validation
*
* @return {Object|Null}
*/
validate: function() {
if (!this.validators) return null;
//Collect errors
var errors = _.map(this.items, function(item) {
return item.validate();
});
//Check if any item has errors
var hasErrors = _.compact(errors).length ? true : false;
if (!hasErrors) return null;
//If so create a shared error
var fieldError = {
type: 'list',
message: 'Some of the items in the list failed validation',
errors: errors
};
return fieldError;
}
}, {
//STATICS
template: _.template('\
<div>\
<div data-items></div>\
<button type="button" data-action="add">Add</button>\
</div>\
', null, Form.templateSettings)
});
/**
* A single item in the list
*
* @param {editors.List} options.list The List editor instance this item belongs to
* @param {Function} options.Editor Editor constructor function
* @param {String} options.key Model key
* @param {Mixed} options.value Value
* @param {Object} options.schema Field schema
*/
Form.editors.List.Item = Form.editors.Base.extend({
events: {
'click [data-action="remove"]': function(event) {
event.preventDefault();
this.list.removeItem(this);
},
'keydown input[type=text]': function(event) {
if(event.keyCode !== 13) return;
event.preventDefault();
this.list.addItem();
this.list.$list.find("> li:last input").focus();
}
},
initialize: function(options) {
this.list = options.list;
this.schema = options.schema || this.list.schema;
this.value = options.value;
this.Editor = options.Editor || Form.editors.Text;
this.key = options.key;
this.template = options.template || this.schema.itemTemplate || this.constructor.template;
this.errorClassName = options.errorClassName || this.constructor.errorClassName;
this.form = options.form;
},
render: function() {
var $ = Backbone.$;
//Create editor
this.editor = new this.Editor({
key: this.key,
schema: this.schema,
value: this.value,
list: this.list,
item: this,
form: this.form
}).render();
//Create main element
var $el = $($.trim(this.template()));
$el.find('[data-editor]').append(this.editor.el);
//Replace the entire element so there isn't a wrapper tag
this.setElement($el);
return this;
},
getValue: function() {
return this.editor.getValue();
},
setValue: function(value) {
this.editor.setValue(value);
},
focus: function() {
this.editor.focus();
},
blur: function() {
this.editor.blur();
},
remove: function() {
this.editor.remove();
Backbone.View.prototype.remove.call(this);
},
validate: function() {
var value = this.getValue(),
formValues = this.list.form ? this.list.form.getValue() : {},
validators = this.schema.validators,
getValidator = this.getValidator;
if (!validators) return null;
//Run through validators until an error is found
var error = null;
_.every(validators, function(validator) {
error = getValidator(validator)(value, formValues);
return error ? false : true;
});
//Show/hide error
if (error){
this.setError(error);
} else {
this.clearError();
}
//Return error to be aggregated by list
return error ? error : null;
},
/**
* Show a validation error
*/
setError: function(err) {
this.$el.addClass(this.errorClassName);
this.$el.attr('title', err.message);
},
/**
* Hide validation errors
*/
clearError: function() {
this.$el.removeClass(this.errorClassName);
this.$el.attr('title', null);
}
}, {
//STATICS
template: _.template('\
<div>\
<span data-editor></span>\
<button type="button" data-action="remove">×</button>\
</div>\
', null, Form.templateSettings),
errorClassName: 'error'
});
/**
* Base modal object editor for use with the List editor; used by Object
* and NestedModal list types
*/
Form.editors.List.Modal = Form.editors.Base.extend({
events: {
'click': 'openEditor'
},
/**
* @param {Object} options
* @param {Form} options.form The main form
* @param {Function} [options.schema.itemToString] Function to transform the value for display in the list.
* @param {String} [options.schema.itemType] Editor type e.g. 'Text', 'Object'.
* @param {Object} [options.schema.subSchema] Schema for nested form,. Required when itemType is 'Object'
* @param {Function} [options.schema.model] Model constructor function. Required when itemType is 'NestedModel'
*/
initialize: function(options) {
options = options || {};
Form.editors.Base.prototype.initialize.call(this, options);
//Dependencies
if (!Form.editors.List.Modal.ModalAdapter) throw new Error('A ModalAdapter is required');
this.form = options.form;
if (!options.form) throw new Error('Missing required option: "form"');
//Template
this.template = options.template || this.constructor.template;
},
/**
* Render the list item representation
*/
render: function() {
var self = this;
//New items in the list are only rendered when the editor has been OK'd
if (_.isEmpty(this.value)) {
this.openEditor();
}
//But items with values are added automatically
else {
this.renderSummary();
setTimeout(function() {
self.trigger('readyToAdd');
}, 0);
}
if (this.hasFocus) this.trigger('blur', this);
return this;
},
/**
* Renders the list item representation
*/
renderSummary: function() {
this.$el.html($.trim(this.template({
summary: this.getStringValue()
})));
},
/**
* Function which returns a generic string representation of an object
*
* @param {Object} value
*
* @return {String}
*/
itemToString: function(value) {
var createTitle = function(key) {
var context = { key: key };
return Form.Field.prototype.createTitle.call(context);
};
value = value || {};
//Pretty print the object keys and values
var parts = [];
_.each(this.nestedSchema, function(schema, key) {
var desc = schema.title ? schema.title : createTitle(key),
val = value[key];
if (_.isUndefined(val) || _.isNull(val)) val = '';
parts.push(desc + ': ' + val);
});
return parts.join('<br />');
},
/**
* Returns the string representation of the object value
*/
getStringValue: function() {
var schema = this.schema,
value = this.getValue();
if (_.isEmpty(value)) return '[Empty]';
//If there's a specified toString use that
if (schema.itemToString) return schema.itemToString(value);
//Otherwise use the generic method or custom overridden method
return this.itemToString(value);
},
openEditor: function() {
var self = this,
ModalForm = this.form.constructor;
var form = this.modalForm = new ModalForm({
schema: this.nestedSchema,
data: this.value
});
var modal = this.modal = new Form.editors.List.Modal.ModalAdapter({
content: form,
animate: true
});
modal.open();
this.trigger('open', this);
this.trigger('focus', this);
modal.on('cancel', this.onModalClosed, this);
modal.on('ok', _.bind(this.onModalSubmitted, this));
},
/**
* Called when the user clicks 'OK'.
* Runs validation and tells the list when ready to add the item
*/
onModalSubmitted: function() {
var modal = this.modal,
form = this.modalForm,
isNew = !this.value;
//Stop if there are validation errors
var error = form.validate();
if (error) return modal.preventClose();
//Store form value
this.value = form.getValue();
//Render item
this.renderSummary();
if (isNew) this.trigger('readyToAdd');
this.trigger('change', this);
this.onModalClosed();
},
/**
* Cleans up references, triggers events. To be called whenever the modal closes
*/
onModalClosed: function() {
this.modal = null;
this.modalForm = null;
this.trigger('close', this);
this.trigger('blur', this);
},
getValue: function() {
return this.value;
},
setValue: function(value) {
this.value = value;
},
focus: function() {
if (this.hasFocus) return;
this.openEditor();
},
blur: function() {
if (!this.hasFocus) return;
if (this.modal) {
this.modal.trigger('cancel');
}
}
}, {
//STATICS
template: _.template('\
<div><%= summary %></div>\
', null, Form.templateSettings),
//The modal adapter that creates and manages the modal dialog.
//Defaults to BootstrapModal (http://github.com/powmedia/backbone.bootstrap-modal)
//Can be replaced with another adapter that implements the same interface.
ModalAdapter: Backbone.BootstrapModal,
//Make the wait list for the 'ready' event before adding the item to the list
isAsync: true
});
Form.editors.List.Object = Form.editors.List.Modal.extend({
initialize: function () {
Form.editors.List.Modal.prototype.initialize.apply(this, arguments);
var schema = this.schema;
if (!schema.subSchema) throw new Error('Missing required option "schema.subSchema"');
this.nestedSchema = schema.subSchema;
}
});
Form.editors.List.NestedModel = Form.editors.List.Modal.extend({
initialize: function() {
Form.editors.List.Modal.prototype.initialize.apply(this, arguments);
var schema = this.schema;
if (!schema.model) throw new Error('Missing required option "schema.model"');
var nestedSchema = schema.model.prototype.schema;
this.nestedSchema = (_.isFunction(nestedSchema)) ? nestedSchema() : nestedSchema;
},
/**
* Returns the string representation of the object value
*/
getStringValue: function() {
var schema = this.schema,
value = this.getValue();
if (_.isEmpty(value)) return null;
//If there's a specified toString use that
if (schema.itemToString) return schema.itemToString(value);
//Otherwise use the model
return new (schema.model)(value).toString();
}
});
})(Backbone.Form);
|
var searchData=
[
['rgb',['Rgb',['../structarctic_1_1_rgb.html',1,'arctic']]],
['rgba',['Rgba',['../structarctic_1_1easy_1_1_rgba.html',1,'arctic::easy']]]
];
|
define(function(require, exports, module) {
require('vendor/zepto/zepto');
var $ = window.Zepto;
// Zepto.js
// (c) 2010-2014 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
var touch = {},
touchTimeout,
tapTimeout,
swipeTimeout,
longTapTimeout,
longTapDelay = 750,
gesture;
function swipeDirection(x1, x2, y1, y2) {
return Math.abs(x1 - x2) >=
Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
}
function longTap() {
longTapTimeout = null;
if (touch.last) {
touch.el.trigger('longTap');
touch = {}
}
}
function cancelLongTap() {
if (longTapTimeout) clearTimeout(longTapTimeout);
longTapTimeout = null;
}
function cancelAll() {
if (touchTimeout) clearTimeout(touchTimeout);
if (tapTimeout) clearTimeout(tapTimeout);
if (swipeTimeout) clearTimeout(swipeTimeout);
if (longTapTimeout) clearTimeout(longTapTimeout);
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null;
touch = {}
}
function isPrimaryTouch(event) {
return (event.pointerType == 'touch' ||
event.pointerType == event.MSPOINTER_TYPE_TOUCH)
&& event.isPrimary;
}
function isPointerEventType(e, type) {
return (e.type == 'pointer' + type ||
e.type.toLowerCase() == 'mspointer' + type);
}
$(document).ready(function() {
var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType;
if ('MSGesture' in window) {
gesture = new MSGesture();
gesture.target = document.body;
}
$(document)
.on('MSGestureEnd', function(e) {
var swipeDirectionFromVelocity =
e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;
if (swipeDirectionFromVelocity) {
touch.el.trigger('swipe');
touch.el.trigger('swipe' + swipeDirectionFromVelocity);
}
})
.on('touchstart MSPointerDown pointerdown', function(e) {
if ((_isPointerType = isPointerEventType(e, 'down')) && !isPrimaryTouch(e)) return;
firstTouch = _isPointerType ? e : e.touches[0];
if (e.touches && e.touches.length === 1 && touch.x2) {
// Clear out touch movement data if we have it sticking around
// This can occur if touchcancel doesn't fire due to preventDefault, etc.
touch.x2 = undefined;
touch.y2 = undefined;
}
now = Date.now();
delta = now - (touch.last || now);
touch.el = $('tagName' in firstTouch.target ?
firstTouch.target : firstTouch.target.parentNode);
touchTimeout && clearTimeout(touchTimeout);
touch.x1 = firstTouch.pageX;
touch.y1 = firstTouch.pageY;
if (delta > 0 && delta <= 250) touch.isDoubleTap = true;
touch.last = now;
longTapTimeout = setTimeout(longTap, longTapDelay);
// adds the current touch contact for IE gesture recognition
if (gesture && _isPointerType) gesture.addPointer(e.pointerId);
})
.on('touchmove MSPointerMove pointermove', function(e) {
if ((_isPointerType = isPointerEventType(e, 'move')) && !isPrimaryTouch(e)) return
firstTouch = _isPointerType ? e : e.touches[0];
cancelLongTap();
touch.x2 = firstTouch.pageX;
touch.y2 = firstTouch.pageY;
deltaX += Math.abs(touch.x1 - touch.x2);
deltaY += Math.abs(touch.y1 - touch.y2);
})
.on('touchend MSPointerUp pointerup', function(e) {
if ((_isPointerType = isPointerEventType(e, 'up')) && !isPrimaryTouch(e)) return;
cancelLongTap();
// swipe
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
(touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))
swipeTimeout = setTimeout(function() {
touch.el.trigger('swipe');
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
touch = {}
}, 0);
// normal tap
else if ('last' in touch)
// don't fire tap when delta position changed by more than 30 pixels,
// for instance when moving to a point and back to origin
if (deltaX < 30 && deltaY < 30) {
// delay by one tick so we can cancel the 'tap' event if 'scroll' fires
// ('tap' fires before 'scroll')
tapTimeout = setTimeout(function() {
// trigger universal 'tap' with the option to cancelTouch()
// (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
var event = $.Event('tap');
event.cancelTouch = cancelAll;
touch.el.trigger(event);
// trigger double tap immediately
if (touch.isDoubleTap) {
if (touch.el) touch.el.trigger('doubleTap');
touch = {}
}
// trigger single tap after 250ms of inactivity
else {
touchTimeout = setTimeout(function() {
touchTimeout = null;
if (touch.el) touch.el.trigger('singleTap');
touch = {}
}, 250)
}
}, 0)
} else {
touch = {}
}
deltaX = deltaY = 0;
})
// when the browser window loses focus,
// for example when a modal dialog is shown,
// cancel all ongoing events
.on('touchcancel MSPointerCancel pointercancel', cancelAll);
// scrolling the window indicates intention of the user
// to scroll, not tap or swipe, so cancel all ongoing events
$(window).on('scroll', cancelAll);
});
['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',
'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName) {
$.fn[eventName] = function(callback) {
return this.on(eventName, callback)
}
});
}); |
/*
FusionCharts JavaScript Library - Tree Map Chart
Copyright FusionCharts Technologies LLP
License Information at <http://www.fusioncharts.com/license>
@version 3.11.0
*/
FusionCharts.register("module",["private","modules.renderer.js-treemap",function(){function U(c){return c?c.replace(/^#*/,"#"):"#E5E5E5"}function z(c,b,d){this.label=c;this.value=parseFloat(b,10);this.colorValue=parseFloat(d,10);this.prev=this.next=void 0;this.meta={}}function M(){this._b=[];this._css=void 0;this.rangeOurEffectApplyFn=function(){};this.statePointerLow={value:void 0,index:void 0};this.statePointerHigh={value:void 0,index:void 0}}var ca,da,$,ea,K=this.hcLib,V=K.chartAPI,N=Math,R=N.max,
fa=N.round,la=N.tan,ga=N.min,ma=N.PI,ha=K.extend2,Q=this.window,N=K.Raphael,ia=K.graphics,W=ia.convertColor,ja=ia.getLightColor,I=this.raiseEvent,C=K.pluckNumber,F=K.pluck,na=K.each,aa=K.BLANKSTRING,oa="rgba(192,192,192,"+(/msie/i.test(Q.navigator.userAgent)&&!Q.opera?.002:1E-6)+")",Q=!/fusioncharts\.com$/i.test(Q.location.hostname);N.addSymbol({backIcon:function(c,b,d){--d;var a=b+d,g=a-d/2,s=c+d,q=g-d;return["M",c,b-d,"L",c-d,b,c,a,c,g,s,g,s,q,s-d,q,"Z"]},homeIcon:function(c,b,d){--d;var a=2*d,
g=c-d,s=g+a/6,q=b+d,D=s+a/4,l=q-d/2,v=D+a/6,t=l+d/2,u=v+a/4,f=t-d;return["M",c,b-d,"L",g,b,s,b,s,q,D,q,D,l,v,l,v,t,u,t,u,f,u+a/6,f,"Z"]}});z.prototype.constructor=z;z.prototype.getCSSconf=function(){return this.cssConf};z.prototype.getPath=function(){return this.path};z.prototype.setPath=function(){var c=this.getParent();this.path=(c?c.getPath():[]).concat(this)};z.prototype.addChild=function(c){c instanceof z&&(this.next=this.next||[],[].push.call(this.next,c),c.setParent(this));return this.next};
z.prototype.getChildren=function(){return this.next};z.prototype.addChildren=function(c,b){var d=this.getChildren()||(this.next=[]),a=d.length;b||(b=a-1);d.splice(b>a-1?a-1:0>b?0:b,0,c);c.setParent(this)};z.prototype.getDepth=function(){return this.meta.depth};z.prototype.isLeaf=function(c){return(c?this.getDepth()<c:!0)&&this.next};z.prototype.setParent=function(c){c instanceof z&&(this.prev=c);return this};z.prototype.getSiblingCount=function(c){var b,d=0,a=this;if(this instanceof z){b=this.getParent();
if(c){for(;a;)(a=a.getSibling(c))&&(d+=1);return d}if(b)return b.getChildren().length}};z.prototype.getParent=function(){return this.prev};z.prototype.getLabel=function(){return this.label};z.prototype.getValue=function(){return this.value};z.prototype.setValue=function(c,b){this.value=b?this.value+c:c};z.prototype.getColorValue=function(){return this.colorValue};z.prototype.getSibling=function(c){c=c.toLowerCase();var b=this.getParent(),d=this.getLabel(),a,g;if(b)for(b=b.getChildren(),a=0;a<b.length;a++)if(g=
b[a],g=g.getLabel(),g===d)switch(c){case "left":return b[a-1];case "right":return b[a+1]}};z.prototype.setMeta=function(c,b){this.meta[c]=b};z.prototype.setDepth=function(c){this.meta.depth=c};z.prototype.getMeta=function(c){return c?this.meta[c]:this.meta};M.prototype.constructor=M;M.prototype.resetPointers=function(){this.statePointerLow={value:void 0,index:void 0};this.statePointerHigh={value:void 0,index:void 0}};M.prototype.setRangeOutEffect=function(c,b){this._css=c;this.rangeOurEffectApplyFn=
b};M.prototype.addInBucket=function(c){var b=this._b,d=c.getColorValue(),a=0,g=b.length-1;if(d){a:{for(var s,q;a<=g;)if(s=(a+g)/2|0,q=b[s],q=q.getColorValue(),q<d)a=s+1;else if(q>d)g=s-1;else{d=s;break a}d=~g}b.splice(Math.abs(d),0,c)}};M.prototype.moveLowerShadePointer=function(c){var b=this._b,d,a,g,s=this.statePointerLow;d=s.index;a=s.value;var q=!1;d=void 0!==d?d:0;a=void 0!==a?a:Number.NEGATIVE_INFINITY;if(c!==a){if(a<=c){for(;;){g=(a=b[d++])?a.getColorValue():0;if(c<g||!a)break;q=!0;a.rangeOutEffect=
this._css;this.rangeOurEffectApplyFn.call(a,this._css)}d=q?d-2:d-1}else{for(;;){g=(a=b[d--])?a.getColorValue():0;if(c>=g||!a)break;a.cssConf=a.cssConf||{};q=!0;delete a.rangeOutEffect;a.cssConf.opacity=1;this.rangeOurEffectApplyFn.call(a,a.cssConf)}d=q?d+2:d+1}s.index=d;s.value=c}};M.prototype.moveHigherShadePointer=function(c){var b=this._b,d=b.length,a,g,s=this.statePointerHigh;g=s.index;a=s.value;var q=!1,d=void 0!==g?g:d-1;a=void 0!==a?a:Number.POSITIVE_INFINITY;if(c!==a){if(a>c){for(;;){g=(a=
b[d--])?a.getColorValue():0;if(c>=g||!a)break;q=!0;a.rangeOutEffect=this._css;this.rangeOurEffectApplyFn.call(a,this._css)}d=q?d+2:d+1}else{for(;;){g=(a=b[d++])?a.getColorValue():0;if(c<g||!a)break;a.cssConf=a.cssConf||{};q=!0;delete a.rangeOutEffect;a.cssConf.opacity=1;this.rangeOurEffectApplyFn.call(a,a.cssConf)}d=q?d-2:d-1}s.index=d;s.value=c}};V("treemap",{friendlyName:"TreeMap",standaloneInit:!0,hasGradientLegend:!0,creditLabel:Q,defaultDatasetType:"treemap",applicableDSList:{treemap:!0},addData:function(){var c=
this._ref.algorithmFactory,b=Array.prototype.slice.call(arguments,0);b.unshift("addData");b.unshift(this._getCleanValue());c.realTimeUpdate.apply(this,b)},removeData:function(){var c=this._ref.algorithmFactory,b=Array.prototype.slice.call(arguments,0);b.unshift("deleteData");b.unshift(this._getCleanValue());c.realTimeUpdate.apply(this,b)},_createToolBox:function(){var c,b,d,a,g=this.components;c=g.chartMenuBar;c&&c.drawn||(V.mscartesian._createToolBox.call(this),c=g.tb,b=c.getAPIInstances(c.ALIGNMENT_HORIZONTAL),
d=b.Symbol,b=g.chartMenuBar.componentGroups[0],a=new d("backIcon",!1,(c.idCount=c.idCount||0,c.idCount++),c.pId),c=new d("homeIcon",!1,c.idCount++,c.pId),b.addSymbol(c,!0),b.addSymbol(a,!0),g.toolbarBtns={back:a,home:c})},_getCleanValue:function(){var c=this.components.numberFormatter;return function(b){return c.getCleanValue(b)}},_createDatasets:function(){var c=this.components,b=this.jsonData,d=b.dataset,d=b.data||d&&d[0].data,a=this.defaultDatasetType,g=[];d&&d.length||this.setChartMessage();na(d,
function(a){a.vline||g.push(a)});b={data:g};this.config.categories=g;c=c.dataset||(c.dataset=[]);d?a&&(d=FusionCharts.get("component",["dataset",a]))&&(c[0]?(c[0].JSONData=g[0],c[0].configure()):(this._dsInstance=d=new d,c.push(d),d.chart=this,d.init(b))):this.setChartMessage()},init:function(){var c={},b={},d={};this._ref={afAPI:ca(c,b,d),algorithmFactory:da(c,b,d),containerManager:ea(c,b,d),treeOpt:$};V.guageBase.init.apply(this,arguments)}},V.guageBase);FusionCharts.register("component",["dataset",
"TreeMap",{type:"treemap",pIndex:2,customConfigFn:"_createDatasets",init:function(c){this.JSONData=c.data[0];this.components={};this.conf={};this.graphics={elemStore:{rect:[],label:[],highlight:[],hot:[],polypath:[]}};this.configure()},configure:function(){var c,b=this.chart,d=b.components,a=this.conf,b=b.jsonData.chart;a.metaTreeInf={};a.algorithm=(b.algorithm||"squarified").toLowerCase();a.horizontalPadding=C(b.horizontalpadding,5);a.horizontalPadding=0>a.horizontalPadding?0:a.horizontalPadding;
a.verticalPadding=C(b.verticalpadding,5);a.verticalPadding=0>a.verticalPadding?0:a.verticalPadding;a.showParent=C(b.showparent,1);a.showChildLabels=C(b.showchildlabels,0);a.highlightParentsOnHover=C(b.highlightparentsonhover,0);a.defaultParentBGColor=F(b.defaultparentbgcolor,void 0);a.defaultNavigationBarBGColor=F(b.defaultnavigationbarbgcolor,a.defaultParentBGColor);a.showTooltip=C(b.showtooltip,1);a.baseFontSize=C(b.basefontsize,10);a.baseFontSize=1>a.baseFontSize?1:a.baseFontSize;a.labelFontSize=
C(b.labelfontsize,void 0);a.labelFontSize=1>a.labelFontSize?1:a.labelFontSize;a.baseFont=F(b.basefont,"Verdana, Sans");a.labelFont=F(b.labelfont,void 0);a.baseFontColor=F(b.basefontcolor,"#000000").replace(/^#?([a-f0-9]+)/ig,"#$1");a.labelFontColor=F(b.labelfontcolor,void 0);a.labelFontColor&&(a.labelFontColor=a.labelFontColor.replace(/^#?([a-f0-9]+)/ig,"#$1"));a.labelFontBold=C(b.labelfontbold,0);a.labelFontItalic=C(b.labelfontitalic,0);a.plotBorderThickness=C(b.plotborderthickness,1);a.plotBorderThickness=
0>a.plotBorderThickness?0:5<a.plotBorderThickness?5:a.plotBorderThickness;a.plotBorderColor=F(b.plotbordercolor,"#000000").replace(/^#?([a-f0-9]+)/ig,"#$1");a.tooltipSeparationCharacter=F(b.tooltipsepchar,",");a.plotToolText=F(b.plottooltext,"");a.parentLabelLineHeight=C(b.parentlabellineheight,12);a.parentLabelLineHeight=0>a.parentLabelLineHeight?0:a.parentLabelLineHeight;a.labelGlow=C(b.labelglow,1);a.labelGlowIntensity=C(b.labelglowintensity,100)/100;a.labelGlowIntensity=0>a.labelGlowIntensity?
0:1<a.labelGlowIntensity?1:a.labelGlowIntensity;a.labelGlowColor=F(b.labelglowcolor,"#ffffff").replace(/^#?([a-f0-9]+)/ig,"#$1");a.labelGlowRadius=C(b.labelglowradius,2);a.labelGlowRadius=0>a.labelGlowRadius?0:10<a.labelGlowRadius?10:a.labelGlowRadius;a.btnResetChartTooltext=F(b.btnresetcharttooltext,"Back to Top");a.btnBackChartTooltext=F(b.btnbackcharttooltext,"Back to Parent");a.rangeOutBgColor=F(b.rangeoutbgcolor,"#808080").replace(/^#?([a-f0-9]+)/ig,"#$1");a.rangeOutBgAlpha=C(b.rangeoutbgalpha,
100);a.rangeOutBgAlpha=1>a.rangeOutBgAlpha||100<a.rangeOutBgAlpha?100:a.rangeOutBgAlpha;c=C(b.maxdepth);a.maxDepth=void 0!==c?R(c,1):void 0;c=a.showNavigationBar=C(b.shownavigationbar,1);a.slicingMode=F(b.slicingmode,"alternate");a.navigationBarHeight=C(b.navigationbarheight);a.navigationBarHeightRatio=C(b.navigationbarheightratio);a.navigationBarBorderColor=F(b.navigationbarbordercolor,a.plotBorderColor).replace(/^#?([a-f0-9]+)/ig,"#$1");a.navigationBarBorderThickness=c?C(b.navigationbarborderthickness,
a.plotBorderThickness):0;a.seperatorAngle=C(b.seperatorangle)*(ma/180);d.postLegendInitFn({min:0,max:100});a.isConfigured=!0},draw:function(){var c=this.conf,b=this.chart,d=b.config,a=b.components,g=d.canvasLeft,s=d.canvasRight,q=d.canvasBottom,D=d.canvasTop,l=a.paper,v=b.graphics,t=v.trackerGroup,u,f,B,h,n,d=c.metaTreeInf,m=this.graphics.elemStore,x={},p,e,k,a=a.gradientLegend,w,y=b._ref,X=y.afAPI.visibilityController,r=b.get("config","animationObj"),A=r.duration||0,Y=r.dummyObj,O=r.animObj,S=r.animType,
Z,ba,E,z,r=y.containerManager,y=y.algorithmFactory;for(f in m){Z=m[f];E=0;for(z=Z.length;E<z;E++)(ba=Z[E])&&ba.remove&&ba.remove();Z.length=0}r.remove();u=v.datasetGroup=v.datasetGroup||l.group("dataset");f=v.datalabelsGroup=v.datalabelsGroup||l.group("datalabels").insertAfter(u);B=v.lineHot=v.lineHot||l.group("line-hot",t);h=v.labelHighlight=v.labelHighlight||l.group("labelhighlight",f);n=v.floatLabel=v.floatLabel||l.group("labelfloat",f).insertAfter(h);c.colorRange=a.colorRange;d.effectiveWidth=
s-g;d.effectiveHeight=q-D;d.startX=g;d.startY=D;p=d.effectiveWidth/2;e=d.effectiveHeight/2;p=d.effectiveWidth/2;e=d.effectiveHeight/2;x.drawPolyPath=function(a,e){var c,b;c=(x.graphicPool(!1,"polyPathItem")||(b=l.path(u))).attr({path:a._path}).animateWith(Y,O,{path:a.path},A,S);c.css(e);b&&m.polypath.push(b);return c};x.drawRect=function(a,c,b,d){var n,h,w={},f={},t;for(n in a)h=a[n],0>h&&(a[n]=0,f.visibility="hidden");ha(w,a);w.x=p;w.y=e;w.height=0;w.width=0;k=x.graphicPool(!1,"plotItem")||(t=l.rect(u));
k.attr(b&&(b.x||b.y)&&b||w);k.attr(d);k.animateWith(Y,O,a,A,S,X.controlPostAnimVisibility);k.css(c).toFront();k.css(f);t&&m.rect.push(t);return k};x.drawText=function(a,b,k,d,w){var f={},t,v,r=x.graphicPool(!1,"labelItem")||(t=l.text(n)),y=x.graphicPool(!1,"highlightItem")||(v=l.text(h)),ka=k.textAttrs;k=k.highlightAttrs;ha(f,ka);delete f.fill;f["stroke-linejoin"]="round";r.attr({x:d.x||p,y:d.y||e,fill:"#000000"}).css(ka);r.attr(w);a=0>b.x||0>b.y?aa:a;r.animateWith(Y,O,{text:a,x:b.x,y:b.y},A,S);y.attr({text:a,
x:d.x||p,y:d.y||e,stroke:c.labelGlow?"#ffffff":oa}).css(f).css(k);y.attr(w);y.animateWith(Y,O,{x:b.x,y:b.y},A,S);m.label.push(t);m.highlight.push(v);return{label:r,highlightMask:y}};x.drawHot=function(a,c){var e;e=a.plotItem||{};var b=a.rect,k,d,n;for(d in b)n=b[d],0>n&&(b[d]=0);e=e.tracker=l.rect(B).attr(b).attr({cursor:"pointer",fill:"rgba(255, 255, 255, 0)",stroke:"none"});for(k in c)b=c[k],e[k].apply(e,b);m.hot.push(e);return e};x.disposeItems=function(a,e){var c,b,m,k=e||"plotItem labelItem hotItem highlightItem polyPathItem pathlabelItem pathhighlightItem stackedpolyPathItem stackedpathlabelItem stackedpathhighlightItem".split(" ");
for(c=0;c<k.length;c+=1)m=k[c],(b=a[m])&&x.graphicPool(!0,m,b,a.rect),b&&b.hide(),a[m]=void 0};x.disposeChild=function(){var a,e=function(){return a.disposeItems},c=function(a,b){var m,k;e(a);for(m=0;m<(a.getChildren()||[]).length;m++)k=a.getChildren(),m=c(k[m],m);return b};return function(b){var m=b.getParent();a||(a=this,e=e());m?a.disposeChild(m):c(b,0)}}();x.graphicPool=function(){var a={};return function(e,c,b){var m=a[c];m||(m=a[c]=[]);"hotItem"!==c&&"pathhotItem"!==c||b.remove();if(e)m.push(b);
else if(e=m.splice(0,1)[0])return e.show(),e}}();x.disposeComplimentary=function(a){var e,c;e=a.getParent();var b=a.getSiblingCount("left");e&&(c=e.getChildren(),e=c.splice(b,1)[0],this.disposeChild(a),c.splice(b,0,e));this.removeLayers()};x.removeLayers=function(){var a,e,c,b;c=m.hot;b=c.length;for(a=0;a<b;a++)(e=c[a])&&e.remove();c.length=0};y.init(c.algorithm,!0,c.maxDepth);b=y.plotOnCanvas(this.JSONData,void 0,b._getCleanValue());r.init(this,d,x,void 0,b);r.draw();w=y.applyShadeFiltering({fill:c.rangeOutBgColor,
opacity:.01*c.rangeOutBgAlpha},function(a){this.plotItem&&this.plotItem.css(a)});a&&a.enabled&&(a.resetLegend(),a.clearListeners());a.notifyWhenUpdate(function(a,e){w.call(this,{start:a,end:e})},this);c.isConfigured=!1}}]);ca=function(c,b,d){function a(a,c,b){this.node=a;this.bucket=c?new M:void 0;this.cleansingFn=b}var g,s,q,D;a.prototype.get=function(){var a=this.order,c=this.bucket,b=this.cleansingFn;return function f(d,h){var n,m,x,p;m=["label","value","data","svalue"];if(d)for(p in n=new z(d.label,
b(d.value),b(d.svalue)),x=d.data||[],0===x.length&&c&&c.addInBucket(n),n.setDepth(h),d)-1===m.indexOf(p)&&n.setMeta(p,d[p]);a&&(x=a(x));for(m=0;m<x.length;m++)p=x[m],p=f(p,h+1),n.addChild(p);return n}(this.node,0)};a.prototype.getBucket=function(){return this.bucket};a.prototype.getMaxDepth=function(){return s};g=function(a,c){function b(a){this.iterAPI=a}var d=c&&c.exception,f,g;b.prototype.constructor=b;b.prototype.initWith=function(a){return this.iterAPI(a)};f=(new b(function(a){var c=a,b=[],x=
!1;b.push(c);return{next:function(a){var c,k;if(!x){c=b.shift();if(d&&c===d&&(c=b.shift(),!c)){x=!0;return}(k=(a=void 0!==a?c.getDepth()>=a?[]:c.getChildren():c.getChildren())&&a.length||0)&&[].unshift.apply(b,a);0===b.length&&(x=!0);return c}},reset:function(){x=!1;c=a;b.length=0;b.push(c)}}})).initWith(a);g=(new b(function(a){var c=a,b=[],d=[],f=!1;b.push(c);d.push(c);return{next:function(){var a,c,d;if(!f)return c=b.shift(),(d=(a=c.getChildren())&&a.length||0)&&[].push.apply(b,a),0===b.length&&
(f=!0),c},nextBatch:function(){var a,c;if(!f)return a=d.shift(),(c=(a=a.getChildren())&&a.length||0)&&[].push.apply(d,a),0===b.length&&(f=!0),a},reset:function(){f=!1;c=a;b.length=0;b.push(c)}}})).initWith(a);return{df:f,bf:g}};D=function(){function a(){this.con={}}var c={},b;a.prototype.constructor=a;a.prototype.get=function(a){return this.con[a]};a.prototype.set=function(a,c){this.con[a]=c};a.prototype["delete"]=function(a){return delete this.con[a]};return{getInstance:function(d){var f;return(f=
c[d])?b=f:b=c[d]=new a}}}();b=function(){var a=[],c,b=!1,d={visibility:"visible"};return{controlPreAnimVisibility:function(d,B){var h,n,m;if(d){for(n=d;;){n=n.getParent();if(!n)break;h=n}h=g(h,{exception:d});for(h=h.df;;){n=h.next();if(!n)break;m=n.overAttr||(n.overAttr={});m.visibility="hidden";a.push(n)}c=B||d.getParent();b=!1;return a}},displayAll:function(d){var B;if(d){d=g(d.getParent()||d);for(d=d.df;;){B=d.next();if(!B)break;B=B.overAttr||(B.overAttr={});B.visibility="visible"}c=void 0;a.length=
0;b=!1}},controlPostAnimVisibility:function(){var f,B;if(!b&&(b=!0,c)){B=g(c);for(B=B.df;;){f=B.next(s);if(!f)break;if(f=f.dirtyNode)f&&f.plotItem.attr(d),(f=f&&f.textItem)&&f.label&&f.label.attr(d),f&&f.label&&f.highlightMask.attr(d)}c=void 0;a.length=0}}}}();c.AbstractTreeMaker=a;c.iterator=g;c.initConfigurationForlabel=function(a,c,b){var d=a.x,f=a.y,g=c/2,h=b.showParent?0:1,n=b.showChildLabels;return function(a,x,p,e){p=!1;var k={x:void 0,y:void 0,width:void 0,height:void 0},w={},y=0,l={},r={},
A,l=a.meta;if(a)return a.isLeaf(s)||(p=!0),w.label=a.getLabel(),k.width=x.width-2*d,k.x=x.x+x.width/2,a=x.height-2*f,!p&&a<c&&(k.height=-1),!e&&p?(k.height=n?k.height?k.height:x.height-2*f:-1,k.y=x.y+x.height/2):h?(k.y=-1,c=f=0,A="hidden"):(k.height=k.height?k.height:c,k.y=x.y+f+g),y+=2*f,y+=c,w.rectShiftY=y,w.textRect=k,b.labelGlow?(r["stroke-width"]=b.labelGlowRadius,r.opacity=b.labelGlowIntensity,r.stroke=b.labelGlowColor,r.visibility="hidden"===A?"hidden":"visible"):r.visibility="hidden",l={fontSize:b.labelFontSize||
b.baseFontSize,fontFamily:b.labelFont||b.baseFont,fill:l&&l.fontcolor&&U(l.fontcolor)||b.labelFontColor||b.baseFontColor,fontWeight:b.labelFontBold&&"bold",fontStyle:b.labelFontItalic&&"italic",visibility:A},{conf:w,attr:l,highlight:r}}};c.context=D;c.mapColorManager=function(a,c,b){var d=U(b?a.defaultNavigationBarBGColor:a.defaultParentBGColor);return function(b,g,h){g={};var n=b.cssConf,m=b.meta,m=m.fillcolor?U(m.fillcolor):void 0,x=b.getParent(),p;p=b.getColorValue();a.isLegendEnabled=!0;p=a.isLegendEnabled&&
p===p?c.getColorByValue(p)&&"#"+c.getColorByValue(p)||U(c.rangeOutsideColor):void 0;b.isLeaf(s)?g.fill=m||p||d:(b=(b=(x?x:b).cssConf)&&b.fill,g.fill=m||(p?p:b));g.stroke=h?a.navigationBarBorderColor:a.plotBorderColor;g.strokeWidth=h?a.navigationBarBorderThickness:a.plotBorderThickness;g["stroke-dasharray"]="none";!h&&n&&"--"===n["stroke-dasharray"]&&(g["stroke-dasharray"]=n["stroke-dasharray"],g.strokeWidth=n.strokeWidth);return g}};c.abstractEventRegisterer=function(a,b,g,u){function f(a){var c=
{},b,e;for(b in A)e=A[b],c[e]=a[b];return c}var s=b.chart,h=s.components,n=h.toolbarBtns,m=s.chartInstance,x=b.conf,p=h.gradientLegend,e=a.drawTree,k=u.disposeChild,w,y=arguments,X,r,A={colorValue:"svalue",label:"name",value:"value",rect:"metrics"};X=c.context.getInstance("ClickedState");s._intSR={};s._intSR.backToParent=w=function(a){var b=this,d=b,n=d&&b.getParent(),h=c.context.getInstance("ClickedState").get("VisibileRoot")||{};a?I("beforedrillup",{node:b,withoutHead:!x.showParent},m,void 0,function(){n&&
(h.state="drillup",h.node=[{virginNode:c.getVisibleRoot()},n],k(d),e.apply(n,y));I("drillup",{node:b,withoutHead:!x.showParent,drillUp:w,drillUpToTop:r},m);b=b&&b.getParent()},function(){I("drillupcancelled",{node:b,withoutHead:!x.showParent},m)}):(n&&(h.state="drillup",h.node=[{virginNode:c.getVisibleRoot()},n],k(d),e.apply(n,y)),b=b&&b.getParent())};s._intSR.resetTree=r=function(a){for(var b=this,d=b&&b.getParent(),n,h=c.context.getInstance("ClickedState").get("VisibileRoot")||{};d;)n=d,d=d.getParent();
a?I("beforedrillup",{node:b,withoutHead:!x.showParent},m,void 0,function(){n&&(h.state="drillup",h.node=[{virginNode:c.getVisibleRoot()},n],k(n),e.apply(n,y),I("drillup",{node:b,sender:s.fusionCharts,withoutHead:!x.showParent,drillUp:w,drillUpToTop:r},m))},function(){I("drillupcancelled",{node:b,withoutHead:!x.showParent},m)}):n&&(h.state="drillup",h.node=[{virginNode:c.getVisibleRoot()},n],k(n),e.apply(n,y))};return{click:function(b,c){var e=b.virginNode,h,y,g;I("dataplotclick",f(b.virginNode),m);
if(y=e.getParent()){if(e===c)g=y,h="drillup";else{if(e.next)g=e;else if(g=y,c===g){h=void 0;return}h="drilldown"}p&&p.enabled&&p.resetLegend();a.applyShadeFiltering.reset();h&&I("before"+h,{node:g,withoutHead:!x.showParent},m,void 0,function(){X.set("VisibileRoot",{node:b,state:h});k.call(u,g);q=g;d.draw();I(h,{node:g,withoutHead:!x.showParent,drillUp:w,drillUpToTop:r},m)},function(){I(h+"cancelled",{node:g,withoutHead:!x.showParent},m)});n.back&&n.back.attachEventHandlers({click:w.bind(g)});n.home&&
n.home.attachEventHandlers({click:r.bind(g)})}},mouseover:function(a){var b=f(a.virginNode);I("dataplotrollover",b,m,void 0,void 0,function(){I("dataplotrollovercancelled",b,m)})},mouseout:function(a){var b=f(a.virginNode);I("dataplotrollout",f(a.virginNode),m,void 0,void 0,function(){I("dataplotrolloutcancelled",b,m)})}}};c.setMaxDepth=function(a){return s=a};c.getVisibleRoot=function(){return q};c.setVisibleRoot=function(a){q=a};c.visibilityController=b;return c};da=function(c,b){function d(){D.apply(this,
arguments)}function a(a,b,m){v=new d(a,u,b);a=v.get();!1!==m&&(t=a);c.setVisibleRoot(a);return a}function g(){var a=q[l],d;b.realTimeUpdate=s.apply(this,arguments);d=Array.prototype.slice.call(arguments,0);d.unshift(a);a.drawTree.apply(c.getVisibleRoot(),d)}function s(){var a,b,c=q[l];b=Array.prototype.slice.call(arguments,0);b.unshift(c);a=b.slice(-1)[0];return function(){var d=Array.prototype.slice.call(arguments,0),p=d.shift(),e=d.shift();$(t,function(a){c.drawTree.apply(a||t,b)},a,p)[e].apply(this,
d)}}var q,D=c.AbstractTreeMaker,l,v,t,u,f,B;q={sliceanddice:{areaBaseCalculator:function(a,b){return function(c,d,p){var e,k,w={},y,g,r,f=e=0;if(c){p&&(e=p.textMargin||e);f=e;p=c.getParent();e=c.getSibling("left");if(p){k=p.getValue();r=p.rect;y=r.height-2*b-f;g=r.width-2*a;w.effectiveRect={height:y,width:g,x:r.x+a,y:r.y+b+f};w.effectiveArea=y*g;w.ratio=c.getValue()/k;if(e)return d.call(c,w,e,p);w.lastIsParent=!0;return d.call(c,w,p)}return null}}},applyShadeFiltering:function(a,b,c){a.setRangeOutEffect(b,
c);this.applyShadeFiltering.reset=function(){a.resetPointers()};return function(b){a.moveLowerShadePointer(b.start);a.moveHigherShadePointer(b.end)}},alternateModeManager:function(){return function(a,b){var c,d,g,e,k,w=a.effectiveArea*a.ratio;d=a.effectiveRect;var y=b.rect;a.lastIsParent?(e=d.x,k=d.y,c=d.height,d=d.width,g=this.isDirectionVertical=!0):(c=d.height+d.y-(y.height+y.y),d=d.width+d.x-(y.width+y.x),g=this.isDirectionVertical=!b.isDirectionVertical);g?(d=w/c,e=void 0!==e?e:y.x,k=void 0!==
k?k:y.y+y.height):(c=w/d,e=void 0!==e?e:y.x+y.width,k=void 0!==k?k:y.y);return{height:c,width:d,x:e,y:k}}},horizontalVerticalManager:function(a){var b=Boolean("vertical"===a?!0:!1);return function(a,c,d){var e,k,w,g=a.effectiveArea*a.ratio,h=a.effectiveRect,f=c.rect;a.lastIsParent?(k=h.x,w=h.y,a=h.height,e=h.width,c=this.isDirectionVertical=!c.isDirectionVertical):(a=h.height+h.y-(f.height+f.y),e=h.width+h.x-(f.width+f.x),c=this.isDirectionVertical=!d.isDirectionVertical);(c=b?c:!c)?(0===a&&(a=h.height,
k=void 0!==k?k:f.x+f.width,w=void 0!==w?w:f.y),e=g/a,k=void 0!==k?k:f.x,w=void 0!==w?w:f.y+f.height):(0===e&&(e=h.width,k=void 0!==k?k:f.x,w=void 0!==w?w:f.y+f.height),a=g/e,k=void 0!==k?k:f.x+f.width,w=void 0!==w?w:f.y);return{height:a,width:e,x:k,y:w}}},drawTree:function(a,b,d,g){var p=b.chart,e=p.components,k=e.numberFormatter,e=e.toolbarBtns,w=g.drawRect,y=g.drawText,v=g.drawHot,r=d.horizontalPadding,A=d.verticalPadding,t=b.chart.linkedItems.smartLabel,l=c.iterator,s=l(this).df,q,u=a.areaBaseCalculator(r,
A),E=b.conf,D=E.highlightParentsOnHover,z,C=c.context,r=c.visibilityController,L=c.mapColorManager(E,b.conf.colorRange),A=c.abstractEventRegisterer.apply(c,arguments),F=A.click,I=A.mouseover,G=A.mouseout,A=E.slicingMode,J=a["alternate"===A?"alternateModeManager":"horizontalVerticalManager"](A),A=p._intSR,H,l=C.getInstance("ClickedState").get("VisibileRoot")||{};(H=l.node)&&l.state&&("drillup"===l.state.toLowerCase()?H instanceof Array?r.controlPreAnimVisibility(H[0].virginNode,H[1]):r.controlPreAnimVisibility(H.virginNode):
r.displayAll(l.node.virginNode));z=c.initConfigurationForlabel({x:5,y:5},E.parentLabelLineHeight,E);for(r=q=s.next(B=c.setMaxDepth(this.getDepth()+f));r.getParent();)r=r.getParent();E.showNavigationBar?(e.home.hide(),e.back.hide()):r!=q?(e.home.show(),e.back.show()):(e.home.hide(),e.back.hide());t.useEllipsesOnOverflow(p.config.useEllipsesWhenOverflow);t.setStyle(E._setStyle={fontSize:(E.labelFontSize||E.baseFontSize)+"px",fontFamily:E.labelFont||E.baseFont,lineHeight:1.2*(E.labelFontSize||E.baseFontSize)+
"px"});p=A.backToParent;r=A.resetTree;e.back&&e.back.attachEventHandlers({click:p.bind(q)});e.home&&e.home.attachEventHandlers({click:r.bind(q)});(function P(a,b){var c,d,e,n,m,f,h,p;f={};var r,l,A={},O={};h={};var H="",M,N;a&&(M=k.yAxis(a.getValue()),N=k.sYAxis(a.getColorValue()),a.setPath(),c=a.rect||{},d=a.textRect||{},e=a.rect={},h=a.textRect={},e.width=b.width,e.height=b.height,e.x=b.x,e.y=b.y,h=L(a),(l=a.plotItem)&&g.graphicPool(!0,"plotItem",l,c),l=a.plotItem=w(e,h,c,a.overAttr),a.cssConf=
h,p=z(a,e),n=p.conf,f.textMargin=n.rectShiftY,h=a.textRect=n.textRect,r=t.getSmartText(n.label,h.width,h.height).text,a.plotItem=l,(n=a.labelItem)?(m=a.highlightItem,g.graphicPool(!0,"labelItem",n,c),g.graphicPool(!0,"highlightItem",m,c)):d=d||{},d=y(r,h,{textAttrs:p.attr,highlightAttrs:p.highlight},d,a.overAttr),a.labelItem=d.label,a.highlightItem=d.highlightMask,A.virginNode=a,A.plotItem=l,A.textItem=d,A.virginNode.dirtyNode=A,a.getColorValue()&&(H=E.tooltipSeparationCharacter+N),A.toolText=K.parseTooltext(E.plotToolText,
[1,2,3,119,122],{label:a.getLabel(),formattedValue:M,formattedsValue:N},{value:a.getValue(),svalue:a.getColorValue()})||a.getLabel()+E.tooltipSeparationCharacter+M+H,A.rect=e,O.hover=[function(){var a,b,c;c=C.getInstance("hover");b=this.virginNode;a=D&&!b.next?(a=b.getParent())?a:b:this.virginNode;c.set("element",a);c=W(ja(a.cssConf.fill,80),60);a.plotItem.tracker.attr({fill:c});I(this)}.bind(A),function(){var a,b;a=C.getInstance("hover").get("element");b=W(a.cssConf.fill||"#fff",0);a.plotItem.tracker.attr({fill:b});
G(this)}.bind(A)],O.tooltip=[A.toolText],O.click=[function(){F(this,q)}.bind(A)],(e=a.hotItem)&&g.graphicPool(!0,"hotItem",e,c),e=a.hotItem=v(A,O),c=s.next(B),f=u(c,J,f),P(c,f))})(q,d)}},squarified:{orderNodes:function(){return this.sort(function(a,b){return parseFloat(a.value,10)<parseFloat(b.value,10)?1:-1})},areaBaseCalculator:function(a,b){return function(c,d,f){var e={},k,w=k=0,g,l;if(c&&0!==c.length)return f&&(k=f.textMargin||k),w=k,g=c[0],(c=g.getParent())?(l=c.rect,f=l.height-2*b-w,k=l.width-
2*a,e.effectiveRect={height:f,width:k,x:l.x+a,y:l.y+b+w},e.effectiveArea=f*k,d.call(g,e,c)):null}},layoutManager:function(){function a(b,c){this.totalValue=c;this._rHeight=b.height;this._rWidth=b.width;this._rx=b.x;this._ry=b.y;this._rTotalArea=b.height*b.width;this.nodes=[];this._prevAR=void 0;this._rHeight<this._rWidth&&(this._hSegmented=!0)}a.prototype.constructor=a;a.prototype.addNode=function(a){var b=this._rTotalArea,c,d,e,k,f,g,h,r=this._hSegmented,l=this._rx,v=this._ry,t,s,q,u,E=0;this.nodes.push(a);
e=0;for(d=this.nodes.length;e<d;e++)E+=parseFloat(this.nodes[e].getValue(),10);c=E/this.totalValue*b;r?(b=this._rHeight,d=c/b,t=l+d,s=v,q=this._rHeight,u=this._rWidth-d):(d=this._rWidth,b=c/d,t=l,s=v+b,q=this._rHeight-b,u=this._rWidth);e=0;for(k=this.nodes.length;e<k;e++)a=this.nodes[e],f=a.getValue(),g=f/E*c,a.hRect=a.rect||{},a._hRect=a._rect||{},f=a.rect={},r?(f.width=h=d,f.height=h=g/h,f.x=l,f.y=v,v+=h):(f.height=h=b,f.width=h=g/h,f.x=l,f.y=v,l+=h),g=R(f.height,f.width),f=ga(f.height,f.width),
a.aspectRatio=g/f;if(1<this.nodes.length){if(this.prevAR<a.aspectRatio){this.nodes.pop().rect={};e=0;for(d=this.nodes.length;e<d;e++)this.nodes[e].rect=1===d&&this.nodes[e].firstPassed?this.nodes[e]._hRect:this.nodes[e].hRect,r=this.nodes[e]._rect={},l=this.nodes[e].rect,r.width=l.width,r.height=l.height,r.x=l.x,r.y=l.y;return!1}}else a&&(r=a._rect={},l=a.rect,r.width=l.width,r.height=l.height,r.x=l.x,r.y=l.y,a.firstPassed=!0);this.prevAR=a.aspectRatio;this.height=b;this.width=d;this.getNextLogicalDivision=
function(){return{height:q,width:u,x:t,y:s}};return a};return{RowLayout:a}}(),applyShadeFiltering:function(a,b,c){a.setRangeOutEffect(b,c);this.applyShadeFiltering.reset=function(){a.resetPointers()};return function(b){a.moveLowerShadePointer(b.start);a.moveHigherShadePointer(b.end)}},drawTree:function(a,b,d,g){var l=b.chart,e=l.components,k=e.numberFormatter,e=e.toolbarBtns,w=a.areaBaseCalculator(d.horizontalPadding,d.verticalPadding),y=a.layoutManager.RowLayout,v=b.chart.linkedItems.smartLabel,
r=g.drawRect,t=g.drawText,s=g.drawHot,q=c.iterator,u=q(this).bf,z,D=b.conf,E=D.highlightParentsOnHover,C,F=c.context,I=c.mapColorManager(D,b.conf.colorRange),q=c.abstractEventRegisterer.apply(c,arguments),L=q.click,M=q.mouseover,N=q.mouseout,q=l._intSR,G=c.visibilityController,J,H;J=F.getInstance("ClickedState").get("VisibileRoot")||{};(H=J.node)&&J.state&&("drillup"===J.state.toLowerCase()?H instanceof Array?G.controlPreAnimVisibility(H[0].virginNode,H[1]):G.controlPreAnimVisibility(H.virginNode):
G.displayAll(J.node.virginNode));C=c.initConfigurationForlabel({x:5,y:5},D.parentLabelLineHeight,D);for(u=z=u.next(B=c.setMaxDepth(this.getDepth()+f));u.getParent();)u=u.getParent();D.showNavigationBar?(e.home.hide(),e.back.hide()):u!=z?(e.home.show(),e.back.show()):(e.home.hide(),e.back.hide());v.useEllipsesOnOverflow(l.config.useEllipsesWhenOverflow);v.setStyle(D._setStyle={fontSize:(D.labelFontSize||D.baseFontSize)+"px",fontFamily:D.labelFont||D.baseFont,lineHeight:1.2*(D.labelFontSize||D.baseFontSize)+
"px"});l=q.backToParent;q=q.resetTree;e.back&&e.back.attachEventHandlers({click:l.bind(z)});e.home&&e.home.attachEventHandlers({click:q.bind(z)});(function P(a,b){var c,d={},e,f,h,l,m,n,q=0,p,u,G,H;n={};var J;p={};u={};l={};var O="",S,R;if(a){S=k.yAxis(a.getValue());R=k.sYAxis(a.getColorValue());a.setPath();if(c=a.__initRect)d.x=c.x,d.y=c.y,d.width=c.width,d.height=c.height;h=a.textRect||{};c=a.rect=a.__initRect={};l=a.textRect={};c.width=b.width;c.height=b.height;c.x=b.x;c.y=b.y;l=I(a);(G=a.plotItem)&&
g.graphicPool(!0,"plotItem",G,d);G=a.plotItem=r(c,l,d,a.overAttr);a.cssConf=l;J=C(a,c);e=J.conf;n.textMargin=e.rectShiftY;l=a.textRect=e.textRect;H=v.getSmartText(e.label,l.width,l.height).text;(f=a.labelItem)?(e=a.highlightItem,g.graphicPool(!0,"labelItem",f,d),g.graphicPool(!0,"highlightItem",e,d)):h=h||{};h=t(H,l,{textAttrs:J.attr,highlightAttrs:J.highlight},h,a.overAttr);a.labelItem=h.label;a.highlightItem=h.highlightMask;a.plotItem=G;p.virginNode=a;p.plotItem=G;p.textItem=h;p.virginNode.dirtyNode=
p;a.getColorValue()&&(O=D.tooltipSeparationCharacter+R);p.toolText=D.showTooltip?K.parseTooltext(D.plotToolText,[1,2,3,119,122],{label:a.getLabel(),formattedValue:S,formattedsValue:R},{value:a.getValue(),svalue:a.getColorValue()})||a.getLabel()+D.tooltipSeparationCharacter+S+O:aa;p.rect=c;u.hover=[function(){var a,b,c;c=F.getInstance("hover");b=this.virginNode;a=E&&!b.next?(a=b.getParent())?a:b:this.virginNode;c.set("element",a);c=a.cssConf;c=W(c.fill&&ja(c.fill,80),60);a.plotItem.tracker.attr({fill:c});
M(this)}.bind(p),function(){var a,b;a=F.getInstance("hover").get("element");b=W(a.cssConf.fill||"#fff",0);a.plotItem.tracker.attr({fill:b});N(this)}.bind(p)];u.tooltip=[p.toolText];u.click=[function(){L(this,z)}.bind(p)];(c=a.hotItem)&&g.graphicPool(!0,"hotItem",c,d);c=a.hotItem=s(p,u);if(m=void 0!==B?a.getDepth()>=B?void 0:a.getChildren():a.getChildren())for(p=w(m,function(a,b){var c,d,e=0,k,f,g=[];c=new y({width:a.effectiveRect.width,height:a.effectiveRect.height,x:a.effectiveRect.x,y:a.effectiveRect.y},
b.getValue());for(d=m.length;e++!==d;)k=m[e-1],f=c.addNode(k),!1===f?(c=c.getNextLogicalDivision(),c=new y(c,b.getValue()-q),e--):(q+=parseFloat(k.getValue(),10),g.push(k));return g},n),d=0,n=p.length;d<n;d++)u=p[d],P(u,u.rect)}})(z,d)}}};d.prototype=Object.create(D.prototype);d.prototype.constructor=D;d.prototype.order=function(a){var b=q[l],c=b.orderNodes;return c?c.apply(a,[b]):a};b.init=function(a,b,d){l=a;u=b;f=c.setMaxDepth(d);return q[l]};b.plotOnCanvas=function(b,c,d){t=a(b,d);return g};b.applyShadeFiltering=
function(a,b){var c,d;d=q[l].applyShadeFiltering(v.getBucket(),a,b);return function(a){c=Array.prototype.slice.call(arguments,0);c.unshift(a);d.apply(v.getBucket(),c)}};b.setTreeBase=function(a){return a&&(t=a)};b.realTimeUpdate=s;b.makeTree=a;return b};$=function(c,b,d,a){function g(a){var b,d=0;b=c;if(!a.length)return c;for(;b;){b=s.call(b,a[d]);if(d===a.length-1&&b)return q=b.getValue(),b;d+=1}}function s(a){var b,c,d,g=this.getChildren()||[],f=g.length;for(b=0;b<f;b+=1)if(d=g[b],d.label.toLowerCase().trim()===
a.toLowerCase().trim()){c=d;break}return c}var q;return{deleteData:function(a,c){var v=g(a),t=(void 0).iterator(v).df,u=v&&v.getParent(),f=v&&v.getSiblingCount("left"),s=u&&u.getChildren(),h=(void 0).getVisibleRoot();if(v&&u){s.splice(f,1);for(v===h&&(h=v.getParent()||h);v;)d.disposeItems(v),v=t.next();for(;u;)u.setValue(-q,!0),u=u.getParent();c&&b(h)}},addData:function(c,d,q,t){for(var u,f,s,h=0,n=!0,m=(void 0).getVisibleRoot();c.length;)if(u=c.pop(),u=(void 0).makeTree(u,a,!1),h=u.getValue(),f=
g(d||[]))for(f.getChildren()||(s=f.getValue(),n=!1),f.addChildren(u,t);f;)f.setValue(h,n),s&&(h-=s,s=void 0,n=!0),f=f.getParent();q&&b(m)}}};ea=function(c,b,d){function a(){}function g(a){var b=t.plotBorderThickness;l.apply(c.getVisibleRoot(),[z,{width:a.effectiveWidth,height:a.effectiveHeight,x:a.startX,y:a.startY,horizontalPadding:t.horizontalPadding,verticalPadding:t.verticalPadding},u]);t.plotBorderThickness=b}function s(a,b,c){var d=a.width,f=a.height,g=t.seperatorAngle/2;a=["M",a.x,a.y];var h=
C(g?f/2*(1-la(g)):c,15);c=function(a){return{both:["h",d,"v",a,"h",-d,"v",-a],right:["h",d,"v",a,"h",-d,"l",h,-a/2,"l",-h,-a/2],no:["h",d,"l",h,a/2,"l",-h,a/2,"h",-d,"l",h,-a/2,"l",-h,-a/2],left:["h",d,"l",h,a/2,"l",-h,a/2,"h",-d,"v",-a]}};return{path:a.concat(c(f)[b]),_path:a.concat(c(0)[b]),offset:h}}function q(){var a=Array.prototype.splice.call(arguments,0);a.push(!0);h("navigationBar").apply(this,a)}var z,l,v,t,u,f,B=function(a,b){var f,g,h=c.mapColorManager(t,t.colorRange,!0),l=function(){var a;
return{get:function(b,c,d){var e={y:b.startY,height:b.effectiveHeight};c=f[c];var k=c.getParent();e.x=a||(a=b.startX);a=d?a+(e.width=b.effectiveWidth*(c.getValue()/k.getValue())):a+(e.width=b.effectiveWidth/g);return e},resetAllocation:function(){a=void 0}}}(),m=c.initConfigurationForlabel({x:5,y:5},t.parentLabelLineHeight,t),p=u.drawPolyPath,q=u.drawText,C=u.drawHot,B={navigationHistory:{path:"polyPathItem",label:"pathlabelItem",highlightItem:"pathhighlightItem",hotItem:"pathhotItem"}},F=z.chart,
E=F.components.gradientLegend,F=F.linkedItems.smartLabel,I=function(a){return function(){var b=c.context.getInstance("ClickedState").get("VisibileRoot")||{};b.state="drillup";b.node=[{virginNode:c.getVisibleRoot()},a];E&&E.enabled&&E.resetLegend();d.draw([a,a,a])}},M=function(){return function(){}},N=function(){return function(){}},L,K,T,G,J,H,Q=t._setStyle,P;L=n.get().navigationBar;G=2*x("navigationBar");Q=ga(L*v.effectiveHeight-(G+6),Q.fontSize.replace(/\D+/g,""));L=Q+"px";B.stacked={path:"stacked"+
B.navigationHistory.path,label:"stacked"+B.navigationHistory.label,highlightItem:"stacked"+B.navigationHistory.highlightItem,hotItem:"stacked"+B.navigationHistory.hotItem};l.resetAllocation();(function(a){var b=c.getVisibleRoot();f=a?b.getChildren():b.getPath()||[].concat(b);f.pop();g=f.length})(b);F.setStyle({fontSize:L,lineHeight:L});for(L=0;L<g;L+=1)G=f[L],J=l.get(a,L,b),K=(T=s(J,b?"both":1===g?"both":0===L?"left":L<g-1?"no":"right")).offset,G[B[b?"stacked":"navigationHistory"].path]=p(T,h(G,!0,
!0),L),T=m(G,J,!1,!0),H=T.conf,P=H.textRect,P.width-=2*K,P.y=J.y+J.height/2,K=F.getSmartText(H.label,P.width,R(Q,P.height)).text,K=q(K,P,{textAttrs:T.attr,highlightAttrs:T.highlight},{y:J.height/10,"font-size":t._setStyle.fontSize,"font-family":t._setStyle.fontFamily},(b?"stacked":"")+"path"),G[B[b?"stacked":"navigationHistory"].label]=K.label,G[B[b?"stacked":"navigationHistory"].highlightItem]=K.highlightMask,G[B[b?"stacked":"navigationHistory"].hotItem]=C({rect:J},{click:[I(G,b)],hover:[M(G),N()],
tooltip:[t.showTooltip?G.getLabel():aa]})},h=function(a){return{treeMap:g,navigationBar:B,stackedNavigation:q}[a]},n=function(){var a={treeMap:1,navigationBar:0,stackedNavigation:0};return{set:function(b){var c=C(t.navigationBarHeightRatio,t.navigationBarHeight/v.effectiveHeight,.15),d=t.labelFontSize?R(t.labelFontSize,t.baseFontSize):t.baseFontSize,f=2*x("navigationBar"),c=R((6+d+f)/v.effectiveHeight,c);.1>c?c=.1:.15<c&&(c=.15);t.navigationBarHeightRatio=c;a=b?{treeMap:1-c,navigationBar:c,stackedNavigation:0}:
{treeMap:1,navigationBar:0,stackedNavigation:0}},get:function(){return a}}}(),m=0,x=function(a){var b=t.plotBorderThickness,c=t.navigationBarBorderThickness;return t.verticalPadding+("navigationBar"===a?c:b)},p=function(a){var b=v.effectiveWidth,c=v.effectiveHeight,d=x(a);a=n.get()[a];1<=m&&(m=0);m+=a;return{effectiveHeight:fa(a*c*100)/100-d,effectiveWidth:b,startX:v.startX,startY:v.startY+d+fa((m-a)*c*100)/100}};a.prototype.constructor=a;a.prototype.init=function(a,b){(this.conf||(this.conf={})).name=
a.name;this.setDrawingArea(a.drawingAreaMeasurement);this.draw=this.draw(b)};a.prototype.setDrawingArea=function(a){this.conf.drawingAreaMeasurement=a};a.prototype.draw=function(a){return function(){var b=this.conf;0<b.drawingAreaMeasurement.effectiveHeight&&a(b.drawingAreaMeasurement)}};a.prototype.eventCallback=function(){};f=function(){var b=[];return{get:function(){return b},set:function(c){var d;c?(d=new a,d.init({name:c.type,drawingAreaMeasurement:c.drawingArea},c.drawFn),b.push(d)):b.length=
0;return b}}}();d.init=function(){var a,b=["navigationBar","treeMap","stackedNavigation"];a=Array.prototype.slice.call(arguments,0);z=a[0];v=a[1];t=z.conf;u=a[2];l=a[4];for(f.get().length>=b.length&&f.set();b.length;)a=b.shift(),f.set({type:a,drawFn:h(a),drawingArea:p(a)})};d.draw=function(a){var b,g,h;b=c.getVisibleRoot();u.disposeChild(b);a&&(b=a[1]);b.getParent()?t.showNavigationBar&&d.heightProportion.set(!0):d.heightProportion.set(!1);g=f.get();for(b=0;b<g.length;b+=1)h=g[b],h.setDrawingArea(p(h.conf.name)),
a&&c.setVisibleRoot(a[b]),h.draw()};d.heightProportion=n;d.remove=function(){var a=c.getVisibleRoot();a&&u.disposeChild(a)};return d}}]);
|
var lightstep = require("../../../..");
var FileTransport = require("../../../util/file_transport");
var path = require('path');
var reportFilename = path.join(__dirname, "../../../results/on_exit_child.json");
Tracer = new lightstep.Tracer({
access_token : "{your_access_token}",
component_name : "lightstep-tracer/unit-test/on_exit",
override_transport : new FileTransport(reportFilename),
});
for (var i = 0; i < 10; i++) {
var span = Tracer.startSpan("test_span_" + i);
span.log({"log_index" : i});
span.finish();
}
|
/* RequireJS Module Dependency Definitions */
define([
'app',
'jquery',
'marionette',
'handlebars',
'collections/TopBarMessagesCollection',
'text!templates/main_topbar.html',
'foundation-reveal',
'foundation-topbar'
], function (App, $, Marionette, Handlebars, TopBarMessagesCollection, template){
"use strict";
return Marionette.ItemView.extend({
//Template HTML string
template: Handlebars.compile(template),
collection: new TopBarMessagesCollection(),
initialize: function(options){
this.options = options;
},
events: {
"click #logoutButton": "logout",
"click #topbar_settingsButton": "settingsShow",
"click #topbar_profileButton": "myprofileShow",
"click #topbar_message-seeall": "messageSeeall",
"click #topbar_forumsButton": "forumsShow",
"click #topbar_leaderboardsButton": "leaderboardsShow",
"click #topbar_announcementsButton": "announcementsShow",
"click #topbar_adminButton": "adminShow",
"mouseenter #topbar_messageButton,#topbar_messageContainer": "messagesShow",
"mouseleave #topbar_messageButton,#topbar_messageContainer": "messagesHide",
"click li.name": "getMessages"
},
onRender: function(){
this.getMessages();
},
onBeforeDestroy: function() {
this.unbind();
},
getMessages: function(event){
if(event){
event.stopPropagation();
event.preventDefault();
}
var self = this;
$.ajax({
url: '/api/messages/chat/?username='+App.session.user.get('username'),
type: 'GET',
contentType: 'application/json',
dataType: 'json',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(data){
self.collection.reset();
self.collection.add(data, {merge: true});
var html = self.template(self.collection.toJSON());
html += self.template({messageCount:self.collection.length});
html += self.template($.extend({messageCount:self.collection.length},App.session.user.toJSON()));
self.$el.html(html);
$(document).foundation('reflow');
},
error: function(data){
console.log(data);
}
});
},
messagesShow: function() {
this.$("#topbar_messageContainer").show();
},
messagesHide: function() {
this.$("#topbar_messageContainer").hide();
},
messageSeeall: function(){
this.triggerMethod("click:messages:show");
},
detectUserAgent: function() {
var userAgent;
var fileType;
if(navigator.userAgent.match(/Android/g)) {
userAgent = "You are using an Android";
fileType = ".apk";
} else if(navigator.userAgent.match(/iPhone/g)){
userAgent = "iPhone";
fileType = ".ipa";
} else if(navigator.userAgent.match(/Windows/g)){
userAgent = "Windows";
fileType = ".exe";
} else if(navigator.userAgent.match(/Mac/g)){
userAgent = "Mac";
fileType = ".dmg";
} else if(navigator.userAgent.match(/Linux/g)){
userAgent = "Linux";
fileType = ".deb";
}
this.$el.find("#modalPlatform").html("You have the following OS: "+userAgent);
this.$el.find("#modalDownload").html("Download the "+fileType+" on the right to begin playing the game! -->");
this.$el.find("#myModal").foundation('reveal','open');
},
settingsShow: function(){
this.triggerMethod("click:settings:show");
},
myprofileShow: function(){
this.triggerMethod("click:myprofile:show");
},
forumsShow: function(){
this.triggerMethod("click:forums:show");
},
leaderboardsShow: function(){
this.triggerMethod("click:leaderboards:show");
},
announcementsShow: function(){
this.triggerMethod("click:announcements:show");
},
adminShow: function() {
this.triggerMethod("click:admin:show");
},
logout: function(event) {
if(event){
event.stopPropagation();
event.preventDefault();
}
App.session.logout({
},{
success: function(){
console.log("Logged out");
Backbone.history.navigate('home', {trigger: true});
},
error: function() {
console.log("Logged out failed");
}
});
}
});
}); |
module.exports = function(grunt) {
"use strict";
var fs = require('fs'), pkginfo = grunt.file.readJSON("package.json");
grunt.initConfig({
pkg: pkginfo,
meta: {
banner: "/*! <%= pkg.title %> <%= pkg.version %> | <%= pkg.homepage %> | (c) 2014 YOOtheme | MIT License */"
},
jshint: {
src: {
options: {
jshintrc: "src/.jshintrc"
},
src: ["src/js/*.js"]
}
},
less: (function(){
var lessconf = {
"docsmin": {
options: { paths: ["docs/less"], cleancss: true },
files: { "docs/css/uikit.docs.min.css": ["docs/less/uikit.less"] }
}
},
themes = [];
//themes
["default", "custom"].forEach(function(f){
if(grunt.option('quick') && f=="custom") return;
if(fs.existsSync('themes/'+f)) {
fs.readdirSync('themes/'+f).forEach(function(t){
var themepath = 'themes/'+f+'/'+t,
distpath = f=="default" ? "dist/css" : themepath+"/dist";
// Is it a directory?
if (fs.lstatSync(themepath).isDirectory() && t!=="blank" && t!=='.git') {
var files = {};
if(t=="default") {
files[distpath+"/uikit.css"] = [themepath+"/uikit.less"];
} else {
files[distpath+"/uikit."+t+".css"] = [themepath+"/uikit.less"];
}
lessconf[t] = {
"options": { paths: [themepath] },
"files": files
};
var filesmin = {};
if(t=="default") {
filesmin[distpath+"/uikit.min.css"] = [themepath+"/uikit.less"];
} else {
filesmin[distpath+"/uikit."+t+".min.css"] = [themepath+"/uikit.less"];
}
lessconf[t+"min"] = {
"options": { paths: [themepath], cleancss: true},
"files": filesmin
};
themes.push({ "path":themepath, "name":t, "dir":f });
}
});
}
});
//addons
themes.forEach(function(theme){
if(fs.existsSync(theme.path+'/uikit-addons.less')) {
var name = (theme.dir == 'default' && theme.name == 'default') ? 'uikit.addons' : 'uikit.'+theme.name+'.addons',
dest = (theme.dir == 'default') ? 'dist/css/addons' : theme.path+'/dist/addons';
lessconf["addons-"+theme.name] = {options: { paths: ['src/less/addons'] }, files: {} };
lessconf["addons-"+theme.name].files[dest+"/"+name+".css"] = [theme.path+'/uikit-addons.less'];
lessconf["addons-min-"+theme.name] = {options: { paths: ['src/less/addons'], cleancss: true }, files: {} };
lessconf["addons-min-"+theme.name].files[dest+"/"+name+".min.css"] = [theme.path+'/uikit-addons.less'];
}
});
return lessconf;
})(),
copy: {
fonts: {
files: [{ expand: true, cwd: "src/fonts", src: ["*"], dest: "dist/fonts/" }]
}
},
concat: {
dist: {
options: {
separator: "\n\n"
},
src: [
"src/js/core.js",
"src/js/utility.js",
"src/js/touch.js",
"src/js/alert.js",
"src/js/button.js",
"src/js/dropdown.js",
"src/js/grid.js",
"src/js/modal.js",
"src/js/offcanvas.js",
"src/js/nav.js",
"src/js/tooltip.js",
"src/js/switcher.js",
"src/js/tab.js",
"src/js/scrollspy.js",
"src/js/smooth-scroll.js",
"src/js/toggle.js",
],
dest: "dist/js/uikit.js"
}
},
usebanner: {
dist: {
options: {
position: 'top',
banner: "<%= meta.banner %>\n"
},
files: {
src: [ 'dist/css/**/*.css', 'dist/js/**/*.js' ]
}
}
},
uglify: {
distmin: {
options: {
//banner: "<%= meta.banner %>\n"
},
files: {
"dist/js/uikit.min.js": ["dist/js/uikit.js"]
}
},
addonsmin: {
files: (function(){
var files = {};
fs.readdirSync('src/js/addons').forEach(function(f){
if(f.match(/\.js/)) {
var addon = f.replace(".js", "");
grunt.file.copy('src/js/addons/'+f, 'dist/js/addons/'+addon+'.js');
files['dist/js/addons/'+addon+'.min.js'] = ['src/js/addons/'+f];
}
});
return files;
})()
}
},
compress: {
dist: {
options: {
archive: ("dist/uikit-"+pkginfo.version+".zip")
},
files: [
{ expand: true, cwd: "dist/", src: ["css/*", "js/*", "fonts/*", "addons/**/*"], dest: "" }
]
}
},
watch: {
src: {
files: ["src/**/*.less", "themes/**/*.less","src/js/*.js"],
tasks: ["build"]
}
}
});
grunt.registerTask('indexthemes', 'Rebuilding theme index.', function() {
var themes = [];
["default", "custom"].forEach(function(f){
if(fs.existsSync('themes/'+f)) {
fs.readdirSync('themes/'+f).forEach(function(t){
var themepath = 'themes/'+f+'/'+t;
// Is it a directory?
if (fs.lstatSync(themepath).isDirectory() && t!=="blank" && t!=='.git') {
var theme = {
"name" : t.split("-").join(" ").replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function ($1) { return $1.toUpperCase(); }),
"url" : "../"+themepath+"/uikit.less",
"config": (fs.existsSync(themepath+"/customizer.json") ? "../"+themepath+"/customizer.json" : "../themes/default/uikit/customizer.json"),
"styles": {}
};
if(fs.existsSync(themepath+'/styles')) {
var styles = {};
fs.readdirSync(themepath+'/styles').forEach(function(sf){
var stylepath = [themepath, 'styles', sf, 'style.less'].join('/');
if(fs.existsSync(stylepath)) {
styles[sf] = "../"+themepath+"/styles/"+sf+"/style.less";
}
});
theme.styles = styles;
}
themes.push(theme);
}
});
}
});
grunt.log.writeln(themes.length+' themes found: ' + themes.map(function(theme){ return theme.name;}).join(", "));
fs.writeFileSync("themes/themes.json", JSON.stringify(themes, " ", 4));
});
grunt.registerTask('sublime', 'Building Sublime Text Package', function() {
// generates a python list (returns string representation)
var pythonList = function(classes) {
var result = [];
classes.forEach(function(cls) {
// wrap class name in double quotes, add comma (except for last element)
result.push(['"', cls, '"', (i !== classes.length-1 ? ", " : "")].join(''));
// break lines every n elements
if ((i !== 0) && (i%20 === 0)) {
result.push("\n ");
}
});
return "[" + result.join("") + "]";
};
// css core
var filepath = 'dist/css/uikit.css', cssFiles = [filepath];
if (!fs.existsSync(filepath)) {
grunt.log.error("Not found: " + filepath);
return;
}
// css addons
fs.readdirSync('dist/css/addons').forEach(function(f){
if (f.match(/\.css$/)) {
cssFiles.push('dist/css/addons/'+f);
}
});
var cssContent = "";
for (var i in cssFiles) {
cssContent += grunt.file.read(cssFiles[i])+' ';
}
var classesList = cssContent.match(/\.(uk-[a-z\d\-]+)/g),
classesSet = {},
pystring = '# copy & paste into sublime plugin code:\n';
// use object as set (no duplicates)
classesList.forEach(function(c) {
c = c.substr(1); // remove leading dot
classesSet[c] = true;
});
// convert set back to list
classesList = Object.keys(classesSet);
pystring += 'uikit_classes = ' + pythonList(classesList) + '\n';
// JS core
filepath = 'dist/js/uikit.js';
if (!fs.existsSync(filepath)) {
grunt.log.error("Not found: " + filepath);
return;
}
var jsFiles = [filepath];
// JS addons
fs.readdirSync('dist/js/addons').forEach(function(f){
if (f.match(/\.js$/)) {
jsFiles.push('dist/js/addons/'+f);
}
});
var jsContent = "";
for (var i in jsFiles) {
jsContent += grunt.file.read(jsFiles[i]) + ' ';
}
var dataList = jsContent.match(/data-uk-[a-z\d\-]+/g),
dataSet = {};
dataList.forEach(function(s) { dataSet[s] = true; });
dataList = Object.keys(dataSet);
pystring += 'uikit_data = ' + pythonList(dataList) + '\n';
grunt.file.write('dist/uikit_completions.py', pystring);
grunt.log.writeln('Written: dist/uikit_completions.py');
});
// Load grunt tasks from NPM packages
grunt.loadNpmTasks("grunt-contrib-less");
grunt.loadNpmTasks("grunt-contrib-copy");
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-contrib-compress");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-banner");
// Register grunt tasks
grunt.registerTask("build", ["jshint", "indexthemes", "less", "concat", "copy", "uglify", "usebanner"]);
grunt.registerTask("default", ["build", "compress"]);
};
|
/*
* Misc Javascript variables and functions.
*
* This could all likely use some cleanup. Some of this stuff could be:
*
* - turned into event-based unobtrusive javascript
* - simply named / namespaced a bit better
* - the html generated from javascript strings could
* likely be improved or moved to the server-side
*
*/
// DEPRECATED
var image_attribution_panel_open = false;
function toggle_image_attribution() { EOL.log("obsolete method called: toggle_image_attribution"); }
function hide_image_attribution() { EOL.log("obsolete method called: hide_image_attribution"); }
function show_image_attribution() { EOL.log("obsolete method called: show_image_attribution"); }
function create_attribution_table_header() { EOL.log("obsolete method called: create_attribution_table_header"); }
function create_attribution_table_row() { EOL.log("obsolete method called: create_attribution_table_row"); }
function create_attribution_table_footer() { EOL.log("obsolete method called: create_attribution_table_footer"); }
function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
cntfield.innerHTML = maxlimit - field.value.length + ' remaining';
}
// update the content area
function eol_update_content_area(taxon_concept_id, category_id, allow_user_text) {
if($('insert_text_popup')) {
EOL.popup_links['new_text_toc_text'].popup.toggle();
}
// i feel like this could be a lot simpler ...
new Ajax.Request('/taxa/content/', {
parameters: { id: taxon_concept_id, category_id: category_id },
onComplete:function(request){hideAjaxIndicator(true);updateReferences();},
onSuccess:function(request){hideAjaxIndicator(true);updateReferences();},
onError: function(request){hideAjaxIndicator(true);},
onLoading:function(request){showAjaxIndicator(true);},
asynchronous:true,
evalScripts:true});
$A(document.getElementsByClassName('active', $('toc'))).each(function(e) { e.className = 'toc_item'; });
}
// show the pop-up in the div
function eol_show_pop_up(div_name, partial_name, taxon_name) {
if (partial_name==null) partial_name=div_name;
if (taxon_name==null) taxon_name='';
new Ajax.Updater(
div_name,
'/taxa/show_popup',
{
asynchronous:true,
evalScripts:true,
method:'post',
onComplete:function(request){hideAjaxIndicator();EOL.Effect.toggle_with_effect(div_name);},
onLoading:function(request){showAjaxIndicator();},
parameters:{name: partial_name, taxon_name: taxon_name}
}
);
}
// Updates the main image and calls eol_update_credit()
function eol_update_image(large_image_url, params) {
$('main-image').src = large_image_url;
$('main-image').alt=params.nameString;
$('main-image').title=params.nameString;
// update the hrefs for the comment, curation, etc popups
if($$('div#large-image-trust-button a')[0]) {
if (!params.curated) {
$$('div#large-image-trust-button a')[0].href="/data_objects/"+params.data_object_id+"/curate?_method=put&curator_activity_id=3";
$$('div#large-image-untrust-button a')[0].href="/data_objects/"+params.data_object_id+"/curate?_method=put&curator_activity_id=7";
$$('div#large-image-untrust-button a')[0].writeAttribute('data-data_object_id', params.data_object_id);
$$('div#large-image-trust-button a')[0].writeAttribute('data-data_object_id', params.data_object_id);
$('large-image-trust-button').appear();
$('large-image-untrust-button').appear();
} else {
$('large-image-trust-button').disappear();
$('large-image-untrust-button').disappear();
}
}
if ($('large-image-comment-button-popup-link')) $('large-image-comment-button-popup-link').href = "/data_objects/" + params.data_object_id + "/comments";
if ($('large-image-attribution-button-popup-link')) $('large-image-attribution-button-popup-link').href = "/data_objects/" + params.data_object_id + "/attribution";
if ($('large-image-tagging-button-popup-link')) $('large-image-tagging-button-popup-link').href = "/data_objects/" + params.data_object_id + "/tags";
if ($('large-image-curator-button-popup-link')) $('large-image-curator-button-popup-link').href = "/data_objects/" + params.data_object_id + "/curation";
//update star rating links
if($$('div.image-rating ul.user-rating a.one-star')[0]) {
$$('div.image-rating ul.user-rating a.one-star')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=1';
$$('div.image-rating ul.user-rating a.one-star')[0].writeAttribute('data-data_object_id', params.data_object_id);
}
if($$('div.image-rating ul.user-rating a.two-stars')[0]) {
$$('div.image-rating ul.user-rating a.two-stars')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=2';
$$('div.image-rating ul.user-rating a.two-stars')[0].writeAttribute('data-data_object_id', params.data_object_id);
}
if($$('div.image-rating ul.user-rating a.three-stars')[0]) {
$$('div.image-rating ul.user-rating a.three-stars')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=3';
$$('div.image-rating ul.user-rating a.three-stars')[0].writeAttribute('data-data_object_id', params.data_object_id);
}
if($$('div.image-rating ul.user-rating a.four-stars')[0]) {
$$('div.image-rating ul.user-rating a.four-stars')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=4';
$$('div.image-rating ul.user-rating a.four-stars')[0].writeAttribute('data-data_object_id', params.data_object_id);
}
if($$('div.image-rating ul.user-rating a.five-stars')[0]) {
$$('div.image-rating ul.user-rating a.five-stars')[0].href = '/data_objects/rate/' + params.data_object_id +'?stars=5';
$$('div.image-rating ul.user-rating a.five-stars')[0].writeAttribute('data-data_object_id', params.data_object_id);
}
EOL.Rating.update_average_image_rating(params.data_object_id, params.average_rating);
EOL.Rating.update_user_image_rating(params.data_object_id, params.user_rating);
eol_update_credit(params);
// make a logging call to let the server know that we've viewed this image
eol_log_data_objects_for_taxon_concept( params.taxonID, params.data_object_id );
return false;
}
// Updates the image credit box
//
// TODO - this should be fetched from the server-side ... way too much HTML generation in the javascript
//
// ... this updates abunchof stuff and is pretty disorganized :(
//
function eol_update_credit(params){
// ! FIELD NOTES ! <start> NOTE: this should really be moved into a partial on the server side!
field_notes_area = '';
if (params.taxaIDs.length > 0 ) {
var current_page_name_or_id = window.location.toString().sub(/.*\//,'').sub(/\?.*/,'');
var taxa_thats_not_the_current_page = 0;
// loop thru and find a taxa that's NOT the current page's taxa
while (params.taxaIDs[taxa_thats_not_the_current_page] != null && current_page_name_or_id == params.taxaIDs[taxa_thats_not_the_current_page].toString() ) {
taxa_thats_not_the_current_page++;
}
// if it exists, show it ...
if ( params.taxaIDs[taxa_thats_not_the_current_page] != null ) {
field_notes_area += 'Image of <a href="/pages/' + params.taxaIDs[taxa_thats_not_the_current_page] + '">' + params.taxaNames[taxa_thats_not_the_current_page] + '</a><br />';
}
}
license_info='COPYRIGHT: ';
if (params.license_text != '') {
license_info += params.license_text;
}
if (params.license_logo != '') {
license_info += ' <a href="' + params.license_link + '" class="external_link"><img src="' + params.license_logo + '" border="0"></a>';
}
field_notes_area += license_info+'<br />'
if (params.data_supplier != '') {
if (params.data_supplier_url != '') {
field_notes_area += 'SUPPLIER: <a href="'+params.data_supplier_url+'" class="external_link">' + params.data_supplier + ' <img alt="external link" src="/images/external_link.png"></a> ' + params.data_supplier_icon + '<br />';
} else {
field_notes_area += 'SUPPLIER: ' + params.data_supplier + '<br />';
}
}
if (params.authors_linked != '') {
field_notes_area += 'AUTHOR: ' + params.authors_linked + '<br />';
}
if (params.sources != '' && params.info_url != '' && params.info_url != null) {
field_notes_area += 'SOURCE: <a href="'+params.info_url+'" class="external_link">' + params.sources + ' <img alt="external link" src="/images/external_link.png"></a><br />';
}
else if (params.sources_linked != '') {
field_notes_area += 'SOURCE:' + params.sources_linked + '<br />';
}
if (params.sources_icons_linked != '') {
field_notes_area += params.sources_icons_linked + '<br />';
}
field_notes_area += '<br /><br />';
field_notes_area += params.field_notes ? params.field_notes : "";
$$('#large-image-button-group .published_icon')[0].hide();
$$('#large-image-button-group .unpublished_icon')[0].hide();
$$('#large-image-button-group .inappropriate_icon')[0].hide();
$$('#large-image-button-group .invisible_icon')[0].hide();
if (params.published_by_agent){
$$('#large-image-button-group .published_icon')[0].show();
} else if(!params.published) {
$$('#large-image-button-group .unpublished_icon')[0].show();
}
if (params.visibility_id == EOL.Curation.INVISIBLE_ID) {
$$('#large-image-button-group .invisible_icon')[0].show();
} else if (params.visibility_id == EOL.Curation.INAPPROPRIATE_ID) {
$$('#large-image-button-group .inappropriate_icon')[0].show();
}
$('large-image-attribution-button').removeClassName('unknown');
$('large-image-attribution-button').removeClassName('untrusted');
$('mc-notes').removeClassName('unknown-background-text');
$('mc-notes').removeClassName('untrusted-background-text');
$('main-image-bg').removeClassName('unknown-background-image');
$('main-image-bg').removeClassName('untrusted-background-image');
if (params.vetted_id == EOL.Curation.UNKNOWN_ID) {
$('mc-notes').addClassName('unknown-background-text');
$('main-image-bg').addClassName('unknown-background-image');
$('large-image-attribution-button').addClassName('unknown');
field_notes_area += '<br /><br /><strong>Note:</strong> The image from this source has not been reviewed.';
} else if (params.vetted_id == EOL.Curation.UNTRUSTED_ID) {
$('mc-notes').addClassName('untrusted-background-text');
$('main-image-bg').addClassName('untrusted-background-image');
$('large-image-attribution-button').addClassName('untrusted');
field_notes_area += '<br /><br /><strong>Note:</strong> The image from this source is not trusted.';
}
$('field-notes').innerHTML = field_notes_area; // this is the 'gray box'
// ! FIELD NOTES ! </end>
EOL.reload_behaviors();
}
// Updates the main image and calls eol_update_credit()
function eol_update_video(params) {
$$('div#media-videos div.attribution_link')[0].show();
for(var i in EOL.popups) {
EOL.popups[i].destroy();
}
$('video_attributions').href = "/data_objects/" + params.data_object_id + "/attribution";
new Ajax.Request('/taxa/show_video/', {
parameters: { video_type: params.video_type, video_url: params.video_url },
onComplete:function(request){hideAjaxIndicator();},
onLoading:function(request){showAjaxIndicator();},
asynchronous:true,
evalScripts:true});
$('video-notes').removeClassName('untrusted-background-text');
$('video-player').removeClassName('untrusted-background-color');
$('video_attributions').removeClassName('untrusted');
$('video-notes').removeClassName('unknown-background-text');
$('video-player').removeClassName('unknown-background-color');
$('video_attributions').removeClassName('unknown');
if (params.video_trusted == EOL.Curation.UNTRUSTED_ID){
$('video-notes').addClassName('untrusted-background-text');
$('video-player').addClassName('untrusted-background-color');
$('video_attributions').addClassName('untrusted');
}
else if (params.video_trusted == EOL.Curation.UNKNOWN_ID){
$('video-notes').addClassName('unknown-background-text');
$('video-player').addClassName('unknown-background-color');
$('video_attributions').addClassName('unknown');
}
license_info='COPYRIGHT: ';
if (params.license_text != '') {
license_info += params.license_text;
}
if (params.license_logo != '') {
license_info += ' <a href="' + params.license_link + '" class="external_link"><img src="' + params.license_logo + '" border="0"></a>';
}
video_notes_area = '';
video_notes_area += params.title +'<br /><br />';
if (license_info != '') {video_notes_area += license_info + '<br />';}
data_supplier = params.video_data_supplier;
data_supplier_name = params.video_supplier_name;
data_supplier_url = params.video_supplier_url;
if (data_supplier != '') {
if (data_supplier_url != '') {
video_notes_area += 'SUPPLIER: <a href="'+data_supplier_url+'" class="external_link">' + data_supplier + ' <img alt="external link" src="/images/external_link.png"></a> ' + params.video_supplier_icon + '<br />';
} else {
video_notes_area += 'SUPPLIER: ' + data_supplier + '<br />';
}
}
if (params.author != '') {video_notes_area += 'AUTHOR: ' + params.author + '<br />';}
if (params.collection != '') {video_notes_area += 'SOURCE: ' + params.collection + '<br />';}
video_notes_area += params.field_notes ? '<br />' + params.field_notes : '';
$('video-notes').innerHTML = video_notes_area;
// make a logging call to let the server know that we've viewed this video
eol_log_data_objects_for_taxon_concept( params.taxon_concept_id, params.data_object_id );
return false;
}
function displayNode(id) {
displayNode(id, false)
}
// call remote function to show the selected node in the text-based navigational tree view
function displayNode(id, for_selection) {
url = '/navigation/show_tree_view'
if(for_selection) {
url = '/navigation/show_tree_view_for_selection'
}
new Ajax.Updater(
'browser-text', url,
{
asynchronous:true,
evalScripts:true,
method:'post',
onComplete:function(request){hideAjaxIndicator();},
onLoading:function(request){showAjaxIndicator();},
parameters:'id='+id
}
);
}
function eol_change_to_flash_browser()
{
if ($('classification-attribution-button_popup') != null) {EOL.Effect.disappear('classification-attribution-button_popup');}
EOL.Effect.disappear('browser-text');
EOL.Effect.appear('browser-flash');
update_default_taxonomic_browser('flash');
}
function eol_change_to_text_browser()
{
if ($('classification-attribution-button_popup') != null) {EOL.Effect.disappear('classification-attribution-button_popup');}
EOL.Effect.disappear('browser-flash');
EOL.Effect.appear('browser-text');
update_default_taxonomic_browser('text');
}
function update_default_taxonomic_browser(default_browser)
{
new Ajax.Request(
'/navigation/set_default_taxonomic_browser',
{
asynchronous:true,
evalScripts:true,
method:'get',
parameters:'browser='+default_browser
}
);
}
function toggle_children() {
Element.toggle('taxonomic-children');
if ($('toggle_children_link').innerHTML=='-') {
$('toggle_children_link').innerHTML='+'
}
else
{
$('toggle_children_link').innerHTML='-'
}
}
// DEPRECATED! let's use EOL.Ajax.start() / .finish()
function showAjaxIndicator(on_content_area) {
on_content_area = on_content_area || false
if (on_content_area)
{
Element.show('center-page-content-loading');
}
Element.show('ajax-indicator');
}
function hideAjaxIndicator(on_content_area) {
on_content_area = on_content_area || false
if (on_content_area)
{
Element.hide('center-page-content-loading');
}
Element.hide('ajax-indicator');
}
function eol_log_data_objects_for_taxon_concept( taxon_concept_id, data_object_ids ) {
// make a logging call to let the server know we have seen an object
new Ajax.Request('/taxa/view_object/', {
method: 'post',
parameters: { id: data_object_ids, taxon_concept_id: taxon_concept_id },
asynchronous: true
});
}
function taxon_comments_permalink(comment_id) {
window.onload = function() {
EOL.load_taxon_comments_tab({page_to_comment_id: comment_id});
$('media-images').hide();
if($('image').childNodes[0].className='active'){
$('image').childNodes[0].removeClassName('active');
}
$('taxa-comments').childNodes[0].addClassName('active');
}
var id_arrays = $$('#tab_media_center li').pluck('id');
function hide_taxa_comment(element){
$(element).childNodes[0].observe('click', function()
{
$('media-taxa-comments').hide();
})
}
id_arrays.forEach(hide_taxa_comment);
}
function text_comments_permalink(data_object_id, text_comment_id, comment_page) {
document.observe("dom:loaded", function(e) {
textComments = "text-comments-" + data_object_id;
textCommentsWrapper = "text-comments-wrapper-" + data_object_id;
if ($(textCommentsWrapper).style.display == 'none') {
new Ajax.Updater(textComments, '/data_objects/'+data_object_id+'/comments',
{asynchronous:true, evalScripts:true, method:'get',
parameters: { body_div_name: textComments,
comment_id: text_comment_id,
page: comment_page},
onLoading: Effect.BlindDown(textCommentsWrapper),
onComplete: function() {
$('comment_'+text_comment_id).scrollTo();
}
});
} else {
Effect.DropOut(textCommentsWrapper);
}
e.stop();
});
}
|
/*jshint node: true*/
'use strict';
// Defaults derived from: https://github.com/dequelabs/axe-core
const defaults = {
rules: {
'area-alt': { 'enabled': true },
'audio-caption': { 'enabled': true },
'button-name': { 'enabled': true },
'document-title': { 'enabled': true },
'empty-heading': { 'enabled': true },
'frame-title': { 'enabled': true },
'frame-title-unique': { 'enabled': true },
'image-alt': { 'enabled': true },
'image-redundant-alt': { 'enabled': true },
'input-image-alt': { 'enabled': true },
'link-name': { 'enabled': true },
'object-alt': { 'enabled': true },
'server-side-image-map': { 'enabled': true },
'video-caption': { 'enabled': true },
'video-description': { 'enabled': true },
'definition-list': { 'enabled': true },
'dlitem': { 'enabled': true },
'heading-order': { 'enabled': true },
'href-no-hash': { 'enabled': true },
'layout-table': { 'enabled': true },
'list': { 'enabled': true },
'listitem': { 'enabled': true },
'p-as-heading': { 'enabled': true },
'scope-attr-valid': { 'enabled': true },
'table-duplicate-name': { 'enabled': true },
'table-fake-caption': { 'enabled': true },
'td-has-header': { 'enabled': true },
'td-headers-attr': { 'enabled': true },
'th-has-data-cells': { 'enabled': true },
'duplicate-id': { 'enabled': true },
'html-has-lang': { 'enabled': true },
'html-lang-valid': { 'enabled': true },
'meta-refresh': { 'enabled': true },
'valid-lang': { 'enabled': true },
'checkboxgroup': { 'enabled': true },
'label': { 'enabled': true },
'radiogroup': { 'enabled': true },
'accesskeys': { 'enabled': true },
'bypass': { 'enabled': true },
'tabindex': { 'enabled': true },
// TODO: this should be re-enabled when we upgrade to axe-core ^3.1.1 (https://github.com/dequelabs/axe-core/issues/961)
'aria-allowed-attr': { 'enabled': false },
'aria-required-attr': { 'enabled': true },
'aria-required-children': { 'enabled': true },
'aria-required-parent': { 'enabled': true },
'aria-roles': { 'enabled': true },
'aria-valid-attr': { 'enabled': true },
'aria-valid-attr-value': { 'enabled': true },
'blink': { 'enabled': true },
'color-contrast': { 'enabled': true },
'link-in-text-block': { 'enabled': true },
'marquee': { 'enabled': true },
'meta-viewport': { 'enabled': true },
'meta-viewport-large': { 'enabled': true }
}
};
module.exports = {
getConfig: () => {
const skyPagesConfigUtil = require('../sky-pages/sky-pages.config');
const skyPagesConfig = skyPagesConfigUtil.getSkyPagesConfig();
let config = {};
// Merge rules from skyux config.
if (skyPagesConfig.skyux.a11y && skyPagesConfig.skyux.a11y.rules) {
config.rules = Object.assign({}, defaults.rules, skyPagesConfig.skyux.a11y.rules);
}
// The consuming SPA wishes to disable all rules.
if (skyPagesConfig.skyux.a11y === false) {
config.rules = Object.assign({}, defaults.rules);
Object.keys(config.rules).forEach((key) => {
config.rules[key].enabled = false;
});
}
if (!config.rules) {
return defaults;
}
return config;
}
};
|
angular.module('app.controllers')
.controller('detailsEventCtrl', ['$stateParams', '$window', '$http','eventService','personService','commentService','participantService', '$state', '$filter', '$ionicPopup', 'reviewService',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($stateParams, $window, $http, eventService,personService,commentService,participantService, $state, $filter, $ionicPopup, reviewService) {
var vm = this;
vm.data = {};
vm.event;
vm.isRegister;
vm.dateOfDay;
vm.connectedUser;
vm.isLogged;
vm.ListCommentResponse = [];
vm.registerUserToEvent = registerUserToEvent;
vm.unregisterUserToEvent = unregisterUserToEvent;
vm.getCommentMargin = getCommentMargin;
vm.cancelEvent = cancelEvent;
vm.detailsParticipant = detailsParticipant;
vm.swipeOnImage = swipeOnImage;
vm.formatDate = formatDate;
vm.displayRateForm = displayRateForm;
vm.hideRateForm = hideRateForm;
vm.noteEvent = noteEvent;
vm.openPopup = openPopup;
vm.registerComment = registerComment;
vm.showResponse = showResponse;
vm.imageToDisplay = "";
vm.getGoogleImage = getGoogleImage;
vm.images = {};
activate();
function activate(){
vm.dateOfDay = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm');
if (personService.getConnectedUser() == null){
vm.connectedUser = -1;
vm.isLogged = "false"
} else {
vm.connectedUser = personService.getConnectedUser().PersonId;
vm.isLogged = "true"
}
vm.event = eventService.getEvent();
var rng = Math.random();
if(rng < 0.4){
vm.imageToDisplay = "grosChat.jpg";
} else if(rng < 0.8) {
vm.imageToDisplay = "chaton.jpg";
} else if (rng < 0.98){
vm.imageToDisplay = "defaultUser2.jpg";
} else {
vm.imageToDisplay = "d74c8cec9490f925a191d4f677fb37ae.jpg"
}
commentService.getCommentByEvent(vm.event.EventId)
.then(function successCallback(response) {
vm.ListComment = response.reverse();
console.log(response);
}, function erroCallabck(response) {
console.log("Il y a eu des erreurs!")
console.log(response);
});
participantService.getAllParticipantById(vm.event.EventId)
.then(function successCallback(response) {
console.log(response);
vm.ListParticipant = response;
vm.nbParticipants = vm.ListParticipant.length;
if (personService.getConnectedUser() == null){
vm.isRegister = "null";
}else {
var isRegister = "false";
for(i=0;i<vm.ListParticipant.length;i++){
if(vm.ListParticipant[i].PersonId == personService.getConnectedUser().PersonId){
isRegister = "true";
}
}
if (isRegister == "true"){
vm.isRegister = "true";
}else{
vm.isRegister = "false";
}
}
console.log("isRegister");
console.log(vm.isRegister);
}, function erroCallabck(response) {
console.log("Participant: Il y a eu des erreurs!")
console.log(response);
});
}
function registerUserToEvent () {
participantService.saveParticipant(personService.getResponseGoogle().idToken, personService.getConnectedUser().PersonId, eventService.getEvent().EventId)
.then(function(response){
vm.isRegister = "true";
})
}
function unregisterUserToEvent() {
participantService.cancelParticipation(personService.getResponseGoogle().idToken, personService.getConnectedUser().PersonId, eventService.getEvent().EventId)
.then(function(response){
vm.isRegister = "false";
})
}
function getCommentMargin(owner){
if (owner == null){
return "0%";
}else {
return "5%";
}
}
function cancelEvent() {
var responseGoogle = personService.getResponseGoogle();
var eventToSend = {
"EventId" : vm.event.EventId,
"Name" : vm.event.Name,
"DateStart" : vm.event.DateStart,
"DateEnd" : vm.event.DateEnd,
"PlaceId" : vm.event.PlaceId,
"Description": vm.event.Description,
"Image" : vm.event.Image,
"IsCanceled" : 1,
"Owner" : vm.event.Owner,
"EventType" : vm.event.EventType
};
eventService.registerEvent(responseGoogle.idToken,eventToSend);
alert('Votre évènement à bien été annulé');
}
function detailsParticipant(){
var div = document.getElementById("participantDiv");
if (div.style.display == 'none'){
div.style.display = 'block';
}else{
div.style.display = 'none';
}
}
function displayRateForm() {
document.getElementById("ratingForm").style.display = "block";
document.getElementById("beforeRate").style.display = "none";
}
function hideRateForm() {
document.getElementById("ratingForm").style.display = "none";
document.getElementById("beforeRate").style.display = "block";
}
function noteEvent() {
var note = document.getElementById("note").value;
var comment = document.getElementById("comment").value;
console.log(note);
console.log(comment);
var reviewToSend = {
"person" : personService.getConnectedUser().PersonId,
"event" : vm.event.EventId,
"rate" : note,
"text" : comment
};
reviewService.updateReview(personService.getResponseGoogle().idToken, reviewToSend )
.then(function(result){
vm.hideRateForm();
})
}
function registerComment(responseTo) {
if (responseTo == 'NULL'){
responseTo = null;
}
var commentToSend = {
"ResponseTo" : responseTo,
"Text" : document.getElementById("commentText").value,
"DatePost" : $filter('date')(new Date(), 'yyyy-MM-dd HH:mm'),
"EventId" : vm.event.EventId,
"PersonId" : personService.getConnectedUser().PersonId,
"Person" : personService.getConnectedUser()
};
commentService.registerComment(personService.getResponseGoogle().idToken, commentToSend )
.then(function(result){
commentService.getCommentByEvent(vm.event.EventId)
.then(function successCallback(response) {
vm.ListComment = response.reverse();
console.log(response);
}, function erroCallabck(response) {
console.log("Il y a eu des erreurs!")
console.log(response);
});
})
}
function swipeOnImage() {
/*var audio = new Audio('img/986.mp3');
audio.play();*/
}
function formatDate(date){
var dateOut = new Date(date);
return dateOut;
}
function getGoogleImage(email){
var res = personService.getGooglePicture(email)
.then(function(result){
if (!(email in vm.images)){
vm.images[email]=result;
}
return result;
})
.catch(function(error){console.log(error)});
return res;
}
function openPopup(responseTo, $event) {
var myPopup = $ionicPopup.show({
template: '<textarea id="commentText" rows="6" cols="150" maxlength="300" ng-model="data.model" ng-model="vm.data.comment" ></textarea>',
title: 'Commentaire',
subTitle: 'Les commentaires que vous rentrez doivent être assumés, ils ne pourront pas être effacés!',
buttons: [
{ text: 'Annuler' }, {
text: '<b>Commenter</b>',
type: 'button-positive',
onTap: function(e) {
if (!document.getElementById("commentText").value.trim()) {
e.preventDefault();
} else {
return document.getElementById("commentText").value;
}
}
}
]
});
myPopup.then(function(res) {
if (res){
registerComment(responseTo);
}
});
$event.stopPropagation();
}
function showResponse(eventId, commentId, $event) {
if (vm.ListCommentResponse[commentId] == undefined || vm.ListCommentResponse[commentId].length == 0){
commentService.getResponseList(eventId, commentId)
.then(function(result){
vm.ListCommentResponse[commentId] = result.reverse();
})
$event.stopPropagation();
} else {
vm.ListCommentResponse[commentId] = [];
}
}
}])
|
import Instruction from './Instruction';
function arcTo(x1, y1, x2, y2, r) {
return new Instruction('call', {
name: 'arcTo',
args: [x1, y1, x2, y2, r],
count: 5,
});
}
export default arcTo;
|
'use strict';
exports.fixShould = function fixShould(str) {
var segs = str.split('var should = require(\'should\');');
return segs.join('require(\'should\');');
};
|
//// config/database.js
module.exports = {
url: 'mongodb://gaurav:[email protected]:10056/cmpe275'
}; |
/* jslint node: true */
/*!
* rinco - include templates
* Copyright(c) 2014 Allan Esquina
* MIT Licensed
*/
'use strict';
var rinco = require('../rinco');
var it = require('../interpreter');
var Markdown = require('markdown').markdown;
var md = require('markdown-it')({
html: true,
linkify: true,
typographer: true
});
var config = require('../constants');
// Parse templates files
rinco.render.middleware.register(function rinco_template(next, content) {
[{ start:'<r-include', end:'/>'}].map(function (tag) {
function r(content) {
var has = false;
content = it.parse(content, tag, function (prc) {
var filename = prc.trim();
var tpl = rinco.fs.file.read(rinco.fs.path.join(config.INCLUDE_DIR, filename));
has = true;
if(tpl) {
if (rinco.fs.path.extname(filename) === ".md") {
tpl = md.render(tpl.toString());
}
return tpl;
}
else {
return "File: " + rinco.fs.path.join(config.INCLUDE_DIR, filename);
}
});
return has ? r(content) : content;
}
content = r(content.toString());
});
next(content);
});
|
BASE.require(["Object"], function () {
BASE.namespace("LG.core.dataModel.core");
var _globalObject = this;
LG.core.dataModel.core.Credential = (function (Super) {
var Credential = function () {
var self = this;
if (self === _globalObject) {
throw new Error("Credential constructor invoked with global context. Say new.");
}
Super.call(self);
self["authenticationFactors"] = [];
self["authentications"] = [];
self["personId"] = null;
self["person"] = null;
self["startDate"] = null;
self["endDate"] = null;
self["id"] = null;
return self;
};
BASE.extend(Credential, Super);
return Credential;
}(Object));
}); |
var events = require('events');
var request = require('request');
var zlib = require('zlib');
var iconv = require('iconv-lite');
var async = require('async');
var imagesize = require('imagesize');
var moment = require('moment');
var _ = require('underscore');
var cache = require('./cache');
var htmlUtils = require('./html-utils');
if (!GLOBAL.CONFIG) {
GLOBAL.CONFIG = require('../config');
}
/**
* @private
* Do HTTP GET request and handle redirects
* @param url Request uri (parsed object or string)
* @param {Object} options
* @param {Number} [options.maxRedirects]
* @param {Boolean} [options.fullResponse] True if need load full page response. Default: false.
* @param {Function} [callback] The completion callback function or events.EventEmitter object
* @returns {events.EventEmitter} The emitter object which emit error or response event
*/
var getUrl = exports.getUrl = function(url, options) {
var req = new events.EventEmitter();
var options = options || {};
// Store cookies between redirects and requests.
var jar = options.jar;
if (!jar) {
jar = request.jar();
}
process.nextTick(function() {
try {
var supportGzip = !process.version.match(/^v0\.8/);
var r = request({
uri: url,
method: 'GET',
headers: {
'User-Agent': CONFIG.USER_AGENT,
'Connection': 'close',
'Accept-Encoding': supportGzip ? 'gzip' : ''
},
maxRedirects: options.maxRedirects || 3,
timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT,
followRedirect: options.followRedirect,
jar: jar
})
.on('error', function(error) {
req.emit('error', error);
})
.on('response', function(res) {
if (supportGzip && ['gzip', 'deflate'].indexOf(res.headers['content-encoding']) > -1) {
var gunzip = zlib.createUnzip();
gunzip.request = res.request;
gunzip.statusCode = res.statusCode;
gunzip.headers = res.headers;
if (!options.asBuffer) {
gunzip.setEncoding("binary");
}
req.emit('response', gunzip);
res.pipe(gunzip);
} else {
if (!options.asBuffer) {
res.setEncoding("binary");
}
req.emit('response', res);
}
});
req.emit('request', r);
} catch (ex) {
console.error('Error on getUrl for', url, '.\n Error:' + ex);
req.emit('error', ex);
}
});
return req;
};
var getHead = function(url, options) {
var req = new events.EventEmitter();
var options = options || {};
// Store cookies between redirects and requests.
var jar = options.jar;
if (!jar) {
jar = request.jar();
}
process.nextTick(function() {
try {
var r = request({
uri: url,
method: 'HEAD',
headers: {
'User-Agent': CONFIG.USER_AGENT,
'Connection': 'close'
},
maxRedirects: options.maxRedirects || 3,
timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT,
followRedirect: options.followRedirect,
jar: jar
})
.on('error', function(error) {
req.emit('error', error);
})
.on('response', function(res) {
req.emit('response', res);
});
req.emit('request', r);
} catch (ex) {
console.error('Error on getHead for', url, '.\n Error:' + ex);
req.emit('error', ex);
}
});
return req;
};
exports.getCharset = function(string, doNotParse) {
var charset;
if (doNotParse) {
charset = string.toUpperCase();
} else if (string) {
var m = string && string.match(/charset\s*=\s*([\w_-]+)/i);
charset = m && m[1].toUpperCase();
}
return charset;
};
exports.encodeText = function(charset, text) {
try {
var b = iconv.encode(text, "ISO8859-1");
return iconv.decode(b, charset || "UTF-8");
} catch(e) {
return text;
}
};
/**
* @public
* Get image size and type.
* @param {String} uri Image uri.
* @param {Object} [options] Options.
* @param {Boolean} [options.cache] False to disable cache. Default: true.
* @param {Function} callback Completion callback function. The callback gets two arguments (error, result) where result has:
* - result.format
* - result.width
* - result.height
*
* error == 404 if not found.
* */
exports.getImageMetadata = function(uri, options, callback){
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
cache.withCache("image-meta:" + uri, function(callback) {
var loadImageHead, imageResponseStarted, totalTime, timeout, contentLength;
var requestInstance = null;
function finish(error, data) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
} else {
return;
}
// We don't need more data. Abort causes error. timeout === null here so error will be skipped.
requestInstance && requestInstance.abort();
if (!error && !data) {
error = 404;
}
data = data || {};
if (options.debug) {
data._time = {
imageResponseStarted: imageResponseStarted || totalTime(),
loadImageHead: loadImageHead && loadImageHead() || 0,
total: totalTime()
};
}
if (error && error.message) {
error = error.message;
}
if ((typeof error === 'string' && error.indexOf('ENOTFOUND') > -1) ||
error === 500) {
error = 404;
}
if (error) {
data.error = error;
}
callback(null, data);
}
timeout = setTimeout(function() {
finish("timeout");
}, options.timeout || CONFIG.RESPONSE_TIMEOUT);
if (options.debug) {
totalTime = createTimer();
}
async.waterfall([
function(cb){
getUrl(uri, {
timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT,
maxRedirects: 5,
asBuffer: true
})
.on('request', function(req) {
requestInstance = req;
})
.on('response', function(res) {
var content_type = res.headers['content-type'];
if (content_type && content_type !== 'application/octet-stream' && content_type !== 'binary/octet-stream') {
if (content_type.indexOf('image/') === -1) {
cb('invalid content type: ' + res.headers['content-type']);
}
} else {
if (!uri.match(/\.(jpg|png|gif)(\?.*)?$/i)) {
cb('invalid content type: no content-type header and file extension');
}
}
if (res.statusCode == 200) {
if (options.debug) {
imageResponseStarted = totalTime();
}
contentLength = parseInt(res.headers['content-length'] || '0', 10);
imagesize(res, cb);
} else {
cb(res.statusCode);
}
})
.on('error', function(error) {
cb(error);
});
},
function(data, cb){
if (options.debug) {
loadImageHead = createTimer();
}
if (contentLength) {
data.content_length = contentLength;
}
cb(null, data);
}
], finish);
}, {disableCache: options.disableCache}, callback);
};
exports.getUriStatus = function(uri, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
cache.withCache("status:" + uri, function(cb) {
var time, timeout;
function finish(error, data) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
} else {
return;
}
data = data || {};
if (error) {
data.error = error;
}
if (options.debug) {
data._time = time();
}
cb(null, data);
}
timeout = setTimeout(function() {
finish("timeout");
}, options.timeout || CONFIG.RESPONSE_TIMEOUT);
if (options.debug) {
time = createTimer();
}
getUriStatus(uri, options, finish);
}, {disableCache: options.disableCache}, callback);
};
exports.getContentType = function(uriForCache, uriOriginal, options, cb) {
cache.withCache("content-type:" + uriForCache, function(cb) {
var timeout, requestInstance, totalTime;
function finish(error, content_type) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
} else {
return;
}
// We don't need more data. Abort causes error. timeout === null here so error will be skipped.
requestInstance && requestInstance.abort();
var data = {};
if (options.debug) {
data._time = totalTime();
}
if (error) {
data.error = error;
}
if (!error && !data) {
data.error = 404;
}
data.type = content_type;
cb(null, data);
}
timeout = setTimeout(function() {
finish("timeout");
}, options.timeout || CONFIG.RESPONSE_TIMEOUT);
if (options.debug) {
totalTime = createTimer();
}
getHead(uriOriginal, {
timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT,
maxRedirects: 5
})
.on('request', function(req) {
requestInstance = req;
})
.on('response', function(res) {
var content_type = res.headers['content-type'];
if (content_type) {
content_type = content_type.split(';')[0];
}
finish(null, content_type);
})
.on('error', function(error) {
finish(error);
});
}, {disableCache: options.disableCache}, cb);
};
var NOW = new Date().getTime();
exports.unifyDate = function(date) {
if (typeof date === "number") {
if (date === 0) {
return null;
}
// Check if date in seconds, not miliseconds.
if (NOW / date > 100) {
date = date * 1000;
}
var parsedDate = moment(date);
if (parsedDate.isValid()) {
return parsedDate.toJSON();
}
}
// TODO: time in format 'Mon, 29 October 2012 18:15:00' parsed as local timezone anyway.
var parsedDate = moment.utc(date);
if (parsedDate && parsedDate.isValid()) {
return parsedDate.toJSON();
}
return date;
};
var lowerCaseKeys = exports.lowerCaseKeys = function(obj) {
for (var k in obj) {
var lowerCaseKey = k.toLowerCase();
if (lowerCaseKey != k) {
obj[lowerCaseKey] = obj[k];
delete obj[k];
k = lowerCaseKey;
}
if (typeof obj[k] == "object") {
lowerCaseKeys(obj[k]);
}
}
};
exports.sendLogToWhitelist = function(uri, meta, oembed, whitelistRecord) {
if (!CONFIG.WHITELIST_LOG_URL) {
return
}
if (whitelistRecord && !whitelistRecord.isDefault) {
// Skip whitelisted urls.
return;
}
var data = getWhitelistLogData(meta, oembed);
if (data) {
data.uri = uri;
request({
uri: CONFIG.WHITELIST_LOG_URL,
method: 'GET',
qs: data
})
.on('error', function(error) {
console.error('Error logging url:', uri, error);
})
.on('response', function(res) {
if (res.statusCode !== 200) {
console.error('Error logging url:', uri, res.statusCode);
}
});
}
};
exports.filterLinks = function(data, options) {
var links = data.links;
for(var i = 0; i < links.length;) {
var link = links[i];
// SSL.
var isImage = link.type.indexOf('image') === 0;
var isHTML5Video = link.type.indexOf('video/') === 0;
if (options.filterNonSSL) {
var sslProtocol = link.href && link.href.match(/^(https:)?\/\//i);
var hasSSL = link.rel.indexOf('ssl') > -1;
if (sslProtocol || hasSSL || isImage || isHTML5Video) {
// Good: has ssl.
} else {
// Filter non ssl if required.
link.error = true;
}
}
// HTML5.
if (options.filterNonHTML5) {
var hasHTML5 = link.rel.indexOf('html5') > -1;
var isReader = link.rel.indexOf('reader') > -1;
if (hasHTML5 || isImage || isHTML5Video || isReader) {
// Good: is HTML5.
} else {
// Filter non HTML5 if required.
link.error = true;
}
}
// Max-width.
if (options.maxWidth) {
var isImage = link.type.indexOf('image') === 0;
// TODO: force make html5 video responsive?
var isHTML5Video = link.type.indexOf('video/') === 0;
var m = link.media;
if (m && !isImage && !isHTML5Video) {
if (m.width && m.width > options.maxWidth) {
link.error = true;
} else if (m['min-width'] && m['min-width'] > options.maxWidth) {
link.error = true;
}
}
}
if (link.error) {
links.splice(i, 1);
} else {
i++;
}
}
};
function iterateLinks(links, func) {
if (links instanceof Array) {
return links.forEach(func);
} else if (typeof links === 'object') {
for(var id in links) {
var items = links[id];
if (items instanceof Array) {
items.forEach(func);
}
}
}
}
exports.generateLinksHtml = function(data, options) {
// Links may be grouped.
var links = data.links;
iterateLinks(links, function(link) {
if (!link.html && !link.type.match(/^image/)) {
// Force make mp4 video to be autoplay in autoplayMode.
if (options.autoplayMode && link.type.indexOf('video/') === 0 && link.rel.indexOf('autoplay') === -1) {
link.rel.push('autoplay');
}
var html = htmlUtils.generateLinkElementHtml(link, {
iframelyData: data
});
if (html) {
link.html = html;
}
}
});
if (!data.html) {
var links_list = [];
iterateLinks(links, function(link) {
links_list.push(link);
});
var plain_data = _.extend({}, data, {links:links_list});
// Prevent override main html field.
var mainLink = htmlUtils.findMainLink(plain_data, options);
if (mainLink) {
if (mainLink.html) {
data.rel = mainLink.rel;
data.html = mainLink.html;
}
}
}
};
//====================================================================================
// Private
//====================================================================================
var getUriStatus = function(uri, options, cb) {
var r = request({
uri: uri,
method: 'GET',
headers: {
'User-Agent': CONFIG.USER_AGENT
},
maxRedirects: 5,
timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT,
jar: request.jar() //Enable cookies, uses new jar
})
.on('error', cb)
.on('response', function(res) {
r.abort();
cb(null, {
code: res.statusCode,
content_type: res.headers['content-type']
});
});
};
var createTimer = exports.createTimer = function() {
var timer = new Date().getTime();
return function() {
return new Date().getTime() - timer;
};
};
var SHOPIFY_OEMBED_URLS = ['shopify.com', '/collections/', '/products/'];
function isYoutube(meta) {
var video;
if (meta.og && (video = meta.og.video)) {
if (!(video instanceof Array)) {
video = [video];
}
for(var i = 0; i < video.length; i++) {
var v = video[i];
var url = v.url || v;
if (url.indexOf && url.indexOf('youtube') > -1) {
return true;
}
if (v.secure_url && v.secure_url.indexOf && v.secure_url.indexOf('youtube') > -1) {
return true;
}
}
}
return false;
}
function getWhitelistLogData(meta, oembed) {
var r = {};
if (meta) {
var isJetpack = meta.twitter && meta.twitter.card === 'jetpack';
var isWordpress = meta.twitter && meta.twitter.generator === 'wordpress';
var isShopify = false;
if (meta.alternate) {
var alternate = meta.alternate instanceof Array ? meta.alternate : [meta.alternate];
var oembedLink;
for(var i = 0; !oembedLink && i < alternate.length; i++) {
var a = alternate[i];
if (a.type && a.href && a.type.indexOf('oembed') > -1) {
oembedLink = a;
}
}
if (oembedLink) {
for(var i = 0; !isShopify && i < SHOPIFY_OEMBED_URLS.length; i++) {
if (oembedLink.href.indexOf(SHOPIFY_OEMBED_URLS[i]) > -1) {
isShopify = true;
}
}
}
}
r.twitter_photo =
(meta.twitter && meta.twitter.card === 'photo')
&&
(meta.og && meta.og.type !== "article")
&&
!isJetpack
&&
!isWordpress
&&
(meta.twitter && meta.twitter.site !== 'tumblr')
&& (
(meta.twitter && !!meta.twitter.image)
||
(meta.og && !!meta.og.image)
);
r.twitter_player =
meta.twitter && !!meta.twitter.player;
r.twitter_stream =
meta.twitter && meta.twitter.player && !!meta.twitter.player.stream;
r.og_video =
(meta.og && !!meta.og.video)
&& !isYoutube(meta);
r.video_src =
!!meta.video_src;
r.sm4_video =
!!(meta.sm4 && meta.sm4.video && meta.sm4.video.embed)
}
if (oembed && oembed.type !== 'link') {
r['oembed_' + oembed.type] = true;
}
var hasTrue = false;
var result = {};
for(var k in r) {
if (r[k]) {
result[k] = r[k];
hasTrue = true;
}
}
// TODO: embedURL: getEl('[itemprop="embedURL"]')
return hasTrue && result;
}
|
/**
* Copyright 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.
*
* @providesModule dangerousStyleValue
*/
import CSSProperty from './CSSProperty'
import warning from 'fbjs/lib/warning'
let isUnitlessNumber = CSSProperty.isUnitlessNumber
let styleWarnings = {}
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @param {ReactDOMComponent} component
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, component) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
let isEmpty = value == null || typeof value === 'boolean' || value === ''
if (isEmpty) {
return ''
}
let isNonNumeric = isNaN(value)
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value // cast to string
}
if (typeof value === 'string') {
if (process.env.NODE_ENV !== 'production') {
// Allow '0' to pass through without warning. 0 is already special and
// doesn't require units, so we don't need to warn about it.
if (component && value !== '0') {
let owner = component._currentElement._owner
let ownerName = owner ? owner.getName() : null
if (ownerName && !styleWarnings[ownerName]) {
styleWarnings[ownerName] = {}
}
let warned = false
if (ownerName) {
let warnings = styleWarnings[ownerName]
warned = warnings[name]
if (!warned) {
warnings[name] = true
}
}
if (!warned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0
}
}
}
value = value.trim()
}
return value + 'px'
}
export default dangerousStyleValue
|
function CScrollingBg(oSprite){
var _iLastObjIndex;
var _aTiles;
var _oSpriteTile;
this._init = function(oSprite){
_oSpriteTile = oSprite;
_aTiles = new Array();
var iYPos = -oSprite.height;
while( iYPos < CANVAS_HEIGHT){
var oTile = new createjs.Bitmap(oSprite);
oTile.y=iYPos;
iYPos += oSprite.height;
_aTiles.push(oTile);
s_oStage.addChild(oTile);
}
_iLastObjIndex = 0;
};
this.update = function(iSpeed){
for(var i=0;i<_aTiles.length;i++){
if(_aTiles[i].y > CANVAS_HEIGHT){
_aTiles[i].y = _aTiles[_iLastObjIndex].y - (_oSpriteTile.height);
_iLastObjIndex = i;
}
_aTiles[i].y += iSpeed;
}
};
this._init(oSprite);
} |
// generate a hash from string
var crypto = require('crypto'),
text = 'hello bob',
key = 'mysecret key'
// create hahs
var hash = crypto.createHmac('sha512', key)
hash.update(text)
var value = hash.digest('hex')
// print result
console.log(value);
|
module.exports = function ({ serializers, $lookup }) {
serializers.inc.object = function () {
return function (object, $step = 0) {
let $_, $bite
return function $serialize ($buffer, $start, $end) {
switch ($step) {
case 0:
$step = 1
$bite = 7n
$_ = object.value
case 1:
while ($bite != -1n) {
if ($start == $end) {
return { start: $start, serialize: $serialize }
}
$buffer[$start++] = Number($_ >> $bite * 8n & 0xffn)
$bite--
}
$step = 2
case 2:
break
}
return { start: $start, serialize: null }
}
}
} ()
}
|
import applicationActions from '../../constants/application';
import productActions from '../../constants/products';
export default function fetchProductAndCheckIfFound(context, payload, done) {
context.dispatch(productActions.PRODUCTS_ITEM);
context.api.products.get(payload).then(function successFn(result) {
context.dispatch(productActions.PRODUCTS_ITEM_SUCCESS, result);
done && done();
}, function errorFn(err) {
context.dispatch(productActions.PRODUCTS_ITEM_ERROR, err.result);
context.dispatch(applicationActions.APPLICATION_ROUTE_ERROR, err.status);
done && done();
});
}
|
(function() {
'use strict';
angular.module('ionic.ui.service.sideMenuDelegate', [])
.factory('$ionicSideMenuDelegate', ['$rootScope', '$timeout', '$q', function($rootScope, $timeout, $q) {
return {
getSideMenuController: function($scope) {
return $scope.sideMenuController;
},
close: function($scope) {
if($scope.sideMenuController) {
$scope.sideMenuController.close();
}
},
toggleLeft: function($scope) {
if($scope.sideMenuController) {
$scope.sideMenuController.toggleLeft();
}
},
toggleRight: function($scope) {
if($scope.sideMenuController) {
$scope.sideMenuController.toggleRight();
}
},
openLeft: function($scope) {
if($scope.sideMenuController) {
$scope.sideMenuController.openPercentage(100);
}
},
openRight: function($scope) {
if($scope.sideMenuController) {
$scope.sideMenuController.openPercentage(-100);
}
}
};
}]);
})();
|
/* */
"format global";
jasmine.HtmlReporterHelpers = {};
jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) {
var el = document.createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else {
if (child) {
el.appendChild(child);
}
}
}
for (var attr in attrs) {
if (attr == "className") {
el[attr] = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
}
return el;
};
jasmine.HtmlReporterHelpers.getSpecStatus = function(child) {
var results = child.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.skipped) {
status = 'skipped';
}
return status;
};
jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) {
var parentDiv = this.dom.summary;
var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite';
var parent = child[parentSuite];
if (parent) {
if (typeof this.views.suites[parent.id] == 'undefined') {
this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views);
}
parentDiv = this.views.suites[parent.id].element;
}
parentDiv.appendChild(childElement);
};
jasmine.HtmlReporterHelpers.addHelpers = function(ctor) {
for(var fn in jasmine.HtmlReporterHelpers) {
ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn];
}
};
jasmine.HtmlReporter = function(_doc) {
var self = this;
var doc = _doc || window.document;
var reporterView;
var dom = {};
// Jasmine Reporter Public Interface
self.logRunningSpecs = false;
self.reportRunnerStarting = function(runner) {
var specs = runner.specs() || [];
if (specs.length == 0) {
return;
}
createReporterDom(runner.env.versionString());
doc.body.appendChild(dom.reporter);
reporterView = new jasmine.HtmlReporter.ReporterView(dom);
reporterView.addSpecs(specs, self.specFilter);
};
self.reportRunnerResults = function(runner) {
reporterView && reporterView.complete();
};
self.reportSuiteResults = function(suite) {
reporterView.suiteComplete(suite);
};
self.reportSpecStarting = function(spec) {
if (self.logRunningSpecs) {
self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
}
};
self.reportSpecResults = function(spec) {
reporterView.specComplete(spec);
};
self.log = function() {
var console = jasmine.getGlobal().console;
if (console && console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
}
}
};
self.specFilter = function(spec) {
if (!focusedSpecName()) {
return true;
}
return spec.getFullName().indexOf(focusedSpecName()) === 0;
};
return self;
function focusedSpecName() {
var specName;
(function memoizeFocusedSpec() {
if (specName) {
return;
}
var paramMap = [];
var params = doc.location.search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
}
specName = paramMap.spec;
})();
return specName;
}
function createReporterDom(version) {
dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' },
dom.banner = self.createDom('div', { className: 'banner' },
self.createDom('span', { className: 'title' }, "Jasmine "),
self.createDom('span', { className: 'version' }, version)),
dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}),
dom.alert = self.createDom('div', {className: 'alert'}),
dom.results = self.createDom('div', {className: 'results'},
dom.summary = self.createDom('div', { className: 'summary' }),
dom.details = self.createDom('div', { id: 'details' }))
);
}
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);jasmine.HtmlReporter.ReporterView = function(dom) {
this.startedAt = new Date();
this.runningSpecCount = 0;
this.completeSpecCount = 0;
this.passedCount = 0;
this.failedCount = 0;
this.skippedCount = 0;
this.createResultsMenu = function() {
this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'},
this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'),
' | ',
this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing'));
this.summaryMenuItem.onclick = function() {
dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, '');
};
this.detailsMenuItem.onclick = function() {
showDetails();
};
};
this.addSpecs = function(specs, specFilter) {
this.totalSpecCount = specs.length;
this.views = {
specs: {},
suites: {}
};
for (var i = 0; i < specs.length; i++) {
var spec = specs[i];
this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views);
if (specFilter(spec)) {
this.runningSpecCount++;
}
}
};
this.specComplete = function(spec) {
this.completeSpecCount++;
if (isUndefined(this.views.specs[spec.id])) {
this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom);
}
var specView = this.views.specs[spec.id];
switch (specView.status()) {
case 'passed':
this.passedCount++;
break;
case 'failed':
this.failedCount++;
break;
case 'skipped':
this.skippedCount++;
break;
}
specView.refresh();
this.refresh();
};
this.suiteComplete = function(suite) {
var suiteView = this.views.suites[suite.id];
if (isUndefined(suiteView)) {
return;
}
suiteView.refresh();
};
this.refresh = function() {
if (isUndefined(this.resultsMenu)) {
this.createResultsMenu();
}
// currently running UI
if (isUndefined(this.runningAlert)) {
this.runningAlert = this.createDom('a', {href: "?", className: "runningAlert bar"});
dom.alert.appendChild(this.runningAlert);
}
this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount);
// skipped specs UI
if (isUndefined(this.skippedAlert)) {
this.skippedAlert = this.createDom('a', {href: "?", className: "skippedAlert bar"});
}
this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
if (this.skippedCount === 1 && isDefined(dom.alert)) {
dom.alert.appendChild(this.skippedAlert);
}
// passing specs UI
if (isUndefined(this.passedAlert)) {
this.passedAlert = this.createDom('span', {href: "?", className: "passingAlert bar"});
}
this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount);
// failing specs UI
if (isUndefined(this.failedAlert)) {
this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"});
}
this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount);
if (this.failedCount === 1 && isDefined(dom.alert)) {
dom.alert.appendChild(this.failedAlert);
dom.alert.appendChild(this.resultsMenu);
}
// summary info
this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount);
this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing";
};
this.complete = function() {
dom.alert.removeChild(this.runningAlert);
this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all";
if (this.failedCount === 0) {
dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount)));
} else {
showDetails();
}
dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"));
};
return this;
function showDetails() {
if (dom.reporter.className.search(/showDetails/) === -1) {
dom.reporter.className += " showDetails";
}
}
function isUndefined(obj) {
return typeof obj === 'undefined';
}
function isDefined(obj) {
return !isUndefined(obj);
}
function specPluralizedFor(count) {
var str = count + " spec";
if (count > 1) {
str += "s"
}
return str;
}
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView);
jasmine.HtmlReporter.SpecView = function(spec, dom, views) {
this.spec = spec;
this.dom = dom;
this.views = views;
this.symbol = this.createDom('li', { className: 'pending' });
this.dom.symbolSummary.appendChild(this.symbol);
this.summary = this.createDom('div', { className: 'specSummary' },
this.createDom('a', {
className: 'description',
href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
title: this.spec.getFullName()
}, this.spec.description)
);
this.detail = this.createDom('div', { className: 'specDetail' },
this.createDom('a', {
className: 'description',
href: '?spec=' + encodeURIComponent(this.spec.getFullName()),
title: this.spec.getFullName()
}, this.spec.getFullName())
);
};
jasmine.HtmlReporter.SpecView.prototype.status = function() {
return this.getSpecStatus(this.spec);
};
jasmine.HtmlReporter.SpecView.prototype.refresh = function() {
this.symbol.className = this.status();
switch (this.status()) {
case 'skipped':
break;
case 'passed':
this.appendSummaryToSuiteDiv();
break;
case 'failed':
this.appendSummaryToSuiteDiv();
this.appendFailureDetail();
break;
}
};
jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() {
this.summary.className += ' ' + this.status();
this.appendToSummary(this.spec, this.summary);
};
jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() {
this.detail.className += ' ' + this.status();
var resultItems = this.spec.results().getItems();
var messagesDiv = this.createDom('div', { className: 'messages' });
for (var i = 0; i < resultItems.length; i++) {
var result = resultItems[i];
if (result.type == 'log') {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
} else if (result.type == 'expect' && result.passed && !result.passed()) {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
if (result.trace.stack) {
messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
}
}
}
if (messagesDiv.childNodes.length > 0) {
this.detail.appendChild(messagesDiv);
this.dom.details.appendChild(this.detail);
}
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) {
this.suite = suite;
this.dom = dom;
this.views = views;
this.element = this.createDom('div', { className: 'suite' },
this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.suite.getFullName()) }, this.suite.description)
);
this.appendToSummary(this.suite, this.element);
};
jasmine.HtmlReporter.SuiteView.prototype.status = function() {
return this.getSpecStatus(this.suite);
};
jasmine.HtmlReporter.SuiteView.prototype.refresh = function() {
this.element.className += " " + this.status();
};
jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView);
/* @deprecated Use jasmine.HtmlReporter instead
*/
jasmine.TrivialReporter = function(doc) {
this.document = doc || document;
this.suiteDivs = {};
this.logRunningSpecs = false;
};
jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) {
var el = document.createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else {
if (child) { el.appendChild(child); }
}
}
for (var attr in attrs) {
if (attr == "className") {
el[attr] = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
}
return el;
};
jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) {
var showPassed, showSkipped;
this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' },
this.createDom('div', { className: 'banner' },
this.createDom('div', { className: 'logo' },
this.createDom('span', { className: 'title' }, "Jasmine"),
this.createDom('span', { className: 'version' }, runner.env.versionString())),
this.createDom('div', { className: 'options' },
"Show ",
showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
)
),
this.runnerDiv = this.createDom('div', { className: 'runner running' },
this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
);
this.document.body.appendChild(this.outerDiv);
var suites = runner.suites();
for (var i = 0; i < suites.length; i++) {
var suite = suites[i];
var suiteDiv = this.createDom('div', { className: 'suite' },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description));
this.suiteDivs[suite.id] = suiteDiv;
var parentDiv = this.outerDiv;
if (suite.parentSuite) {
parentDiv = this.suiteDivs[suite.parentSuite.id];
}
parentDiv.appendChild(suiteDiv);
}
this.startedAt = new Date();
var self = this;
showPassed.onclick = function(evt) {
if (showPassed.checked) {
self.outerDiv.className += ' show-passed';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
}
};
showSkipped.onclick = function(evt) {
if (showSkipped.checked) {
self.outerDiv.className += ' show-skipped';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
}
};
};
jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
var results = runner.results();
var className = (results.failedCount > 0) ? "runner failed" : "runner passed";
this.runnerDiv.setAttribute("class", className);
//do it twice for IE
this.runnerDiv.setAttribute("className", className);
var specs = runner.specs();
var specCount = 0;
for (var i = 0; i < specs.length; i++) {
if (this.specFilter(specs[i])) {
specCount++;
}
}
var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s");
message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s";
this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild);
this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString()));
};
jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
var results = suite.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.totalCount === 0) { // todo: change this to check results.skipped
status = 'skipped';
}
this.suiteDivs[suite.id].className += " " + status;
};
jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) {
if (this.logRunningSpecs) {
this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
}
};
jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) {
var results = spec.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.skipped) {
status = 'skipped';
}
var specDiv = this.createDom('div', { className: 'spec ' + status },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"),
this.createDom('a', {
className: 'description',
href: '?spec=' + encodeURIComponent(spec.getFullName()),
title: spec.getFullName()
}, spec.description));
var resultItems = results.getItems();
var messagesDiv = this.createDom('div', { className: 'messages' });
for (var i = 0; i < resultItems.length; i++) {
var result = resultItems[i];
if (result.type == 'log') {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
} else if (result.type == 'expect' && result.passed && !result.passed()) {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
if (result.trace.stack) {
messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
}
}
}
if (messagesDiv.childNodes.length > 0) {
specDiv.appendChild(messagesDiv);
}
this.suiteDivs[spec.suite.id].appendChild(specDiv);
};
jasmine.TrivialReporter.prototype.log = function() {
var console = jasmine.getGlobal().console;
if (console && console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
}
}
};
jasmine.TrivialReporter.prototype.getLocation = function() {
return this.document.location;
};
jasmine.TrivialReporter.prototype.specFilter = function(spec) {
var paramMap = {};
var params = this.getLocation().search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
}
if (!paramMap.spec) {
return true;
}
return spec.getFullName().indexOf(paramMap.spec) === 0;
};
|
"use strict";
const Channel = require("./Channel");
const Collection = require("../util/Collection");
const Endpoints = require("../rest/Endpoints");
const Message = require("./Message");
const OPCodes = require("../Constants").GatewayOPCodes;
const User = require("./User");
/**
* Represents a private channel
* @extends Channel
* @prop {String} id The ID of the channel
* @prop {String} mention A string that mentions the channel
* @prop {Number} type The type of the channel
* @prop {String} lastMessageID The ID of the last message in this channel
* @prop {User} recipient The recipient in this private channel (private channels only)
* @prop {Collection<Message>} messages Collection of Messages in this channel
*/
class PrivateChannel extends Channel {
constructor(data, client) {
super(data);
this._client = client;
this.lastMessageID = data.last_message_id;
this.call = this.lastCall = null;
if(this.type === 1 || this.type === undefined) {
this.recipient = new User(data.recipients[0], client);
}
this.messages = new Collection(Message, client.options.messageLimit);
}
/**
* Ring fellow group channel recipient(s)
* @arg {String[]} recipients The IDs of the recipients to ring
*/
ring(recipients) {
this._client.requestHandler.request("POST", Endpoints.CHANNEL_CALL_RING(this.id), true, {
recipients
});
}
/**
* Check if the channel has an existing call
*/
syncCall() {
this._client.shards.values().next().value.sendWS(OPCodes.SYNC_CALL, {
channel_id: this.id
});
}
/**
* Leave the channel
* @returns {Promise}
*/
leave() {
return this._client.deleteChannel.call(this._client, this.id);
}
/**
* Send typing status in a text channel
* @returns {Promise}
*/
sendTyping() {
return (this._client || this.guild.shard.client).sendChannelTyping.call((this._client || this.guild.shard.client), this.id);
}
/**
* Get a previous message in a text channel
* @arg {String} messageID The ID of the message
* @returns {Promise<Message>}
*/
getMessage(messageID) {
return (this._client || this.guild.shard.client).getMessage.call((this._client || this.guild.shard.client), this.id, messageID);
}
/**
* Get a previous message in a text channel
* @arg {Number} [limit=50] The max number of messages to get
* @arg {String} [before] Get messages before this message ID
* @arg {String} [after] Get messages after this message ID
* @arg {String} [around] Get messages around this message ID (does not work with limit > 100)
* @returns {Promise<Message[]>}
*/
getMessages(limit, before, after, around) {
return (this._client || this.guild.shard.client).getMessages.call((this._client || this.guild.shard.client), this.id, limit, before, after, around);
}
/**
* Get all the pins in a text channel
* @returns {Promise<Message[]>}
*/
getPins() {
return (this._client || this.guild.shard.client).getPins.call((this._client || this.guild.shard.client), this.id);
}
/**
* Create a message in a text channel
* Note: If you want to DM someone, the user ID is **not** the DM channel ID. use Client.getDMChannel() to get the DM channel ID for a user
* @arg {String | Object} content A string or object. If an object is passed:
* @arg {String} content.content A content string
* @arg {Boolean} [content.tts] Set the message TTS flag
* @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
* @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
* @arg {Object} [file] A file object
* @arg {String} file.file A buffer containing file data
* @arg {String} file.name What to name the file
* @returns {Promise<Message>}
*/
createMessage(content, file) {
return (this._client || this.guild.shard.client).createMessage.call((this._client || this.guild.shard.client), this.id, content, file);
}
/**
* Edit a message
* @arg {String} messageID The ID of the message
* @arg {String | Array | Object} content A string, array of strings, or object. If an object is passed:
* @arg {String} content.content A content string
* @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
* @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
* @returns {Promise<Message>}
*/
editMessage(messageID, content) {
return (this._client || this.guild.shard.client).editMessage.call((this._client || this.guild.shard.client), this.id, messageID, content);
}
/**
* Pin a message
* @arg {String} messageID The ID of the message
* @returns {Promise}
*/
pinMessage(messageID) {
return (this._client || this.guild.shard.client).pinMessage.call((this._client || this.guild.shard.client), this.id, messageID);
}
/**
* Unpin a message
* @arg {String} messageID The ID of the message
* @returns {Promise}
*/
unpinMessage(messageID) {
return (this._client || this.guild.shard.client).unpinMessage.call((this._client || this.guild.shard.client), this.id, messageID);
}
/**
* Get a list of users who reacted with a specific reaction
* @arg {String} messageID The ID of the message
* @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
* @arg {Number} [limit=100] The maximum number of users to get
* @arg {String} [before] Get users before this user ID
* @arg {String} [after] Get users after this user ID
* @returns {Promise<User[]>}
*/
getMessageReaction(messageID, reaction, limit, before, after) {
return (this._client || this.guild.shard.client).getMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, limit, before, after);
}
/**
* Add a reaction to a message
* @arg {String} messageID The ID of the message
* @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
* @arg {String} [userID="@me"] The ID of the user to react as
* @returns {Promise}
*/
addMessageReaction(messageID, reaction, userID) {
return (this._client || this.guild.shard.client).addMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, userID);
}
/**
* Remove a reaction from a message
* @arg {String} messageID The ID of the message
* @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
* @arg {String} [userID="@me"] The ID of the user to remove the reaction for
* @returns {Promise}
*/
removeMessageReaction(messageID, reaction, userID) {
return (this._client || this.guild.shard.client).removeMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, userID);
}
/**
* Remove all reactions from a message
* @arg {String} messageID The ID of the message
* @returns {Promise}
*/
removeMessageReactions(messageID) {
return (this._client || this.guild.shard.client).removeMessageReactions.call((this._client || this.guild.shard.client), this.id, messageID);
}
/**
* Delete a message
* @arg {String} messageID The ID of the message
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise}
*/
deleteMessage(messageID, reason) {
return (this._client || this.guild.shard.client).deleteMessage.call((this._client || this.guild.shard.client), this.id, messageID, reason);
}
/**
* Un-send a message. You're welcome Programmix
* @arg {String} messageID The ID of the message
* @returns {Promise}
*/
unsendMessage(messageID) {
return (this._client || this.guild.shard.client).deleteMessage.call((this._client || this.guild.shard.client), this.id, messageID);
}
toJSON() {
var base = super.toJSON(true);
for(var prop of ["call", "lastCall", "lastMessageID", "messages", "recipient"]) {
base[prop] = this[prop] && this[prop].toJSON ? this[prop].toJSON() : this[prop];
}
return base;
}
}
module.exports = PrivateChannel; |
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require select2
//= require has_accounts_engine/accounting
//= require has_accounts_engine/accounting-jquery
//= require has_accounts_engine/bootstrap.datepicker
//= require_tree .
// Application specific behaviour
function addAlternateTableBehaviour() {
$("table.list tr:odd").addClass("odd");
}
// Dirty Form
function makeEditForm(form) {
var buttons = form.find("fieldset.buttons");
buttons.animate({opacity: 1}, 1000);
}
function addDirtyForm() {
$(".form-view form").dirty_form()
.dirty(function(event, data){
makeEditForm($(this));
})
$(".form-view").focusin(function() {makeEditForm($(this))});
}
function addNestedFormBehaviour() {
$('body').on('click', '.delete-nested-form-item', function(event) {
var item = $(this).parents('.nested-form-item');
// Hide item
item.hide();
// Mark as ready to delete
item.find("input[name$='[_destroy]']").val("1");
item.addClass('delete');
// Drop input fields to prevent browser validation problems
item.find(":input").not("[name$='[_destroy]'], [name$='[id]']").remove();
// TODO: should be callbacks
updatePositions($(this).parents('.nested-form-container'));
updateLineItems();
// Don't follow link
event.preventDefault();
});
}
// Currency helpers
function currencyRound(value) {
if (isNaN(value)) {
return 0.0;
};
rounded = Math.round(value * 20) / 20;
return rounded.toFixed(2);
}
// Line Item calculation
function updateLineItemPrice(lineItem) {
var list = lineItem.parent();
var reference_code = lineItem.find(":input[name$='[reference_code]']").val();
var quantity = lineItem.find(":input[name$='[quantity]']").val();
if (quantity == '%' || quantity == 'saldo_of') {
var included_items;
if (reference_code == '') {
included_items = lineItem.prevAll('.line_item');
} else {
// Should match using ~= but acts_as_taggable_adds_colons between tags
included_items = list.find(":input[name$='[code]'][value='" + reference_code + "']").parents('.line_item, .saldo_line_item');
if (included_items.length == 0) {
// Should match using ~= but acts_as_taggable_adds_colons between tags
included_items = list.find(":input[name$='[include_in_saldo_list]'][value*='" + reference_code + "']").parents('.line_item, .saldo_line_item');
}
}
var price_input = lineItem.find(":input[name$='[price]']");
price_input.val(calculateTotalAmount(included_items));
}
}
function updateAllLineItemPrices() {
$('.line_item, .saldo_line_item').each(function() {
updateLineItemPrice($(this));
});
}
function calculateLineItemTotalAmount(lineItem) {
var times_input = lineItem.find(":input[name$='[times]']");
var times = accounting.parse(times_input.val());
if (isNaN(times)) {
times = 1;
};
var quantity_input = lineItem.find(":input[name$='[quantity]']");
var price_input = lineItem.find(":input[name$='[price]']");
var price = accounting.parse(price_input.val());
// For 'saldo_of' items, we don't take accounts into account
if (quantity_input.val() == "saldo_of") {
return currencyRound(price);
};
var direct_account_id = $('#line_items').data('direct-account-id');
var direct_account_factor = $('#line_items').data('direct-account-factor');
var factor = 0;
if (lineItem.find(":input[name$='[credit_account_id]']").val() == direct_account_id) {
factor = 1;
};
if (lineItem.find(":input[name$='[debit_account_id]']").val() == direct_account_id) {
factor = -1;
};
if (quantity_input.val() == '%') {
times = times / 100;
};
return currencyRound(times * price * factor * direct_account_factor);
}
function updateLineItemTotalAmount(lineItem) {
var total_amount_input = lineItem.find(".total_amount");
var total_amount = accounting.formatNumber(calculateLineItemTotalAmount(lineItem));
// Update Element
total_amount_input.text(total_amount);
}
function calculateTotalAmount(lineItems) {
var total_amount = 0;
$(lineItems).each(function() {
total_amount += accounting.parse($(this).find(".total_amount").text());
});
return currencyRound(total_amount);
}
function updateLineItems() {
if ($('#line_items').length > 0) {
$('.line_item, .saldo_line_item').each(function() {
updateLineItemPrice($(this));
updateLineItemTotalAmount($(this));
});
};
}
// Recalculate after every key stroke
function handleLineItemChange(event) {
// If character is <return>
if(event.keyCode == 13) {
// ...trigger form action
$(event.currentTarget).submit();
} else if(event.keyCode == 32) {
// ...trigger form action
$(event.currentTarget).submit();
} else {
updateLineItems();
}
}
function addCalculateTotalAmountBehaviour() {
$("#line_items").find(":input[name$='[times]'], :input[name$='[quantity]'], :input[name$='[price]'], input[name$='[reference_code]']").on('keyup', handleLineItemChange);
$("#line_items").bind("sortstop", handleLineItemChange);
}
// Sorting
function updatePositions(collection) {
var items = collection.find('.nested-form-item').not('.delete');
items.each(function(index, element) {
$(this).find("input[id$='_position']").val(index + 1)
});
}
function initAccounting() {
// accounting.js
// Settings object that controls default parameters for library methods:
accounting.settings = {
currency: {
symbol : "", // default currency symbol is '$'
format: "%v", // controls output: %s = symbol, %v = value/number (can be object: see below)
decimal : ".", // decimal point separator
thousand: "'", // thousands separator
precision : 2 // decimal places
},
number: {
precision : 2, // default precision on numbers is 0
thousand: "'",
decimal : "."
}
}
}
// Initialize behaviours
function initializeBehaviours() {
// Init settings
initAccounting();
// from cyt.js
addComboboxBehaviour();
addAutofocusBehaviour();
addDatePickerBehaviour();
addLinkifyContainersBehaviour();
addIconTooltipBehaviour();
addModalBehaviour();
// application
addAlternateTableBehaviour();
addNestedFormBehaviour();
addCalculateTotalAmountBehaviour();
updateLineItems();
// twitter bootstrap
$(function () {
$(".alert").alert();
$("*[rel=popover]").popover({
offset: 10
});
$('.small-tooltip').tooltip({
placement: 'right'
});
})
// select2
$('.select2').select2({
allowClear: true
});
$('.select2-tags').each(function(index, element) {
var tags = $(element).data('tags') || '';
$(element).select2({
tags: tags,
tokenSeparators: [","]
})
})
}
// Loads functions after DOM is ready
$(document).ready(initializeBehaviours);
|
/*
* function Component with Hooks: Modify ./index.js to apply this file
*/
import React, { useState, useLayoutEffect } from 'react';
import './App.css';
import logo from './logo.svg';
import tplsrc from './views/showing-click-times.liquid';
import Parser from 'html-react-parser';
import { engine } from './engine';
import { Context } from './Context';
import { ClickButton } from './ClickButton';
const fetchTpl = engine.getTemplate(tplsrc.toString())
export function App() {
const [state, setState] = useState({
logo: logo,
name: 'alice',
clickCount: 0,
html: ''
});
useLayoutEffect(() => {
fetchTpl
.then(tpl => engine.render(tpl, state))
.then(html => setState({...state, html}))
}, [state.clickCount])
return (
<div className="App">
{Parser(`${state.html}`)}
<Context.Provider
value={{
count: () => setState({...state, clickCount: state.clickCount + 1})
}}
>
<ClickButton/>
</Context.Provider>
</div>
);
}
|
function tree(tasks) {
return Object.keys(tasks)
.reduce(function(prev, task) {
prev.nodes.push({
label: task,
nodes: Object.keys(tasks[task]).map(function(x){ return x; })
});
return prev;
}, {
nodes: [],
});
}
module.exports = tree;
|
if (!Buffer.concat) {
Buffer.concat = function(buffers) {
const buffersCount = buffers.length;
let length = 0;
for (let i = 0; i < buffersCount; i++) {
const buffer = buffers[i];
length += buffer.length;
}
const result = new Buffer(length);
let position = 0;
for (let i = 0; i < buffersCount; i++) {
const buffer = buffers[i];
buffer.copy(result, position, 0);
position += buffer.length;
}
return result;
};
}
Buffer.prototype.toByteArray = function() {
return Array.prototype.slice.call(this, 0);
};
Buffer.prototype.equals = function(other) {
if (this.length !== other.length) {
return false;
}
for (let i = 0, len = this.length; i < len; i++) {
if (this[i] !== other[i]) {
return false;
}
}
return true;
};
|
import React, { Component, } from 'react';
import {
StyleSheet,
View,
} from 'react-native';
export default class Col extends Component {
render() {
return (
<View style={[styles.col, { flex: parseInt(this.props.span) }, this.props.style]}>{this.props.children}</View>
)
}
}
const styles = StyleSheet.create({
col: {
}
}); |
module.exports = function(){ return 'd0' }
|
/**
* Created by IvanIsrael on 06/04/2017.
*/
'use strict';
const express = require('express');
const router = express.Router();
const user_controller = require("../controllers/users");
const methods = user_controller.methods;
const controllers = user_controller.controllers;
const passport = require('passport');
/* GET users listing. */
router.post('/', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '../users',
failureFlash: true
}));
router.get('/logout', function(req, res, next){
try {
req.logOut();
console.log("Cerrando sesion...");
res.redirect('../users');
}
catch (e) {
console.log(e);
res.redirect('../users');
}
});
module.exports = router;
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z" /><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V3c0-.55-.45-1-1-1h-2c-.55 0-1 .45-1 1v1H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z" /></g></React.Fragment>
, 'Battery20Rounded');
|
import { createRenderer } from 'fela'
import cssifyStaticStyle from '../cssifyStaticStyle'
describe('Cssifying static css declarations', () => {
it('should return the minified style string', () => {
expect(cssifyStaticStyle('.foo{color:red}')).toEqual('.foo{color:red}')
expect(
cssifyStaticStyle(
`
.foo {
color: red
}
`
)
).toEqual('.foo {color: red}')
})
it('should cssify the static style', () => {
expect(
cssifyStaticStyle(
{
color: 'red',
WebkitTransitionDuration: 3
},
createRenderer()
)
).toEqual('color:red;-webkit-transition-duration:3')
})
})
|
define([
'aeris/util',
'aeris/errors/invalidargumenterror',
'aeris/maps/layers/aeristile'
], function(_, InvalidArgumentError, AerisTile) {
/**
* Representation of an Aeris Modis layer.
*
* @constructor
* @class aeris.maps.layers.ModisTile
* @extends aeris.maps.layers.AerisTile
*/
var ModisTile = function(opt_attrs, opt_options) {
var options = _.extend({
period: 14
}, opt_options);
var attrs = _.extend({
autoUpdateInterval: AerisTile.updateIntervals.MODIS,
/**
* Hash of available tileType codes by period
* Used to dynamically create layer's tileType
*
* @attribute modisPeriodTileTypes
* @type {Object.<number, string>}
*/
modisPeriodTileTypes: {
/* eg
1: "modis_tileType_1day",
3: "modis_tileType_3day"
*/
}
}, opt_attrs);
// Set initial tileType
_.extend(attrs, {
tileType: attrs.modisPeriodTileTypes[options.period]
});
AerisTile.call(this, attrs, opt_options);
this.setModisPeriod(options.period);
};
// Inherit from AerisTile
_.inherits(ModisTile, AerisTile);
/**
* @param {number} period
* @throws {aeris.errors.InvalidArgumentError} If the layer does not support the given MODIS period.
*/
ModisTile.prototype.setModisPeriod = function(period) {
var validPeriods = _.keys(this.get('modisPeriodTileTypes'));
period = parseInt(period);
// Validate period
if (!period || period < 1) {
throw new InvalidArgumentError('Invalid MODIS period: period must be a positive integer');
}
if (!(period in this.get('modisPeriodTileTypes'))) {
throw new InvalidArgumentError('Invalid MODIS periods: available periods are: ' + validPeriods.join(','));
}
// Set new tile type
this.set('tileType', this.get('modisPeriodTileTypes')[period], { validate: true });
};
return ModisTile;
});
|
goo.V.attachToGlobal();
V.describe('GridRenderSystem Test');
var gooRunner = V.initGoo();
var world = gooRunner.world;
var gridRenderSystem = new GridRenderSystem();
gooRunner.renderSystems.push(gridRenderSystem);
world.setSystem(gridRenderSystem);
V.addLights();
document.body.addEventListener('keypress', function (e) {
switch (e.keyCode) {
case 49:
break;
case 50:
break;
case 51:
break;
}
});
// camera 1 - spinning
// var cameraEntity = V.addOrbitCamera(new Vector3(25, 0, 0));
// cameraEntity.cameraComponent.camera.setFrustumPerspective(null, null, 1, 10000);
// add camera
var camera = new Camera(undefined, undefined, 1, 10000);
var cameraEntity = gooRunner.world.createEntity(camera, 'CameraEntity', [0, 10, 20]).lookAt([0, 0, 0]).addToWorld();
// camera control set up
var scripts = new ScriptComponent();
var wasdScript = Scripts.create('WASD', {
domElement: gooRunner.renderer.domElement,
walkSpeed: 1000,
crawlSpeed: 20
});
// WASD control script to move around
scripts.scripts.push(wasdScript);
// the FPCam script itself that locks the pointer and moves the camera
var fpScript = Scripts.create('MouseLookScript', {
domElement: gooRunner.renderer.domElement
});
scripts.scripts.push(fpScript);
cameraEntity.setComponent(scripts);
world.createEntity('Box', new Box(20, 0.1, 20), new Material(ShaderLib.simpleLit)).addToWorld();
world.createEntity('Sphere', new Sphere(8, 8, 1), new Material(ShaderLib.simpleLit)).addToWorld();
V.process(); |
window.React = require('react');
var App = require('./components/App.react');
var css = require('./../css/app.css');
require('../img/social_media.png');
React.initializeTouchEvents(true);
// Render the app component (js/components/App.react.js)
React.render(
<App />,
document.getElementById('app')
);
|
var gulp = require('gulp');
var config = require('./config');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
gulp.task('cover', function() {
return gulp.src(config.tests.unit, { read: false })
.pipe(mocha({
reporter: 'dot',
ui: 'mocha-given',
require: ['coffee-script/register', 'should', 'should-sinon']
}))
.pipe(istanbul.writeReports());
});
|
//>>built
define({invalidMessage:"Angivet v\u00e4rde \u00e4r inte giltigt.",missingMessage:"V\u00e4rdet kr\u00e4vs.",rangeMessage:"V\u00e4rdet ligger utanf\u00f6r intervallet."}); |
import React from 'react'
import styles from './Toast.scss'
export default ({ className, message, show }) => (
<div
className={[
styles.container,
'animated',
'fadeIn',
].concat(className).join(' ')}
style={{ display: show ? 'block' : 'none' }}
>
{message}
</div>
)
|
"use strict";
var $protobuf = require("../..");
module.exports = exports = $protobuf.descriptor = $protobuf.Root.fromJSON(require("../../google/protobuf/descriptor.json")).lookup(".google.protobuf");
var Namespace = $protobuf.Namespace,
Root = $protobuf.Root,
Enum = $protobuf.Enum,
Type = $protobuf.Type,
Field = $protobuf.Field,
MapField = $protobuf.MapField,
OneOf = $protobuf.OneOf,
Service = $protobuf.Service,
Method = $protobuf.Method;
// --- Root ---
/**
* Properties of a FileDescriptorSet message.
* @interface IFileDescriptorSet
* @property {IFileDescriptorProto[]} file Files
*/
/**
* Properties of a FileDescriptorProto message.
* @interface IFileDescriptorProto
* @property {string} [name] File name
* @property {string} [package] Package
* @property {*} [dependency] Not supported
* @property {*} [publicDependency] Not supported
* @property {*} [weakDependency] Not supported
* @property {IDescriptorProto[]} [messageType] Nested message types
* @property {IEnumDescriptorProto[]} [enumType] Nested enums
* @property {IServiceDescriptorProto[]} [service] Nested services
* @property {IFieldDescriptorProto[]} [extension] Nested extension fields
* @property {IFileOptions} [options] Options
* @property {*} [sourceCodeInfo] Not supported
* @property {string} [syntax="proto2"] Syntax
*/
/**
* Properties of a FileOptions message.
* @interface IFileOptions
* @property {string} [javaPackage]
* @property {string} [javaOuterClassname]
* @property {boolean} [javaMultipleFiles]
* @property {boolean} [javaGenerateEqualsAndHash]
* @property {boolean} [javaStringCheckUtf8]
* @property {IFileOptionsOptimizeMode} [optimizeFor=1]
* @property {string} [goPackage]
* @property {boolean} [ccGenericServices]
* @property {boolean} [javaGenericServices]
* @property {boolean} [pyGenericServices]
* @property {boolean} [deprecated]
* @property {boolean} [ccEnableArenas]
* @property {string} [objcClassPrefix]
* @property {string} [csharpNamespace]
*/
/**
* Values of he FileOptions.OptimizeMode enum.
* @typedef IFileOptionsOptimizeMode
* @type {number}
* @property {number} SPEED=1
* @property {number} CODE_SIZE=2
* @property {number} LITE_RUNTIME=3
*/
/**
* Creates a root from a descriptor set.
* @param {IFileDescriptorSet|Reader|Uint8Array} descriptor Descriptor
* @returns {Root} Root instance
*/
Root.fromDescriptor = function fromDescriptor(descriptor) {
// Decode the descriptor message if specified as a buffer:
if (typeof descriptor.length === "number")
descriptor = exports.FileDescriptorSet.decode(descriptor);
var root = new Root();
if (descriptor.file) {
var fileDescriptor,
filePackage;
for (var j = 0, i; j < descriptor.file.length; ++j) {
filePackage = root;
if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length)
filePackage = root.define(fileDescriptor["package"]);
if (fileDescriptor.name && fileDescriptor.name.length)
root.files.push(filePackage.filename = fileDescriptor.name);
if (fileDescriptor.messageType)
for (i = 0; i < fileDescriptor.messageType.length; ++i)
filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], fileDescriptor.syntax));
if (fileDescriptor.enumType)
for (i = 0; i < fileDescriptor.enumType.length; ++i)
filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i]));
if (fileDescriptor.extension)
for (i = 0; i < fileDescriptor.extension.length; ++i)
filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i]));
if (fileDescriptor.service)
for (i = 0; i < fileDescriptor.service.length; ++i)
filePackage.add(Service.fromDescriptor(fileDescriptor.service[i]));
var opts = fromDescriptorOptions(fileDescriptor.options, exports.FileOptions);
if (opts) {
var ks = Object.keys(opts);
for (i = 0; i < ks.length; ++i)
filePackage.setOption(ks[i], opts[ks[i]]);
}
}
}
return root;
};
/**
* Converts a root to a descriptor set.
* @returns {Message<IFileDescriptorSet>} Descriptor
* @param {string} [syntax="proto2"] Syntax
*/
Root.prototype.toDescriptor = function toDescriptor(syntax) {
var set = exports.FileDescriptorSet.create();
Root_toDescriptorRecursive(this, set.file, syntax);
return set;
};
// Traverses a namespace and assembles the descriptor set
function Root_toDescriptorRecursive(ns, files, syntax) {
// Create a new file
var file = exports.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" });
if (syntax)
file.syntax = syntax;
if (!(ns instanceof Root))
file["package"] = ns.fullName.substring(1);
// Add nested types
for (var i = 0, nested; i < ns.nestedArray.length; ++i)
if ((nested = ns._nestedArray[i]) instanceof Type)
file.messageType.push(nested.toDescriptor(syntax));
else if (nested instanceof Enum)
file.enumType.push(nested.toDescriptor());
else if (nested instanceof Field)
file.extension.push(nested.toDescriptor(syntax));
else if (nested instanceof Service)
file.service.push(nested.toDescriptor());
else if (nested instanceof /* plain */ Namespace)
Root_toDescriptorRecursive(nested, files, syntax); // requires new file
// Keep package-level options
file.options = toDescriptorOptions(ns.options, exports.FileOptions);
// And keep the file only if there is at least one nested object
if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length)
files.push(file);
}
// --- Type ---
/**
* Properties of a DescriptorProto message.
* @interface IDescriptorProto
* @property {string} [name] Message type name
* @property {IFieldDescriptorProto[]} [field] Fields
* @property {IFieldDescriptorProto[]} [extension] Extension fields
* @property {IDescriptorProto[]} [nestedType] Nested message types
* @property {IEnumDescriptorProto[]} [enumType] Nested enums
* @property {IDescriptorProtoExtensionRange[]} [extensionRange] Extension ranges
* @property {IOneofDescriptorProto[]} [oneofDecl] Oneofs
* @property {IMessageOptions} [options] Not supported
* @property {IDescriptorProtoReservedRange[]} [reservedRange] Reserved ranges
* @property {string[]} [reservedName] Reserved names
*/
/**
* Properties of a MessageOptions message.
* @interface IMessageOptions
* @property {boolean} [mapEntry=false] Whether this message is a map entry
*/
/**
* Properties of an ExtensionRange message.
* @interface IDescriptorProtoExtensionRange
* @property {number} [start] Start field id
* @property {number} [end] End field id
*/
/**
* Properties of a ReservedRange message.
* @interface IDescriptorProtoReservedRange
* @property {number} [start] Start field id
* @property {number} [end] End field id
*/
var unnamedMessageIndex = 0;
/**
* Creates a type from a descriptor.
* @param {IDescriptorProto|Reader|Uint8Array} descriptor Descriptor
* @param {string} [syntax="proto2"] Syntax
* @returns {Type} Type instance
*/
Type.fromDescriptor = function fromDescriptor(descriptor, syntax) {
// Decode the descriptor message if specified as a buffer:
if (typeof descriptor.length === "number")
descriptor = exports.DescriptorProto.decode(descriptor);
// Create the message type
var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports.MessageOptions)),
i;
/* Oneofs */ if (descriptor.oneofDecl)
for (i = 0; i < descriptor.oneofDecl.length; ++i)
type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i]));
/* Fields */ if (descriptor.field)
for (i = 0; i < descriptor.field.length; ++i) {
var field = Field.fromDescriptor(descriptor.field[i], syntax);
type.add(field);
if (descriptor.field[i].hasOwnProperty("oneofIndex")) // eslint-disable-line no-prototype-builtins
type.oneofsArray[descriptor.field[i].oneofIndex].add(field);
}
/* Extension fields */ if (descriptor.extension)
for (i = 0; i < descriptor.extension.length; ++i)
type.add(Field.fromDescriptor(descriptor.extension[i], syntax));
/* Nested types */ if (descriptor.nestedType)
for (i = 0; i < descriptor.nestedType.length; ++i) {
type.add(Type.fromDescriptor(descriptor.nestedType[i], syntax));
if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry)
type.setOption("map_entry", true);
}
/* Nested enums */ if (descriptor.enumType)
for (i = 0; i < descriptor.enumType.length; ++i)
type.add(Enum.fromDescriptor(descriptor.enumType[i]));
/* Extension ranges */ if (descriptor.extensionRange && descriptor.extensionRange.length) {
type.extensions = [];
for (i = 0; i < descriptor.extensionRange.length; ++i)
type.extensions.push([ descriptor.extensionRange[i].start, descriptor.extensionRange[i].end ]);
}
/* Reserved... */ if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) {
type.reserved = [];
/* Ranges */ if (descriptor.reservedRange)
for (i = 0; i < descriptor.reservedRange.length; ++i)
type.reserved.push([ descriptor.reservedRange[i].start, descriptor.reservedRange[i].end ]);
/* Names */ if (descriptor.reservedName)
for (i = 0; i < descriptor.reservedName.length; ++i)
type.reserved.push(descriptor.reservedName[i]);
}
return type;
};
/**
* Converts a type to a descriptor.
* @returns {Message<IDescriptorProto>} Descriptor
* @param {string} [syntax="proto2"] Syntax
*/
Type.prototype.toDescriptor = function toDescriptor(syntax) {
var descriptor = exports.DescriptorProto.create({ name: this.name }),
i;
/* Fields */ for (i = 0; i < this.fieldsArray.length; ++i) {
var fieldDescriptor;
descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(syntax));
if (this._fieldsArray[i] instanceof MapField) { // map fields are repeated FieldNameEntry
var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType),
valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType),
valueTypeName = valueType === /* type */ 11 || valueType === /* enum */ 14
? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type
: undefined;
descriptor.nestedType.push(exports.DescriptorProto.create({
name: fieldDescriptor.typeName,
field: [
exports.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }), // can't reference a type or enum
exports.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName })
],
options: exports.MessageOptions.create({ mapEntry: true })
}));
}
}
/* Oneofs */ for (i = 0; i < this.oneofsArray.length; ++i)
descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor());
/* Nested... */ for (i = 0; i < this.nestedArray.length; ++i) {
/* Extension fields */ if (this._nestedArray[i] instanceof Field)
descriptor.field.push(this._nestedArray[i].toDescriptor(syntax));
/* Types */ else if (this._nestedArray[i] instanceof Type)
descriptor.nestedType.push(this._nestedArray[i].toDescriptor(syntax));
/* Enums */ else if (this._nestedArray[i] instanceof Enum)
descriptor.enumType.push(this._nestedArray[i].toDescriptor());
// plain nested namespaces become packages instead in Root#toDescriptor
}
/* Extension ranges */ if (this.extensions)
for (i = 0; i < this.extensions.length; ++i)
descriptor.extensionRange.push(exports.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] }));
/* Reserved... */ if (this.reserved)
for (i = 0; i < this.reserved.length; ++i)
/* Names */ if (typeof this.reserved[i] === "string")
descriptor.reservedName.push(this.reserved[i]);
/* Ranges */ else
descriptor.reservedRange.push(exports.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] }));
descriptor.options = toDescriptorOptions(this.options, exports.MessageOptions);
return descriptor;
};
// --- Field ---
/**
* Properties of a FieldDescriptorProto message.
* @interface IFieldDescriptorProto
* @property {string} [name] Field name
* @property {number} [number] Field id
* @property {IFieldDescriptorProtoLabel} [label] Field rule
* @property {IFieldDescriptorProtoType} [type] Field basic type
* @property {string} [typeName] Field type name
* @property {string} [extendee] Extended type name
* @property {string} [defaultValue] Literal default value
* @property {number} [oneofIndex] Oneof index if part of a oneof
* @property {*} [jsonName] Not supported
* @property {IFieldOptions} [options] Field options
*/
/**
* Values of the FieldDescriptorProto.Label enum.
* @typedef IFieldDescriptorProtoLabel
* @type {number}
* @property {number} LABEL_OPTIONAL=1
* @property {number} LABEL_REQUIRED=2
* @property {number} LABEL_REPEATED=3
*/
/**
* Values of the FieldDescriptorProto.Type enum.
* @typedef IFieldDescriptorProtoType
* @type {number}
* @property {number} TYPE_DOUBLE=1
* @property {number} TYPE_FLOAT=2
* @property {number} TYPE_INT64=3
* @property {number} TYPE_UINT64=4
* @property {number} TYPE_INT32=5
* @property {number} TYPE_FIXED64=6
* @property {number} TYPE_FIXED32=7
* @property {number} TYPE_BOOL=8
* @property {number} TYPE_STRING=9
* @property {number} TYPE_GROUP=10
* @property {number} TYPE_MESSAGE=11
* @property {number} TYPE_BYTES=12
* @property {number} TYPE_UINT32=13
* @property {number} TYPE_ENUM=14
* @property {number} TYPE_SFIXED32=15
* @property {number} TYPE_SFIXED64=16
* @property {number} TYPE_SINT32=17
* @property {number} TYPE_SINT64=18
*/
/**
* Properties of a FieldOptions message.
* @interface IFieldOptions
* @property {boolean} [packed] Whether packed or not (defaults to `false` for proto2 and `true` for proto3)
* @property {IFieldOptionsJSType} [jstype] JavaScript value type (not used by protobuf.js)
*/
/**
* Values of the FieldOptions.JSType enum.
* @typedef IFieldOptionsJSType
* @type {number}
* @property {number} JS_NORMAL=0
* @property {number} JS_STRING=1
* @property {number} JS_NUMBER=2
*/
// copied here from parse.js
var numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;
/**
* Creates a field from a descriptor.
* @param {IFieldDescriptorProto|Reader|Uint8Array} descriptor Descriptor
* @param {string} [syntax="proto2"] Syntax
* @returns {Field} Field instance
*/
Field.fromDescriptor = function fromDescriptor(descriptor, syntax) {
// Decode the descriptor message if specified as a buffer:
if (typeof descriptor.length === "number")
descriptor = exports.DescriptorProto.decode(descriptor);
if (typeof descriptor.number !== "number")
throw Error("missing field id");
// Rewire field type
var fieldType;
if (descriptor.typeName && descriptor.typeName.length)
fieldType = descriptor.typeName;
else
fieldType = fromDescriptorType(descriptor.type);
// Rewire field rule
var fieldRule;
switch (descriptor.label) {
// 0 is reserved for errors
case 1: fieldRule = undefined; break;
case 2: fieldRule = "required"; break;
case 3: fieldRule = "repeated"; break;
default: throw Error("illegal label: " + descriptor.label);
}
var extendee = descriptor.extendee;
if (descriptor.extendee !== undefined) {
extendee = extendee.length ? extendee : undefined;
}
var field = new Field(
descriptor.name.length ? descriptor.name : "field" + descriptor.number,
descriptor.number,
fieldType,
fieldRule,
extendee
);
field.options = fromDescriptorOptions(descriptor.options, exports.FieldOptions);
if (descriptor.defaultValue && descriptor.defaultValue.length) {
var defaultValue = descriptor.defaultValue;
switch (defaultValue) {
case "true": case "TRUE":
defaultValue = true;
break;
case "false": case "FALSE":
defaultValue = false;
break;
default:
var match = numberRe.exec(defaultValue);
if (match)
defaultValue = parseInt(defaultValue); // eslint-disable-line radix
break;
}
field.setOption("default", defaultValue);
}
if (packableDescriptorType(descriptor.type)) {
if (syntax === "proto3") { // defaults to packed=true (internal preset is packed=true)
if (descriptor.options && !descriptor.options.packed)
field.setOption("packed", false);
} else if (!(descriptor.options && descriptor.options.packed)) // defaults to packed=false
field.setOption("packed", false);
}
return field;
};
/**
* Converts a field to a descriptor.
* @returns {Message<IFieldDescriptorProto>} Descriptor
* @param {string} [syntax="proto2"] Syntax
*/
Field.prototype.toDescriptor = function toDescriptor(syntax) {
var descriptor = exports.FieldDescriptorProto.create({ name: this.name, number: this.id });
if (this.map) {
descriptor.type = 11; // message
descriptor.typeName = $protobuf.util.ucFirst(this.name); // fieldName -> FieldNameEntry (built in Type#toDescriptor)
descriptor.label = 3; // repeated
} else {
// Rewire field type
switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType)) {
case 10: // group
case 11: // type
case 14: // enum
descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type;
break;
}
// Rewire field rule
switch (this.rule) {
case "repeated": descriptor.label = 3; break;
case "required": descriptor.label = 2; break;
default: descriptor.label = 1; break;
}
}
// Handle extension field
descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend;
// Handle part of oneof
if (this.partOf)
if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0)
throw Error("missing oneof");
if (this.options) {
descriptor.options = toDescriptorOptions(this.options, exports.FieldOptions);
if (this.options["default"] != null)
descriptor.defaultValue = String(this.options["default"]);
}
if (syntax === "proto3") { // defaults to packed=true
if (!this.packed)
(descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = false;
} else if (this.packed) // defaults to packed=false
(descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = true;
return descriptor;
};
// --- Enum ---
/**
* Properties of an EnumDescriptorProto message.
* @interface IEnumDescriptorProto
* @property {string} [name] Enum name
* @property {IEnumValueDescriptorProto[]} [value] Enum values
* @property {IEnumOptions} [options] Enum options
*/
/**
* Properties of an EnumValueDescriptorProto message.
* @interface IEnumValueDescriptorProto
* @property {string} [name] Name
* @property {number} [number] Value
* @property {*} [options] Not supported
*/
/**
* Properties of an EnumOptions message.
* @interface IEnumOptions
* @property {boolean} [allowAlias] Whether aliases are allowed
* @property {boolean} [deprecated]
*/
var unnamedEnumIndex = 0;
/**
* Creates an enum from a descriptor.
* @param {IEnumDescriptorProto|Reader|Uint8Array} descriptor Descriptor
* @returns {Enum} Enum instance
*/
Enum.fromDescriptor = function fromDescriptor(descriptor) {
// Decode the descriptor message if specified as a buffer:
if (typeof descriptor.length === "number")
descriptor = exports.EnumDescriptorProto.decode(descriptor);
// Construct values object
var values = {};
if (descriptor.value)
for (var i = 0; i < descriptor.value.length; ++i) {
var name = descriptor.value[i].name,
value = descriptor.value[i].number || 0;
values[name && name.length ? name : "NAME" + value] = value;
}
return new Enum(
descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++,
values,
fromDescriptorOptions(descriptor.options, exports.EnumOptions)
);
};
/**
* Converts an enum to a descriptor.
* @returns {Message<IEnumDescriptorProto>} Descriptor
*/
Enum.prototype.toDescriptor = function toDescriptor() {
// Values
var values = [];
for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i)
values.push(exports.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] }));
return exports.EnumDescriptorProto.create({
name: this.name,
value: values,
options: toDescriptorOptions(this.options, exports.EnumOptions)
});
};
// --- OneOf ---
/**
* Properties of a OneofDescriptorProto message.
* @interface IOneofDescriptorProto
* @property {string} [name] Oneof name
* @property {*} [options] Not supported
*/
var unnamedOneofIndex = 0;
/**
* Creates a oneof from a descriptor.
* @param {IOneofDescriptorProto|Reader|Uint8Array} descriptor Descriptor
* @returns {OneOf} OneOf instance
*/
OneOf.fromDescriptor = function fromDescriptor(descriptor) {
// Decode the descriptor message if specified as a buffer:
if (typeof descriptor.length === "number")
descriptor = exports.OneofDescriptorProto.decode(descriptor);
return new OneOf(
// unnamedOneOfIndex is global, not per type, because we have no ref to a type here
descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++
// fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option
);
};
/**
* Converts a oneof to a descriptor.
* @returns {Message<IOneofDescriptorProto>} Descriptor
*/
OneOf.prototype.toDescriptor = function toDescriptor() {
return exports.OneofDescriptorProto.create({
name: this.name
// options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option
});
};
// --- Service ---
/**
* Properties of a ServiceDescriptorProto message.
* @interface IServiceDescriptorProto
* @property {string} [name] Service name
* @property {IMethodDescriptorProto[]} [method] Methods
* @property {IServiceOptions} [options] Options
*/
/**
* Properties of a ServiceOptions message.
* @interface IServiceOptions
* @property {boolean} [deprecated]
*/
var unnamedServiceIndex = 0;
/**
* Creates a service from a descriptor.
* @param {IServiceDescriptorProto|Reader|Uint8Array} descriptor Descriptor
* @returns {Service} Service instance
*/
Service.fromDescriptor = function fromDescriptor(descriptor) {
// Decode the descriptor message if specified as a buffer:
if (typeof descriptor.length === "number")
descriptor = exports.ServiceDescriptorProto.decode(descriptor);
var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports.ServiceOptions));
if (descriptor.method)
for (var i = 0; i < descriptor.method.length; ++i)
service.add(Method.fromDescriptor(descriptor.method[i]));
return service;
};
/**
* Converts a service to a descriptor.
* @returns {Message<IServiceDescriptorProto>} Descriptor
*/
Service.prototype.toDescriptor = function toDescriptor() {
// Methods
var methods = [];
for (var i = 0; i < this.methodsArray; ++i)
methods.push(this._methodsArray[i].toDescriptor());
return exports.ServiceDescriptorProto.create({
name: this.name,
methods: methods,
options: toDescriptorOptions(this.options, exports.ServiceOptions)
});
};
// --- Method ---
/**
* Properties of a MethodDescriptorProto message.
* @interface IMethodDescriptorProto
* @property {string} [name] Method name
* @property {string} [inputType] Request type name
* @property {string} [outputType] Response type name
* @property {IMethodOptions} [options] Not supported
* @property {boolean} [clientStreaming=false] Whether requests are streamed
* @property {boolean} [serverStreaming=false] Whether responses are streamed
*/
/**
* Properties of a MethodOptions message.
* @interface IMethodOptions
* @property {boolean} [deprecated]
*/
var unnamedMethodIndex = 0;
/**
* Creates a method from a descriptor.
* @param {IMethodDescriptorProto|Reader|Uint8Array} descriptor Descriptor
* @returns {Method} Reflected method instance
*/
Method.fromDescriptor = function fromDescriptor(descriptor) {
// Decode the descriptor message if specified as a buffer:
if (typeof descriptor.length === "number")
descriptor = exports.MethodDescriptorProto.decode(descriptor);
return new Method(
// unnamedMethodIndex is global, not per service, because we have no ref to a service here
descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++,
"rpc",
descriptor.inputType,
descriptor.outputType,
Boolean(descriptor.clientStreaming),
Boolean(descriptor.serverStreaming),
fromDescriptorOptions(descriptor.options, exports.MethodOptions)
);
};
/**
* Converts a method to a descriptor.
* @returns {Message<IMethodDescriptorProto>} Descriptor
*/
Method.prototype.toDescriptor = function toDescriptor() {
return exports.MethodDescriptorProto.create({
name: this.name,
inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType,
outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType,
clientStreaming: this.requestStream,
serverStreaming: this.responseStream,
options: toDescriptorOptions(this.options, exports.MethodOptions)
});
};
// --- utility ---
// Converts a descriptor type to a protobuf.js basic type
function fromDescriptorType(type) {
switch (type) {
// 0 is reserved for errors
case 1: return "double";
case 2: return "float";
case 3: return "int64";
case 4: return "uint64";
case 5: return "int32";
case 6: return "fixed64";
case 7: return "fixed32";
case 8: return "bool";
case 9: return "string";
case 12: return "bytes";
case 13: return "uint32";
case 15: return "sfixed32";
case 16: return "sfixed64";
case 17: return "sint32";
case 18: return "sint64";
}
throw Error("illegal type: " + type);
}
// Tests if a descriptor type is packable
function packableDescriptorType(type) {
switch (type) {
case 1: // double
case 2: // float
case 3: // int64
case 4: // uint64
case 5: // int32
case 6: // fixed64
case 7: // fixed32
case 8: // bool
case 13: // uint32
case 14: // enum (!)
case 15: // sfixed32
case 16: // sfixed64
case 17: // sint32
case 18: // sint64
return true;
}
return false;
}
// Converts a protobuf.js basic type to a descriptor type
function toDescriptorType(type, resolvedType) {
switch (type) {
// 0 is reserved for errors
case "double": return 1;
case "float": return 2;
case "int64": return 3;
case "uint64": return 4;
case "int32": return 5;
case "fixed64": return 6;
case "fixed32": return 7;
case "bool": return 8;
case "string": return 9;
case "bytes": return 12;
case "uint32": return 13;
case "sfixed32": return 15;
case "sfixed64": return 16;
case "sint32": return 17;
case "sint64": return 18;
}
if (resolvedType instanceof Enum)
return 14;
if (resolvedType instanceof Type)
return resolvedType.group ? 10 : 11;
throw Error("illegal type: " + type);
}
// Converts descriptor options to an options object
function fromDescriptorOptions(options, type) {
if (!options)
return undefined;
var out = [];
for (var i = 0, field, key, val; i < type.fieldsArray.length; ++i)
if ((key = (field = type._fieldsArray[i]).name) !== "uninterpretedOption")
if (options.hasOwnProperty(key)) { // eslint-disable-line no-prototype-builtins
val = options[key];
if (field.resolvedType instanceof Enum && typeof val === "number" && field.resolvedType.valuesById[val] !== undefined)
val = field.resolvedType.valuesById[val];
out.push(underScore(key), val);
}
return out.length ? $protobuf.util.toObject(out) : undefined;
}
// Converts an options object to descriptor options
function toDescriptorOptions(options, type) {
if (!options)
return undefined;
var out = [];
for (var i = 0, ks = Object.keys(options), key, val; i < ks.length; ++i) {
val = options[key = ks[i]];
if (key === "default")
continue;
var field = type.fields[key];
if (!field && !(field = type.fields[key = $protobuf.util.camelCase(key)]))
continue;
out.push(key, val);
}
return out.length ? type.fromObject($protobuf.util.toObject(out)) : undefined;
}
// Calculates the shortest relative path from `from` to `to`.
function shortname(from, to) {
var fromPath = from.fullName.split("."),
toPath = to.fullName.split("."),
i = 0,
j = 0,
k = toPath.length - 1;
if (!(from instanceof Root) && to instanceof Namespace)
while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) {
var other = to.lookup(fromPath[i++], true);
if (other !== null && other !== to)
break;
++j;
}
else
for (; i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j);
return toPath.slice(j).join(".");
}
// copied here from cli/targets/proto.js
function underScore(str) {
return str.substring(0,1)
+ str.substring(1)
.replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); });
}
// --- exports ---
/**
* Reflected file descriptor set.
* @name FileDescriptorSet
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected file descriptor proto.
* @name FileDescriptorProto
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected descriptor proto.
* @name DescriptorProto
* @type {Type}
* @property {Type} ExtensionRange
* @property {Type} ReservedRange
* @const
* @tstype $protobuf.Type & {
* ExtensionRange: $protobuf.Type,
* ReservedRange: $protobuf.Type
* }
*/
/**
* Reflected field descriptor proto.
* @name FieldDescriptorProto
* @type {Type}
* @property {Enum} Label
* @property {Enum} Type
* @const
* @tstype $protobuf.Type & {
* Label: $protobuf.Enum,
* Type: $protobuf.Enum
* }
*/
/**
* Reflected oneof descriptor proto.
* @name OneofDescriptorProto
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected enum descriptor proto.
* @name EnumDescriptorProto
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected service descriptor proto.
* @name ServiceDescriptorProto
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected enum value descriptor proto.
* @name EnumValueDescriptorProto
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected method descriptor proto.
* @name MethodDescriptorProto
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected file options.
* @name FileOptions
* @type {Type}
* @property {Enum} OptimizeMode
* @const
* @tstype $protobuf.Type & {
* OptimizeMode: $protobuf.Enum
* }
*/
/**
* Reflected message options.
* @name MessageOptions
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected field options.
* @name FieldOptions
* @type {Type}
* @property {Enum} CType
* @property {Enum} JSType
* @const
* @tstype $protobuf.Type & {
* CType: $protobuf.Enum,
* JSType: $protobuf.Enum
* }
*/
/**
* Reflected oneof options.
* @name OneofOptions
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected enum options.
* @name EnumOptions
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected enum value options.
* @name EnumValueOptions
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected service options.
* @name ServiceOptions
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected method options.
* @name MethodOptions
* @type {Type}
* @const
* @tstype $protobuf.Type
*/
/**
* Reflected uninterpretet option.
* @name UninterpretedOption
* @type {Type}
* @property {Type} NamePart
* @const
* @tstype $protobuf.Type & {
* NamePart: $protobuf.Type
* }
*/
/**
* Reflected source code info.
* @name SourceCodeInfo
* @type {Type}
* @property {Type} Location
* @const
* @tstype $protobuf.Type & {
* Location: $protobuf.Type
* }
*/
/**
* Reflected generated code info.
* @name GeneratedCodeInfo
* @type {Type}
* @property {Type} Annotation
* @const
* @tstype $protobuf.Type & {
* Annotation: $protobuf.Type
* }
*/
|
var React = require('react');
var AltContainer = require('../libraries/alt/AltContainer');
var LocationStore = require('../stores/LocationStore');
var FavoritesStore = require('../stores/FavoritesStore');
var LocationActions = require('../actions/LocationActions');
var Favorites = React.createClass({
render() {
return (
<ul>
{this.props.locations.map((location, i) => {
return (
<li key={i}>{location.name}</li>
);
})}
</ul>
);
}
});
var AllLocations = React.createClass({
addFave(ev) {
var location = LocationStore.getLocation(
Number(ev.target.getAttribute('data-id'))
);
LocationActions.favoriteLocation(location);
},
render() {
if (this.props.errorMessage) {
return (
<div>{this.props.errorMessage}</div>
);
}
if (LocationStore.isLoading()) {
return (
<div>
<img src="ajax-loader.gif" />
</div>
)
}
return (
<ul>
{this.props.locations.map((location, i) => {
var faveButton = (
<button onClick={this.addFave} data-id={location.id}>
Favorite
</button>
);
return (
<li key={i}>
{location.name} {location.has_favorite ? '<3' : faveButton}
</li>
);
})}
</ul>
);
}
});
var Locations = React.createClass({
componentDidMount() {
LocationStore.fetchLocations();
},
render() {
return (
<div>
<h1>Locations</h1>
<AltContainer store={LocationStore}>
<AllLocations />
</AltContainer>
<h1>Favorites</h1>
<AltContainer store={FavoritesStore}>
<Favorites />
</AltContainer>
</div>
);
}
});
module.exports = Locations;
|
var util = require('hexo-util');
var code = [
'if tired && night:',
' sleep()'
].join('\n');
var content = [
'# Title',
'``` python',
code,
'```',
'some content',
'',
'## Another title',
'{% blockquote %}',
'quote content',
'{% endblockquote %}',
'',
'{% quote Hello World %}',
'quote content',
'{% endquote %}'
].join('\n');
exports.content = content;
exports.expected = [
'<h1 id="Title"><a href="#Title" class="headerlink" title="Title"></a>Title</h1>',
util.highlight(code, {lang: 'python'}),
'\n<p>some content</p>\n',
'<h2 id="Another-title"><a href="#Another-title" class="headerlink" title="Another title"></a>Another title</h2>',
'<blockquote>',
'<p>quote content</p>\n',
'</blockquote>\n',
'<blockquote><p>quote content</p>\n',
'<footer><strong>Hello World</strong></footer></blockquote>'
].join('');
|
import { Class } from '../mixin/index';
export default function (UIkit) {
UIkit.component('icon', UIkit.components.svg.extend({
mixins: [Class],
name: 'icon',
args: 'icon',
props: ['icon'],
defaults: {exclude: ['id', 'style', 'class', 'src']},
init() {
this.$el.addClass('uk-icon');
}
}));
[
'close',
'navbar-toggle-icon',
'overlay-icon',
'pagination-previous',
'pagination-next',
'slidenav',
'search-icon',
'totop'
].forEach(name => UIkit.component(name, UIkit.components.icon.extend({name})));
}
|
var rowIdSequence = 100;
var rowClassRules = {
"red-row": 'data.color == "Red"',
"green-row": 'data.color == "Green"',
"blue-row": 'data.color == "Blue"',
};
var gridOptions = {
defaultColDef: {
width: 80,
sortable: true,
filter: true,
resizable: true
},
rowClassRules: rowClassRules,
rowData: createRowData(),
rowDragManaged: true,
columnDefs: [
{cellRenderer: 'dragSourceCellRenderer'},
{field: "id"},
{field: "color"},
{field: "value1"},
{field: "value2"}
],
components: {
dragSourceCellRenderer: DragSourceRenderer,
},
animateRows: true
};
function createRowData() {
var data = [];
['Red', 'Green', 'Blue', 'Red', 'Green', 'Blue', 'Red', 'Green', 'Blue'].forEach(function (color) {
var newDataItem = {
id: rowIdSequence++,
color: color,
value1: Math.floor(Math.random() * 100),
value2: Math.floor(Math.random() * 100)
};
data.push(newDataItem);
});
return data;
}
function onDragOver(event) {
var types = event.dataTransfer.types;
var dragSupported = types.length;
if (dragSupported) {
event.dataTransfer.dropEffect = "move";
}
event.preventDefault();
}
function onDrop(event) {
event.preventDefault();
var userAgent = window.navigator.userAgent;
var isIE = userAgent.indexOf("Trident/") >= 0;
var textData = event.dataTransfer.getData(isIE ? 'text' : 'text/plain');
var eJsonRow = document.createElement('div');
eJsonRow.classList.add('json-row');
eJsonRow.innerText = textData;
var eJsonDisplay = document.querySelector('#eJsonDisplay');
eJsonDisplay.appendChild(eJsonRow);
}
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function () {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
});
|
hello[''] = true;
|
var get = Ember.get, set = Ember.set;
var Post, post, Comment, comment, env;
module("integration/serializer/json - JSONSerializer", {
setup: function() {
Post = DS.Model.extend({
title: DS.attr('string'),
comments: DS.hasMany('comment', {inverse:null})
});
Comment = DS.Model.extend({
body: DS.attr('string'),
post: DS.belongsTo('post')
});
env = setupStore({
post: Post,
comment: Comment
});
env.store.modelFor('post');
env.store.modelFor('comment');
},
teardown: function() {
env.store.destroy();
}
});
test("serializeAttribute", function() {
post = env.store.createRecord("post", { title: "Rails is omakase"});
var json = {};
env.serializer.serializeAttribute(post, json, "title", {type: "string"});
deepEqual(json, {
title: "Rails is omakase"
});
});
test("serializeAttribute respects keyForAttribute", function() {
env.container.register('serializer:post', DS.JSONSerializer.extend({
keyForAttribute: function(key) {
return key.toUpperCase();
}
}));
post = env.store.createRecord("post", { title: "Rails is omakase"});
var json = {};
env.container.lookup("serializer:post").serializeAttribute(post, json, "title", {type: "string"});
deepEqual(json, {
TITLE: "Rails is omakase"
});
});
test("serializeBelongsTo", function() {
post = env.store.createRecord(Post, { title: "Rails is omakase", id: "1"});
comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post});
var json = {};
env.serializer.serializeBelongsTo(comment, json, {key: "post", options: {}});
deepEqual(json, {
post: "1"
});
});
test("serializeBelongsTo with null", function() {
comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: null});
var json = {};
env.serializer.serializeBelongsTo(comment, json, {key: "post", options: {}});
deepEqual(json, {
post: null
}, "Can set a belongsTo to a null value");
});
test("serializeBelongsTo respects keyForRelationship", function() {
env.container.register('serializer:post', DS.JSONSerializer.extend({
keyForRelationship: function(key, type) {
return key.toUpperCase();
}
}));
post = env.store.createRecord(Post, { title: "Rails is omakase", id: "1"});
comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post});
var json = {};
env.container.lookup("serializer:post").serializeBelongsTo(comment, json, {key: "post", options: {}});
deepEqual(json, {
POST: "1"
});
});
test("serializeHasMany respects keyForRelationship", function() {
env.container.register('serializer:post', DS.JSONSerializer.extend({
keyForRelationship: function(key, type) {
return key.toUpperCase();
}
}));
post = env.store.createRecord(Post, { title: "Rails is omakase", id: "1"});
comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post, id: "1"});
var json = {};
env.container.lookup("serializer:post").serializeHasMany(post, json, {key: "comments", options: {}});
deepEqual(json, {
COMMENTS: ["1"]
});
});
test("serializeIntoHash", function() {
post = env.store.createRecord("post", { title: "Rails is omakase"});
var json = {};
env.serializer.serializeIntoHash(json, Post, post);
deepEqual(json, {
title: "Rails is omakase",
comments: []
});
});
test("serializePolymorphicType", function() {
env.container.register('serializer:comment', DS.JSONSerializer.extend({
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
json[relationship.key + "TYPE"] = belongsTo.constructor.typeKey;
}
}));
post = env.store.createRecord(Post, { title: "Rails is omakase", id: "1"});
comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post});
var json = {};
env.container.lookup("serializer:comment").serializeBelongsTo(comment, json, {key: "post", options: { polymorphic: true}});
deepEqual(json, {
post: "1",
postTYPE: "post"
});
});
test("extractArray normalizes each record in the array", function() {
var postNormalizeCount = 0;
var posts = [
{ title: "Rails is omakase"},
{ title: "Another Post"}
];
env.container.register('serializer:post', DS.JSONSerializer.extend({
normalize: function () {
postNormalizeCount++;
return this._super.apply(this, arguments);
}
}));
env.container.lookup("serializer:post").extractArray(env.store, Post, posts);
equal(postNormalizeCount, 2, "two posts are normalized");
});
test('Serializer should respect the attrs hash when extracting records', function(){
env.container.register("serializer:post", DS.JSONSerializer.extend({
attrs: {
title: "title_payload_key",
comments: { key: 'my_comments' }
}
}));
var jsonHash = {
title_payload_key: "Rails is omakase",
my_comments: [1, 2]
};
var post = env.container.lookup("serializer:post").extractSingle(env.store, Post, jsonHash);
equal(post.title, "Rails is omakase");
deepEqual(post.comments, [1,2]);
});
test('Serializer should respect the attrs hash when serializing records', function(){
Post.reopen({
parentPost: DS.belongsTo('post')
});
env.container.register("serializer:post", DS.JSONSerializer.extend({
attrs: {
title: "title_payload_key",
parentPost: {key: 'my_parent'}
}
}));
var parentPost = env.store.push("post", { id:2, title: "Rails is omakase"});
post = env.store.createRecord("post", { title: "Rails is omakase", parentPost: parentPost});
var payload = env.container.lookup("serializer:post").serialize(post);
equal(payload.title_payload_key, "Rails is omakase");
equal(payload.my_parent, '2');
});
test('Serializer respects `serialize: false` on the attrs hash', function(){
expect(2);
env.container.register("serializer:post", DS.JSONSerializer.extend({
attrs: {
title: {serialize: false}
}
}));
post = env.store.createRecord("post", { title: "Rails is omakase"});
var payload = env.container.lookup("serializer:post").serialize(post);
ok(!payload.hasOwnProperty('title'), "Does not add the key to instance");
ok(!payload.hasOwnProperty('[object Object]'),"Does not add some random key like [object Object]");
});
test('Serializer respects `serialize: false` on the attrs hash for a `hasMany` property', function(){
expect(1);
env.container.register("serializer:post", DS.JSONSerializer.extend({
attrs: {
comments: {serialize: false}
}
}));
post = env.store.createRecord("post", { title: "Rails is omakase"});
comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post});
var serializer = env.container.lookup("serializer:post");
var serializedProperty = serializer.keyForRelationship('comments', 'hasMany');
var payload = serializer.serialize(post);
ok(!payload.hasOwnProperty(serializedProperty), "Does not add the key to instance");
});
test('Serializer respects `serialize: false` on the attrs hash for a `belongsTo` property', function(){
expect(1);
env.container.register("serializer:comment", DS.JSONSerializer.extend({
attrs: {
post: {serialize: false}
}
}));
post = env.store.createRecord("post", { title: "Rails is omakase"});
comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post});
var serializer = env.container.lookup("serializer:comment");
var serializedProperty = serializer.keyForRelationship('post', 'belongsTo');
var payload = serializer.serialize(comment);
ok(!payload.hasOwnProperty(serializedProperty), "Does not add the key to instance");
});
test("Serializer should respect the primaryKey attribute when extracting records", function() {
env.container.register('serializer:post', DS.JSONSerializer.extend({
primaryKey: '_ID_'
}));
var jsonHash = { "_ID_": 1, title: "Rails is omakase"};
post = env.container.lookup("serializer:post").extractSingle(env.store, Post, jsonHash);
equal(post.id, "1");
equal(post.title, "Rails is omakase");
});
test("Serializer should respect the primaryKey attribute when serializing records", function() {
env.container.register('serializer:post', DS.JSONSerializer.extend({
primaryKey: '_ID_'
}));
post = env.store.createRecord("post", { id: "1", title: "Rails is omakase"});
var payload = env.container.lookup("serializer:post").serialize(post, {includeId: true});
equal(payload._ID_, "1");
});
test("Serializer should respect keyForAttribute when extracting records", function() {
env.container.register('serializer:post', DS.JSONSerializer.extend({
keyForAttribute: function(key) {
return key.toUpperCase();
}
}));
var jsonHash = {id: 1, TITLE: 'Rails is omakase'};
post = env.container.lookup("serializer:post").normalize(Post, jsonHash);
equal(post.id, "1");
equal(post.title, "Rails is omakase");
});
test("Serializer should respect keyForRelationship when extracting records", function() {
env.container.register('serializer:post', DS.JSONSerializer.extend({
keyForRelationship: function(key, type) {
return key.toUpperCase();
}
}));
var jsonHash = {id: 1, title: 'Rails is omakase', COMMENTS: ['1']};
post = env.container.lookup("serializer:post").normalize(Post, jsonHash);
deepEqual(post.comments, ['1']);
});
test("normalizePayload is called during extractSingle", function() {
env.container.register('serializer:post', DS.JSONSerializer.extend({
normalizePayload: function(payload) {
return payload.response;
}
}));
var jsonHash = {
response: {
id: 1,
title: "Rails is omakase"
}
};
post = env.container.lookup("serializer:post").extractSingle(env.store, Post, jsonHash);
equal(post.id, "1");
equal(post.title, "Rails is omakase");
});
test("Calling normalize should normalize the payload (only the passed keys)", function () {
expect(1);
var Person = DS.Model.extend({
posts: DS.hasMany('post')
});
env.container.register('serializer:post', DS.JSONSerializer.extend({
attrs: {
notInHash: 'aCustomAttrNotInHash',
inHash: 'aCustomAttrInHash'
}
}));
env.container.register('model:person', Person);
Post.reopen({
content: DS.attr('string'),
author: DS.belongsTo('person'),
notInHash: DS.attr('string'),
inHash: DS.attr('string')
});
var normalizedPayload = env.container.lookup("serializer:post").normalize(Post, {
id: '1',
title: 'Ember rocks',
author: 1,
aCustomAttrInHash: 'blah'
});
deepEqual(normalizedPayload, {
id: '1',
title: 'Ember rocks',
author: 1,
inHash: 'blah'
});
});
|
//--------------------------------------------------------------------------------------------------
$.SocketClient = $.CT.extend(
/*--------------------------------------------------------------------------------------------------
|
| -> Конструктор
|
|-------------------------------------------------------------------------------------------------*/
{private: {constructor: function(id, ws) {
this.id = id;// ID соединения
this.ws = ws;// Экземпляр соединения
}}},
/*--------------------------------------------------------------------------------------------------
|
| -> Возвращает UserID
|
|-------------------------------------------------------------------------------------------------*/
{public: {getUserID: function() {
return this.userid;
}}},
/*--------------------------------------------------------------------------------------------------
|
| -> Задает UserID
|
|-------------------------------------------------------------------------------------------------*/
{public: {setUserID: function(userid) {
this.userid = userid;
}}},
/*--------------------------------------------------------------------------------------------------
|
| -> Возвращает информацию о юзере
|
|-------------------------------------------------------------------------------------------------*/
{public: {getData: function() {
return this.data;
}}},
/*--------------------------------------------------------------------------------------------------
|
| -> Задает информацию о юзере
|
|-------------------------------------------------------------------------------------------------*/
{public: {setData: function(data) {
this.data = data;
}}},
/*--------------------------------------------------------------------------------------------------
|
| -> Отправляет сообщение об ошибке и закрывает соединение
|
|-------------------------------------------------------------------------------------------------*/
{public: {error: function(error_msg) {
// Отправляем сообщение
this.send('Error', {'error_msg': error_msg});
// Закрываем соединение
this.close();
}}},
/*--------------------------------------------------------------------------------------------------
|
| -> Отправляет сообщение
|
|-------------------------------------------------------------------------------------------------*/
{public: {send: function() {
// Создаем запрос
var r = [];
// Переводим аргументы в массив
var args = Array.prototype.slice.call(arguments, 0);
// Удаляем первый элемент
args.shift();
// Добавляем заголовок
r.push(arguments[0]);
// Добавляем тело запроса (по умолчанию пустой массив)
r.push(args);
// Конвертируем в JSON
var json = JSON.stringify(r);
// Отправляем сообщение
try {
this.ws.send(json);
} catch(e) {
}
// Записываем в консоль
$.SocketConsole['<-'](arguments[0], ($.Socket.isConsole == 'body' ? JSON.stringify(r[1]) : json));
}}},
/*--------------------------------------------------------------------------------------------------
|
| -> Закрывает соединение
|
|-------------------------------------------------------------------------------------------------*/
{public: {close: function() {
// Закрываем соединение
try {
this.ws.close();
} catch(e) {
}
}}}
);
//-------------------------------------------------------------------------------------------------- |
import journey from "lib/journey/journey.js";
import template from "./home.html";
import Ractive from "Ractive.js";
var home = {
// this function is called when we enter the route
enter: function ( route, prevRoute, options ) {
/*%injectPath%*/
// Create our view, and assign it to the route under the property 'view'.
route.view = new Ractive( {
el: options.target,
template: template,
onrender: function() {
// We want a funky intro for our text, so after 500ms we display the node with id='home-demo'
// and add the class rollIn.
setTimeout(function() {
$('#home-demo').removeClass('invisible').addClass("rollIn");
}, 500);
}
} );
},
// this function is called when we leave the route
leave: function ( route, nextRoute, options ) {
// Remove the view from the DOM
route.view.teardown();
}
};
export default home;
|
'use strict';
var digdugAdapter = require('../digdug.js');
var DigdugSauceLabsTunnel = require('digdug/SauceLabsTunnel');
module.exports = function(options) {
return digdugAdapter('SauceLabs', DigdugSauceLabsTunnel, options);
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:723a8517e1cf6d7394b64767b5361ca7f77278fc4d699827b5994af7b1be1714
size 183710
|
/*!
* Copyright © 2008 Fair Oaks Labs, Inc.
* All rights reserved.
*/
// Utility object: Encode/Decode C-style binary primitives to/from octet arrays
function JSPack()
{
// Module-level (private) variables
var el, bBE = false, m = this;
// Raw byte arrays
m._DeArray = function (a, p, l)
{
return [a.slice(p,p+l)];
};
m._EnArray = function (a, p, l, v)
{
for (var i = 0; i < l; a[p+i] = v[i]?v[i]:0, i++);
};
// ASCII characters
m._DeChar = function (a, p)
{
return String.fromCharCode(a[p]);
};
m._EnChar = function (a, p, v)
{
a[p] = v.charCodeAt(0);
};
// Little-endian (un)signed N-byte integers
m._DeInt = function (a, p)
{
var lsb = bBE?(el.len-1):0, nsb = bBE?-1:1, stop = lsb+nsb*el.len, rv, i, f;
for (rv = 0, i = lsb, f = 1; i != stop; rv+=(a[p+i]*f), i+=nsb, f*=256);
if (el.bSigned && (rv & Math.pow(2, el.len*8-1))) { rv -= Math.pow(2, el.len*8); }
return rv;
};
m._EnInt = function (a, p, v)
{
var lsb = bBE?(el.len-1):0, nsb = bBE?-1:1, stop = lsb+nsb*el.len, i;
v = (v<el.min)?el.min:(v>el.max)?el.max:v;
for (i = lsb; i != stop; a[p+i]=v&0xff, i+=nsb, v>>=8);
};
// ASCII character strings
m._DeString = function (a, p, l)
{
for (var rv = new Array(l), i = 0; i < l; rv[i] = String.fromCharCode(a[p+i]), i++);
return rv.join('');
};
m._EnString = function (a, p, l, v)
{
for (var t, i = 0; i < l; a[p+i] = (t=v.charCodeAt(i))?t:0, i++);
};
// Little-endian N-bit IEEE 754 floating point
m._De754 = function (a, p)
{
var s, e, m, i, d, nBits, mLen, eLen, eBias, eMax;
mLen = el.mLen, eLen = el.len*8-el.mLen-1, eMax = (1<<eLen)-1, eBias = eMax>>1;
i = bBE?0:(el.len-1); d = bBE?1:-1; s = a[p+i]; i+=d; nBits = -7;
for (e = s&((1<<(-nBits))-1), s>>=(-nBits), nBits += eLen; nBits > 0; e=e*256+a[p+i], i+=d, nBits-=8);
for (m = e&((1<<(-nBits))-1), e>>=(-nBits), nBits += mLen; nBits > 0; m=m*256+a[p+i], i+=d, nBits-=8);
switch (e)
{
case 0:
// Zero, or denormalized number
e = 1-eBias;
break;
case eMax:
// NaN, or +/-Infinity
return m?NaN:((s?-1:1)*Infinity);
default:
// Normalized number
m = m + Math.pow(2, mLen);
e = e - eBias;
break;
}
return (s?-1:1) * m * Math.pow(2, e-mLen);
};
m._En754 = function (a, p, v)
{
var s, e, m, i, d, c, mLen, eLen, eBias, eMax;
mLen = el.mLen, eLen = el.len*8-el.mLen-1, eMax = (1<<eLen)-1, eBias = eMax>>1;
s = v<0?1:0;
v = Math.abs(v);
if (isNaN(v) || (v == Infinity))
{
m = isNaN(v)?1:0;
e = eMax;
}
else
{
e = Math.floor(Math.log(v)/Math.LN2); // Calculate log2 of the value
if (v*(c = Math.pow(2, -e)) < 1) { e--; c*=2; } // Math.log() isn't 100% reliable
// Round by adding 1/2 the significand's LSD
if (e+eBias >= 1) { v += el.rt/c; } // Normalized: mLen significand digits
else { v += el.rt*Math.pow(2, 1-eBias); } // Denormalized: <= mLen significand digits
if (v*c >= 2) { e++; c/=2; } // Rounding can increment the exponent
if (e+eBias >= eMax)
{
// Overflow
m = 0;
e = eMax;
}
else if (e+eBias >= 1)
{
// Normalized - term order matters, as Math.pow(2, 52-e) and v*Math.pow(2, 52) can overflow
m = (v*c-1)*Math.pow(2, mLen);
e = e + eBias;
}
else
{
// Denormalized - also catches the '0' case, somewhat by chance
m = v*Math.pow(2, eBias-1)*Math.pow(2, mLen);
e = 0;
}
}
for (i = bBE?(el.len-1):0, d=bBE?-1:1; mLen >= 8; a[p+i]=m&0xff, i+=d, m/=256, mLen-=8);
for (e=(e<<mLen)|m, eLen+=mLen; eLen > 0; a[p+i]=e&0xff, i+=d, e/=256, eLen-=8);
a[p+i-d] |= s*128;
};
// Class data
m._sPattern = '(\\d+)?([AxcbBhHsfdiIlLqQ])';
m._lenLut = {'A':1, 'x':1, 'c':1, 'b':1, 'B':1, 'h':2, 'H':2, 's':1, 'f':4, 'd':8, 'i':4, 'I':4, 'l':4, 'L':4, 'q':8, 'Q':8};
m._elLut = { 'A': {en:m._EnArray, de:m._DeArray},
's': {en:m._EnString, de:m._DeString},
'c': {en:m._EnChar, de:m._DeChar},
'b': {en:m._EnInt, de:m._DeInt, len:1, bSigned:true, min:-Math.pow(2, 7), max:Math.pow(2, 7)-1},
'B': {en:m._EnInt, de:m._DeInt, len:1, bSigned:false, min:0, max:Math.pow(2, 8)-1},
'h': {en:m._EnInt, de:m._DeInt, len:2, bSigned:true, min:-Math.pow(2, 15), max:Math.pow(2, 15)-1},
'H': {en:m._EnInt, de:m._DeInt, len:2, bSigned:false, min:0, max:Math.pow(2, 16)-1},
'i': {en:m._EnInt, de:m._DeInt, len:4, bSigned:true, min:-Math.pow(2, 31), max:Math.pow(2, 31)-1},
'I': {en:m._EnInt, de:m._DeInt, len:4, bSigned:false, min:0, max:Math.pow(2, 32)-1},
'l': {en:m._EnInt, de:m._DeInt, len:4, bSigned:true, min:-Math.pow(2, 31), max:Math.pow(2, 31)-1},
'L': {en:m._EnInt, de:m._DeInt, len:4, bSigned:false, min:0, max:Math.pow(2, 32)-1},
'f': {en:m._En754, de:m._De754, len:4, mLen:23, rt:Math.pow(2, -24)-Math.pow(2, -77)},
'd': {en:m._En754, de:m._De754, len:8, mLen:52, rt:0},
'q': {en:m._EnInt, de:m._DeInt, len:8, bSigned:true, min:-Math.pow(2, 63), max:Math.pow(2, 63)-1},
'Q': {en:m._EnInt, de:m._DeInt, len:8, bSigned:false, min:0, max:Math.pow(2, 64)-1}};
// Unpack a series of n elements of size s from array a at offset p with fxn
m._UnpackSeries = function (n, s, a, p)
{
for (var fxn = el.de, rv = [], i = 0; i < n; rv.push(fxn(a, p+i*s)), i++);
return rv;
};
// Pack a series of n elements of size s from array v at offset i to array a at offset p with fxn
m._PackSeries = function (n, s, a, p, v, i)
{
for (var fxn = el.en, o = 0; o < n; fxn(a, p+o*s, v[i+o]), o++);
};
// Unpack the octet array a, beginning at offset p, according to the fmt string
m.Unpack = function (fmt, a, p)
{
// Set the private bBE flag based on the format string - assume big-endianness
bBE = (fmt.charAt(0) != '<');
p = p?p:0;
var re = new RegExp(this._sPattern, 'g'), m, n, s, rv = [];
while (m = re.exec(fmt))
{
n = ((m[1]==undefined)||(m[1]==''))?1:parseInt(m[1]);
s = this._lenLut[m[2]];
if ((p + n*s) > a.length)
{
return undefined;
}
switch (m[2])
{
case 'A': case 's':
rv.push(this._elLut[m[2]].de(a, p, n));
break;
case 'c': case 'b': case 'B': case 'h': case 'H':
case 'i': case 'I': case 'l': case 'L': case 'f': case 'd': case 'q': case 'Q':
el = this._elLut[m[2]];
rv.push(this._UnpackSeries(n, s, a, p));
break;
}
p += n*s;
}
return Array.prototype.concat.apply([], rv);
};
// Pack the supplied values into the octet array a, beginning at offset p, according to the fmt string
m.PackTo = function (fmt, a, p, values)
{
// Set the private bBE flag based on the format string - assume big-endianness
bBE = (fmt.charAt(0) != '<');
var re = new RegExp(this._sPattern, 'g'), m, n, s, i = 0, j;
while (m = re.exec(fmt))
{
n = ((m[1]==undefined)||(m[1]==''))?1:parseInt(m[1]);
s = this._lenLut[m[2]];
if ((p + n*s) > a.length)
{
return false;
}
switch (m[2])
{
case 'A': case 's':
if ((i + 1) > values.length) { return false; }
this._elLut[m[2]].en(a, p, n, values[i]);
i += 1;
break;
case 'c': case 'b': case 'B': case 'h': case 'H':
case 'i': case 'I': case 'l': case 'L': case 'f': case 'd': case 'q': case 'Q':
el = this._elLut[m[2]];
if ((i + n) > values.length) { return false; }
this._PackSeries(n, s, a, p, values, i);
i += n;
break;
case 'x':
for (j = 0; j < n; j++) { a[p+j] = 0; }
break;
}
p += n*s;
}
return a;
};
// Pack the supplied values into a new octet array, according to the fmt string
m.Pack = function (fmt, values)
{
return this.PackTo(fmt, new Array(this.CalcLength(fmt)), 0, values);
};
// Determine the number of bytes represented by the format string
m.CalcLength = function (fmt)
{
var re = new RegExp(this._sPattern, 'g'), m, sum = 0;
while (m = re.exec(fmt))
{
sum += (((m[1]==undefined)||(m[1]==''))?1:parseInt(m[1])) * this._lenLut[m[2]];
}
return sum;
};
};
|
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* A WebGLBatch Enables a group of sprites to be drawn using the same settings.
* if a group of sprites all have the same baseTexture and blendMode then they can be
* grouped into a batch. All the sprites in a batch can then be drawn in one go by the
* GPU which is hugely efficient. ALL sprites in the webGL renderer are added to a batch
* even if the batch only contains one sprite. Batching is handled automatically by the
* webGL renderer. A good tip is: the smaller the number of batchs there are, the faster
* the webGL renderer will run.
*
* @class WebGLBatch
* @contructor
* @param gl {WebGLContext} An instance of the webGL context
*/
PIXI.WebGLRenderGroup = function(gl, transparent)
{
this.gl = gl;
this.root;
this.backgroundColor;
this.transparent = transparent == undefined ? true : transparent;
this.batchs = [];
this.toRemove = [];
// console.log(this.transparent)
this.filterManager = new PIXI.WebGLFilterManager(this.transparent);
}
// constructor
PIXI.WebGLRenderGroup.prototype.constructor = PIXI.WebGLRenderGroup;
/**
* Add a display object to the webgl renderer
*
* @method setRenderable
* @param displayObject {DisplayObject}
* @private
*/
PIXI.WebGLRenderGroup.prototype.setRenderable = function(displayObject)
{
// has this changed??
if(this.root)this.removeDisplayObjectAndChildren(this.root);
displayObject.worldVisible = displayObject.visible;
// soooooo //
// to check if any batchs exist already??
// TODO what if its already has an object? should remove it
this.root = displayObject;
this.addDisplayObjectAndChildren(displayObject);
}
/**
* Renders the stage to its webgl view
*
* @method render
* @param projection {Object}
*/
PIXI.WebGLRenderGroup.prototype.render = function(projection, buffer)
{
PIXI.WebGLRenderer.updateTextures();
var gl = this.gl;
gl.uniform2f(PIXI.defaultShader.projectionVector, projection.x, projection.y);
this.filterManager.begin(projection, buffer);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
// will render all the elements in the group
var renderable;
for (var i=0; i < this.batchs.length; i++)
{
renderable = this.batchs[i];
if(renderable instanceof PIXI.WebGLBatch)
{
this.batchs[i].render();
continue;
}
// render special
this.renderSpecial(renderable, projection);
}
}
/**
* Renders a specific displayObject
*
* @method renderSpecific
* @param displayObject {DisplayObject}
* @param projection {Object}
* @private
*/
PIXI.WebGLRenderGroup.prototype.renderSpecific = function(displayObject, projection, buffer)
{
PIXI.WebGLRenderer.updateTextures();
var gl = this.gl;
gl.uniform2f(PIXI.defaultShader.projectionVector, projection.x, projection.y);
this.filterManager.begin(projection, buffer);
// to do!
// render part of the scene...
var startIndex;
var startBatchIndex;
var endIndex;
var endBatchIndex;
/*
* LOOK FOR THE NEXT SPRITE
* This part looks for the closest next sprite that can go into a batch
* it keeps looking until it finds a sprite or gets to the end of the display
* scene graph
*/
var nextRenderable = displayObject.first;
while(nextRenderable._iNext)
{
if(nextRenderable.renderable && nextRenderable.__renderGroup)break;
nextRenderable = nextRenderable._iNext;
}
var startBatch = nextRenderable.batch;
//console.log(nextRenderable);
//console.log(renderable)
if(nextRenderable instanceof PIXI.Sprite)
{
startBatch = nextRenderable.batch;
var head = startBatch.head;
var next = head;
// ok now we have the batch.. need to find the start index!
if(head == nextRenderable)
{
startIndex = 0;
}
else
{
startIndex = 1;
while(head.__next != nextRenderable)
{
startIndex++;
head = head.__next;
}
}
}
else
{
startBatch = nextRenderable;
}
// Get the LAST renderable object
var lastRenderable = displayObject.last;
while(lastRenderable._iPrev)
{
if(lastRenderable.renderable && lastRenderable.__renderGroup)break;
lastRenderable = lastRenderable._iNext;
}
if(lastRenderable instanceof PIXI.Sprite)
{
endBatch = lastRenderable.batch;
var head = endBatch.head;
if(head == lastRenderable)
{
endIndex = 0;
}
else
{
endIndex = 1;
while(head.__next != lastRenderable)
{
endIndex++;
head = head.__next;
}
}
}
else
{
endBatch = lastRenderable;
}
if(startBatch == endBatch)
{
if(startBatch instanceof PIXI.WebGLBatch)
{
startBatch.render(startIndex, endIndex+1);
}
else
{
this.renderSpecial(startBatch, projection);
}
return;
}
// now we have first and last!
startBatchIndex = this.batchs.indexOf(startBatch);
endBatchIndex = this.batchs.indexOf(endBatch);
// DO the first batch
if(startBatch instanceof PIXI.WebGLBatch)
{
startBatch.render(startIndex);
}
else
{
this.renderSpecial(startBatch, projection);
}
// DO the middle batchs..
for (var i=startBatchIndex+1; i < endBatchIndex; i++)
{
renderable = this.batchs[i];
if(renderable instanceof PIXI.WebGLBatch)
{
this.batchs[i].render();
}
else
{
this.renderSpecial(renderable, projection);
}
}
// DO the last batch..
if(endBatch instanceof PIXI.WebGLBatch)
{
endBatch.render(0, endIndex+1);
}
else
{
this.renderSpecial(endBatch, projection);
}
}
/**
* Renders a specific renderable
*
* @method renderSpecial
* @param renderable {DisplayObject}
* @param projection {Object}
* @private
*/
PIXI.WebGLRenderGroup.prototype.renderSpecial = function(renderable, projection)
{
var worldVisible = renderable.vcount === PIXI.visibleCount
if(renderable instanceof PIXI.TilingSprite)
{
if(worldVisible)this.renderTilingSprite(renderable, projection);
}
else if(renderable instanceof PIXI.Strip)
{
if(worldVisible)this.renderStrip(renderable, projection);
}
else if(renderable instanceof PIXI.CustomRenderable)
{
if(worldVisible) renderable.renderWebGL(this, projection);
}
else if(renderable instanceof PIXI.Graphics)
{
if(worldVisible && renderable.renderable) PIXI.WebGLGraphics.renderGraphics(renderable, projection);
}
else if(renderable instanceof PIXI.FilterBlock)
{
this.handleFilterBlock(renderable, projection);
}
}
flip = false;
var maskStack = [];
var maskPosition = 0;
//var usedMaskStack = [];
PIXI.WebGLRenderGroup.prototype.handleFilterBlock = function(filterBlock, projection)
{
/*
* for now only masks are supported..
*/
var gl = PIXI.gl;
if(filterBlock.open)
{
if(filterBlock.data instanceof Array)
{
this.filterManager.pushFilter(filterBlock);
// ok so..
}
else
{
maskPosition++;
maskStack.push(filterBlock)
gl.enable(gl.STENCIL_TEST);
gl.colorMask(false, false, false, false);
gl.stencilFunc(gl.ALWAYS,1,1);
gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
PIXI.WebGLGraphics.renderGraphics(filterBlock.data, projection);
gl.colorMask(true, true, true, true);
gl.stencilFunc(gl.NOTEQUAL,0,maskStack.length);
gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
}
}
else
{
if(filterBlock.data instanceof Array)
{
this.filterManager.popFilter();
}
else
{
var maskData = maskStack.pop(filterBlock)
if(maskData)
{
gl.colorMask(false, false, false, false);
gl.stencilFunc(gl.ALWAYS,1,1);
gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
PIXI.WebGLGraphics.renderGraphics(maskData.data, projection);
gl.colorMask(true, true, true, true);
gl.stencilFunc(gl.NOTEQUAL,0,maskStack.length);
gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
};
gl.disable(gl.STENCIL_TEST);
}
}
}
/**
* Updates a webgl texture
*
* @method updateTexture
* @param displayObject {DisplayObject}
* @private
*/
PIXI.WebGLRenderGroup.prototype.updateTexture = function(displayObject)
{
// TODO definitely can optimse this function..
this.removeObject(displayObject);
/*
* LOOK FOR THE PREVIOUS RENDERABLE
* This part looks for the closest previous sprite that can go into a batch
* It keeps going back until it finds a sprite or the stage
*/
var previousRenderable = displayObject.first;
while(previousRenderable != this.root)
{
previousRenderable = previousRenderable._iPrev;
if(previousRenderable.renderable && previousRenderable.__renderGroup)break;
}
/*
* LOOK FOR THE NEXT SPRITE
* This part looks for the closest next sprite that can go into a batch
* it keeps looking until it finds a sprite or gets to the end of the display
* scene graph
*/
var nextRenderable = displayObject.last;
while(nextRenderable._iNext)
{
nextRenderable = nextRenderable._iNext;
if(nextRenderable.renderable && nextRenderable.__renderGroup)break;
}
this.insertObject(displayObject, previousRenderable, nextRenderable);
}
/**
* Adds filter blocks
*
* @method addFilterBlocks
* @param start {FilterBlock}
* @param end {FilterBlock}
* @private
*/
PIXI.WebGLRenderGroup.prototype.addFilterBlocks = function(start, end)
{
start.__renderGroup = this;
end.__renderGroup = this;
/*
* LOOK FOR THE PREVIOUS RENDERABLE
* This part looks for the closest previous sprite that can go into a batch
* It keeps going back until it finds a sprite or the stage
*/
var previousRenderable = start;
while(previousRenderable != this.root.first)
{
previousRenderable = previousRenderable._iPrev;
if(previousRenderable.renderable && previousRenderable.__renderGroup)break;
}
this.insertAfter(start, previousRenderable);
/*
* LOOK FOR THE NEXT SPRITE
* This part looks for the closest next sprite that can go into a batch
* it keeps looking until it finds a sprite or gets to the end of the display
* scene graph
*/
var previousRenderable2 = end;
while(previousRenderable2 != this.root.first)
{
previousRenderable2 = previousRenderable2._iPrev;
if(previousRenderable2.renderable && previousRenderable2.__renderGroup)break;
}
this.insertAfter(end, previousRenderable2);
}
/**
* Remove filter blocks
*
* @method removeFilterBlocks
* @param start {FilterBlock}
* @param end {FilterBlock}
* @private
*/
PIXI.WebGLRenderGroup.prototype.removeFilterBlocks = function(start, end)
{
this.removeObject(start);
this.removeObject(end);
}
/**
* Adds a display object and children to the webgl context
*
* @method addDisplayObjectAndChildren
* @param displayObject {DisplayObject}
* @private
*/
PIXI.WebGLRenderGroup.prototype.addDisplayObjectAndChildren = function(displayObject)
{
if(displayObject.__renderGroup)displayObject.__renderGroup.removeDisplayObjectAndChildren(displayObject);
/*
* LOOK FOR THE PREVIOUS RENDERABLE
* This part looks for the closest previous sprite that can go into a batch
* It keeps going back until it finds a sprite or the stage
*/
var previousRenderable = displayObject.first;
while(previousRenderable != this.root.first)
{
previousRenderable = previousRenderable._iPrev;
if(previousRenderable.renderable && previousRenderable.__renderGroup)break;
}
/*
* LOOK FOR THE NEXT SPRITE
* This part looks for the closest next sprite that can go into a batch
* it keeps looking until it finds a sprite or gets to the end of the display
* scene graph
*/
var nextRenderable = displayObject.last;
while(nextRenderable._iNext)
{
nextRenderable = nextRenderable._iNext;
if(nextRenderable.renderable && nextRenderable.__renderGroup)break;
}
// one the display object hits this. we can break the loop
var tempObject = displayObject.first;
var testObject = displayObject.last._iNext;
do
{
tempObject.__renderGroup = this;
if(tempObject.renderable)
{
this.insertObject(tempObject, previousRenderable, nextRenderable);
previousRenderable = tempObject;
}
tempObject = tempObject._iNext;
}
while(tempObject != testObject)
}
/**
* Removes a display object and children to the webgl context
*
* @method removeDisplayObjectAndChildren
* @param displayObject {DisplayObject}
* @private
*/
PIXI.WebGLRenderGroup.prototype.removeDisplayObjectAndChildren = function(displayObject)
{
if(displayObject.__renderGroup != this)return;
// var displayObject = displayObject.first;
var lastObject = displayObject.last;
do
{
displayObject.__renderGroup = null;
if(displayObject.renderable)this.removeObject(displayObject);
displayObject = displayObject._iNext;
}
while(displayObject)
}
/**
* Inserts a displayObject into the linked list
*
* @method insertObject
* @param displayObject {DisplayObject}
* @param previousObject {DisplayObject}
* @param nextObject {DisplayObject}
* @private
*/
PIXI.WebGLRenderGroup.prototype.insertObject = function(displayObject, previousObject, nextObject)
{
// while looping below THE OBJECT MAY NOT HAVE BEEN ADDED
var previousSprite = previousObject;
var nextSprite = nextObject;
/*
* so now we have the next renderable and the previous renderable
*
*/
if(displayObject instanceof PIXI.Sprite)
{
var previousBatch
var nextBatch
if(previousSprite instanceof PIXI.Sprite)
{
previousBatch = previousSprite.batch;
if(previousBatch)
{
if(previousBatch.texture == displayObject.texture.baseTexture && previousBatch.blendMode == displayObject.blendMode)
{
previousBatch.insertAfter(displayObject, previousSprite);
return;
}
}
}
else
{
// TODO reword!
previousBatch = previousSprite;
}
if(nextSprite)
{
if(nextSprite instanceof PIXI.Sprite)
{
nextBatch = nextSprite.batch;
//batch may not exist if item was added to the display list but not to the webGL
if(nextBatch)
{
if(nextBatch.texture == displayObject.texture.baseTexture && nextBatch.blendMode == displayObject.blendMode)
{
nextBatch.insertBefore(displayObject, nextSprite);
return;
}
else
{
if(nextBatch == previousBatch)
{
// THERE IS A SPLIT IN THIS BATCH! //
var splitBatch = previousBatch.split(nextSprite);
// COOL!
// add it back into the array
/*
* OOPS!
* seems the new sprite is in the middle of a batch
* lets split it..
*/
var batch = PIXI.WebGLRenderer.getBatch();
var index = this.batchs.indexOf( previousBatch );
batch.init(displayObject);
this.batchs.splice(index+1, 0, batch, splitBatch);
return;
}
}
}
}
else
{
// TODO re-word!
nextBatch = nextSprite;
}
}
/*
* looks like it does not belong to any batch!
* but is also not intersecting one..
* time to create anew one!
*/
var batch = PIXI.WebGLRenderer.getBatch();
batch.init(displayObject);
if(previousBatch) // if this is invalid it means
{
var index = this.batchs.indexOf( previousBatch );
this.batchs.splice(index+1, 0, batch);
}
else
{
this.batchs.push(batch);
}
return;
}
else if(displayObject instanceof PIXI.TilingSprite)
{
// add to a batch!!
this.initTilingSprite(displayObject);
// this.batchs.push(displayObject);
}
else if(displayObject instanceof PIXI.Strip)
{
// add to a batch!!
this.initStrip(displayObject);
// this.batchs.push(displayObject);
}
else if(displayObject)// instanceof PIXI.Graphics)
{
//displayObject.initWebGL(this);
// add to a batch!!
//this.initStrip(displayObject);
//this.batchs.push(displayObject);
}
this.insertAfter(displayObject, previousSprite);
// insert and SPLIT!
}
/**
* Inserts a displayObject into the linked list
*
* @method insertAfter
* @param item {DisplayObject}
* @param displayObject {DisplayObject} The object to insert
* @private
*/
PIXI.WebGLRenderGroup.prototype.insertAfter = function(item, displayObject)
{
if(displayObject instanceof PIXI.Sprite)
{
var previousBatch = displayObject.batch;
if(previousBatch)
{
// so this object is in a batch!
// is it not? need to split the batch
if(previousBatch.tail == displayObject)
{
// is it tail? insert in to batchs
var index = this.batchs.indexOf( previousBatch );
this.batchs.splice(index+1, 0, item);
}
else
{
// TODO MODIFY ADD / REMOVE CHILD TO ACCOUNT FOR FILTERS (also get prev and next) //
// THERE IS A SPLIT IN THIS BATCH! //
var splitBatch = previousBatch.split(displayObject.__next);
// COOL!
// add it back into the array
/*
* OOPS!
* seems the new sprite is in the middle of a batch
* lets split it..
*/
var index = this.batchs.indexOf( previousBatch );
this.batchs.splice(index+1, 0, item, splitBatch);
}
}
else
{
this.batchs.push(item);
}
}
else
{
var index = this.batchs.indexOf( displayObject );
this.batchs.splice(index+1, 0, item);
}
}
/**
* Removes a displayObject from the linked list
*
* @method removeObject
* @param displayObject {DisplayObject} The object to remove
* @private
*/
PIXI.WebGLRenderGroup.prototype.removeObject = function(displayObject)
{
// loop through children..
// display object //
// add a child from the render group..
// remove it and all its children!
//displayObject.cacheVisible = false;//displayObject.visible;
/*
* removing is a lot quicker..
*
*/
var batchToRemove;
if(displayObject instanceof PIXI.Sprite)
{
// should always have a batch!
var batch = displayObject.batch;
if(!batch)return; // this means the display list has been altered befre rendering
batch.remove(displayObject);
if(batch.size==0)
{
batchToRemove = batch;
}
}
else
{
batchToRemove = displayObject;
}
/*
* Looks like there is somthing that needs removing!
*/
if(batchToRemove)
{
var index = this.batchs.indexOf( batchToRemove );
if(index == -1)return;// this means it was added then removed before rendered
// ok so.. check to see if you adjacent batchs should be joined.
// TODO may optimise?
if(index == 0 || index == this.batchs.length-1)
{
// wha - eva! just get of the empty batch!
this.batchs.splice(index, 1);
if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove);
return;
}
if(this.batchs[index-1] instanceof PIXI.WebGLBatch && this.batchs[index+1] instanceof PIXI.WebGLBatch)
{
if(this.batchs[index-1].texture == this.batchs[index+1].texture && this.batchs[index-1].blendMode == this.batchs[index+1].blendMode)
{
//console.log("MERGE")
this.batchs[index-1].merge(this.batchs[index+1]);
if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove);
PIXI.WebGLRenderer.returnBatch(this.batchs[index+1]);
this.batchs.splice(index, 2);
return;
}
}
this.batchs.splice(index, 1);
if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove);
}
}
/**
* Initializes a tiling sprite
*
* @method initTilingSprite
* @param sprite {TilingSprite} The tiling sprite to initialize
* @private
*/
PIXI.WebGLRenderGroup.prototype.initTilingSprite = function(sprite)
{
var gl = this.gl;
// make the texture tilable..
sprite.verticies = new Float32Array([0, 0,
sprite.width, 0,
sprite.width, sprite.height,
0, sprite.height]);
sprite.uvs = new Float32Array([0, 0,
1, 0,
1, 1,
0, 1]);
sprite.colors = new Float32Array([1,1,1,1]);
sprite.indices = new Uint16Array([0, 1, 3,2])//, 2]);
sprite._vertexBuffer = gl.createBuffer();
sprite._indexBuffer = gl.createBuffer();
sprite._uvBuffer = gl.createBuffer();
sprite._colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, sprite._vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, sprite.verticies, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, sprite._uvBuffer);
gl.bufferData(gl.ARRAY_BUFFER, sprite.uvs, gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, sprite._colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, sprite.colors, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, sprite._indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, sprite.indices, gl.STATIC_DRAW);
// return ( (x > 0) && ((x & (x - 1)) == 0) );
if(sprite.texture.baseTexture._glTexture)
{
gl.bindTexture(gl.TEXTURE_2D, sprite.texture.baseTexture._glTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
sprite.texture.baseTexture._powerOf2 = true;
}
else
{
sprite.texture.baseTexture._powerOf2 = true;
}
}
/**
* Renders a Strip
*
* @method renderStrip
* @param strip {Strip} The strip to render
* @param projection {Object}
* @private
*/
PIXI.WebGLRenderGroup.prototype.renderStrip = function(strip, projection)
{
var gl = this.gl;
PIXI.activateStripShader();
var shader = PIXI.stripShader;
var program = shader.program;
var m = PIXI.mat3.clone(strip.worldTransform);
PIXI.mat3.transpose(m);
// console.log(projection)
// set the matrix transform for the
gl.uniformMatrix3fv(shader.translationMatrix, false, m);
gl.uniform2f(shader.projectionVector, projection.x, projection.y);
gl.uniform2f(shader.offsetVector, -PIXI.offset.x, -PIXI.offset.y);
gl.uniform1f(shader.alpha, strip.worldAlpha);
/*
if(strip.blendMode == PIXI.blendModes.NORMAL)
{
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
}
else
{
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR);
}
*/
//console.log("!!")
if(!strip.dirty)
{
gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, strip.verticies)
gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
// update the uvs
gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer);
gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture);
gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer);
gl.vertexAttribPointer(shader.colorAttribute, 1, gl.FLOAT, false, 0, 0);
// dont need to upload!
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer);
}
else
{
strip.dirty = false;
gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.STATIC_DRAW)
gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
// update the uvs
gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer);
gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW)
gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture);
// console.log(strip.texture.baseTexture._glTexture)
gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW)
gl.vertexAttribPointer(shader.colorAttribute, 1, gl.FLOAT, false, 0, 0);
// dont need to upload!
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW);
}
gl.drawElements(gl.TRIANGLE_STRIP, strip.indices.length, gl.UNSIGNED_SHORT, 0);
PIXI.deactivateStripShader();
//gl.useProgram(PIXI.currentProgram);
}
/**
* Renders a TilingSprite
*
* @method renderTilingSprite
* @param sprite {TilingSprite} The tiling sprite to render
* @param projectionMatrix {Object}
* @private
*/
PIXI.WebGLRenderGroup.prototype.renderTilingSprite = function(sprite, projectionMatrix)
{
var gl = this.gl;
var shaderProgram = PIXI.shaderProgram;
var tilePosition = sprite.tilePosition;
var tileScale = sprite.tileScale;
var offsetX = tilePosition.x/sprite.texture.baseTexture.width;
var offsetY = tilePosition.y/sprite.texture.baseTexture.height;
var scaleX = (sprite.width / sprite.texture.baseTexture.width) / tileScale.x;
var scaleY = (sprite.height / sprite.texture.baseTexture.height) / tileScale.y;
sprite.uvs[0] = 0 - offsetX;
sprite.uvs[1] = 0 - offsetY;
sprite.uvs[2] = (1 * scaleX) -offsetX;
sprite.uvs[3] = 0 - offsetY;
sprite.uvs[4] = (1 *scaleX) - offsetX;
sprite.uvs[5] = (1 *scaleY) - offsetY;
sprite.uvs[6] = 0 - offsetX;
sprite.uvs[7] = (1 *scaleY) - offsetY;
gl.bindBuffer(gl.ARRAY_BUFFER, sprite._uvBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, sprite.uvs)
this.renderStrip(sprite, projectionMatrix);
}
/**
* Initializes a strip to be rendered
*
* @method initStrip
* @param strip {Strip} The strip to initialize
* @private
*/
PIXI.WebGLRenderGroup.prototype.initStrip = function(strip)
{
// build the strip!
var gl = this.gl;
var shaderProgram = this.shaderProgram;
strip._vertexBuffer = gl.createBuffer();
strip._indexBuffer = gl.createBuffer();
strip._uvBuffer = gl.createBuffer();
strip._colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer);
gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW);
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var FaUserMd = function FaUserMd(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm13.1 30q0 0.6-0.5 1t-1 0.4-1-0.4-0.4-1 0.4-1 1-0.4 1 0.4 0.5 1z m22.8 1.4q0 2.7-1.6 4.2t-4.3 1.5h-19.5q-2.7 0-4.4-1.5t-1.6-4.2q0-1.6 0.1-3t0.6-3 1-3 1.8-2.3 2.7-1.4q-0.5 1.2-0.5 2.7v4.6q-1.3 0.4-2.1 1.5t-0.7 2.5q0 1.8 1.2 3t3 1.3 3.1-1.3 1.2-3q0-1.4-0.8-2.5t-2-1.5v-4.6q0-1.4 0.5-2 3 2.3 6.6 2.3t6.6-2.3q0.6 0.6 0.6 2v1.5q-2.4 0-4.1 1.6t-1.7 4.1v2q-0.7 0.6-0.7 1.5 0 0.9 0.7 1.6t1.5 0.6 1.5-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.2 0.9-2t2-0.9 2 0.9 0.8 2v2q-0.7 0.6-0.7 1.5 0 0.9 0.6 1.6t1.5 0.6 1.6-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.5-0.8-2.9t-2.1-2.1q0-0.2 0-0.9t0-1.1 0-0.9-0.2-1.1-0.3-0.8q1.5 0.3 2.7 1.3t1.8 2.3 1.1 3 0.5 3 0.1 3z m-7.1-20q0 3.6-2.5 6.1t-6.1 2.5-6-2.5-2.6-6.1 2.6-6 6-2.5 6.1 2.5 2.5 6z' })
)
);
};
exports.default = FaUserMd;
module.exports = exports['default']; |
module.exports = function(grunt) {
"use strict";
var jsFiles = ["Gruntfile.js", "src/**/*.js"];
var htmlfiles = ["src/view/todoList.html", "src/view/todoFooter.html", "src/view/todoCreater.html"];
grunt.initConfig({
jshint: {
all: jsFiles,
options: {
jshintrc: ".jshintrc",
jshintignore: ".jshintignore"
}
},
watch: {
css: {
options: {
livereload: true
},
files: ["src/**/*.css"]
},
js: {
options: {
livereload: true
},
files: ["src/**/*.js"]
},
html: {
options: {
livereload: true
},
files: ["src/**/*.html"],
tasks: ["template"]
}
},
jsbeautifier: {
js: {
src: jsFiles,
options: {
config: "jsbeautifier.json"
}
},
json: {
fileTypes: [".json"],
src: ["bower.json", "package.json", "jsbeautifier.json"],
options: {
config: "jsbeautifier.json"
}
}
}
});
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-jsbeautifier");
grunt.loadNpmTasks("grunt-contrib-watch");
/*
grunt.loadTasks = "tasks";
require("matchdep").filterAll("grunt-*").forEach(grunt.loadNpmTasks);
*/
grunt.registerTask("template", "Converting HTML templates into JSON", function() {
var _ = require("underscore");
var src = "";
htmlfiles.forEach(function(file) {
var filetext = grunt.file.read(file).split("\t").join("")
.split("\n").join("")
.split(">").map(function(v) {
return v.trim();
}).join(">");
src = src + "templates[\"" + file.split("/").pop() + "\"] = " + _.template(filetext).source + ";\n";
});
grunt.file.write("src/template.js", "templates = {};" + src);
console.log("src/template.js Generated");
});
grunt.registerTask("default", ["jsbeautifier", "jshint"]);
};
|
'use strict';
var config = browser.params;
var UserModel = require(config.serverConfig.root + '/server/api/user/user.model');
describe('Logout View', function() {
var login = function(user) {
let promise = browser.get(config.baseUrl + '/login');
require('../login/login.po').login(user);
return promise;
};
var testUser = {
name: 'Test User',
email: '[email protected]',
password: 'test'
};
beforeEach(function() {
return UserModel
.removeAsync()
.then(function() {
return UserModel.createAsync(testUser);
})
.then(function() {
return login(testUser);
});
});
after(function() {
return UserModel.removeAsync();
})
describe('with local auth', function() {
it('should logout a user and redirecting to "/"', function() {
var navbar = require('../../components/navbar/navbar.po');
browser.getCurrentUrl().should.eventually.equal(config.baseUrl + '/');
navbar.navbarAccountGreeting.getText().should.eventually.equal('Hello ' + testUser.name);
browser.get(config.baseUrl + '/logout');
navbar = require('../../components/navbar/navbar.po');
browser.getCurrentUrl().should.eventually.equal(config.baseUrl + '/');
navbar.navbarAccountGreeting.isDisplayed().should.eventually.equal(false);
});
});
});
|
var gridOptions = {
columnDefs: [
{ field: 'country', rowGroup: true, hide: true },
{ field: 'athlete', minWidth: 180 },
{ field: 'age' },
{ field: 'year' },
{ field: 'date', minWidth: 150 },
{ field: 'sport', minWidth: 150 },
{ field: 'gold' },
{ field: 'silver' },
{ field: 'bronze' },
{ field: 'total' }
],
defaultColDef: {
flex: 1,
minWidth: 100,
sortable: true,
filter: true
},
autoGroupColumnDef: {
minWidth: 200
},
groupDefaultExpanded: 1,
};
function onBtForEachNode() {
console.log('### api.forEachNode() ###');
gridOptions.api.forEachNode(this.printNode);
}
function onBtForEachNodeAfterFilter() {
console.log('### api.forEachNodeAfterFilter() ###');
gridOptions.api.forEachNodeAfterFilter(this.printNode);
}
function onBtForEachNodeAfterFilterAndSort() {
console.log('### api.forEachNodeAfterFilterAndSort() ###');
gridOptions.api.forEachNodeAfterFilterAndSort(this.printNode);
}
function onBtForEachLeafNode() {
console.log('### api.forEachLeafNode() ###');
gridOptions.api.forEachLeafNode(this.printNode);
}
// inScope[printNode]
function printNode(node, index) {
if (node.group) {
console.log(index + ' -> group: ' + node.key);
} else {
console.log(index + ' -> data: ' + node.data.country + ', ' + node.data.athlete);
}
}
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' })
.then(function(data) {
gridOptions.api.setRowData(data.slice(0, 50));
});
});
|
define(
//begin v1.x content
{
"dateFormatItem-Ehm": "E h:mm a",
"days-standAlone-short": [
"อา.",
"จ.",
"อ.",
"พ.",
"พฤ.",
"ศ.",
"ส."
],
"months-format-narrow": [
"ม.ค.",
"ก.พ.",
"มี.ค.",
"เม.ย.",
"พ.ค.",
"มิ.ย.",
"ก.ค.",
"ส.ค.",
"ก.ย.",
"ต.ค.",
"พ.ย.",
"ธ.ค."
],
"field-second-relative+0": "ขณะนี้",
"quarters-standAlone-narrow": [
"1",
"2",
"3",
"4"
],
"field-weekday": "วันในสัปดาห์",
"dateFormatItem-yQQQ": "QQQ y",
"dateFormatItem-yMEd": "E d/M/y",
"field-wed-relative+0": "พุธนี้",
"field-wed-relative+1": "พุธหน้า",
"dateFormatItem-GyMMMEd": "E d MMM G y",
"dateFormatItem-MMMEd": "E d MMM",
"eraNarrow": [
"ก่อน ค.ศ.",
"ก.ส.ศ.",
"ค.ศ.",
"ส.ศ."
],
"field-tue-relative+-1": "อังคารที่แล้ว",
"days-format-short": [
"อา.",
"จ.",
"อ.",
"พ.",
"พฤ.",
"ศ.",
"ส."
],
"dateFormat-long": "d MMMM G y",
"field-fri-relative+-1": "ศุกร์ที่แล้ว",
"field-wed-relative+-1": "พุธที่แล้ว",
"months-format-wide": [
"มกราคม",
"กุมภาพันธ์",
"มีนาคม",
"เมษายน",
"พฤษภาคม",
"มิถุนายน",
"กรกฎาคม",
"สิงหาคม",
"กันยายน",
"ตุลาคม",
"พฤศจิกายน",
"ธันวาคม"
],
"dateTimeFormat-medium": "{1} {0}",
"dayPeriods-format-wide-pm": "หลังเที่ยง",
"dateFormat-full": "EEEEที่ d MMMM G y",
"field-thu-relative+-1": "พฤหัสที่แล้ว",
"dateFormatItem-Md": "d/M",
"dateFormatItem-yMd": "d/M/y",
"field-era": "สมัย",
"dateFormatItem-yM": "M/y",
"months-standAlone-wide": [
"มกราคม",
"กุมภาพันธ์",
"มีนาคม",
"เมษายน",
"พฤษภาคม",
"มิถุนายน",
"กรกฎาคม",
"สิงหาคม",
"กันยายน",
"ตุลาคม",
"พฤศจิกายน",
"ธันวาคม"
],
"timeFormat-short": "HH:mm",
"quarters-format-wide": [
"ไตรมาส 1",
"ไตรมาส 2",
"ไตรมาส 3",
"ไตรมาส 4"
],
"dateFormatItem-yQQQQ": "QQQQ G y",
"timeFormat-long": "H นาฬิกา mm นาที ss วินาที z",
"field-year": "ปี",
"dateFormatItem-yMMM": "MMM y",
"field-hour": "ชั่วโมง",
"months-format-abbr": [
"ม.ค.",
"ก.พ.",
"มี.ค.",
"เม.ย.",
"พ.ค.",
"มิ.ย.",
"ก.ค.",
"ส.ค.",
"ก.ย.",
"ต.ค.",
"พ.ย.",
"ธ.ค."
],
"field-sat-relative+0": "เสาร์นี้",
"field-sat-relative+1": "เสาร์หน้า",
"timeFormat-full": "H นาฬิกา mm นาที ss วินาที zzzz",
"field-day-relative+0": "วันนี้",
"field-thu-relative+0": "พฤหัสนี้",
"field-day-relative+1": "พรุ่งนี้",
"field-thu-relative+1": "พฤหัสหน้า",
"dateFormatItem-GyMMMd": "d MMM G y",
"field-day-relative+2": "มะรืนนี้",
"dateFormatItem-H": "HH",
"months-standAlone-abbr": [
"ม.ค.",
"ก.พ.",
"มี.ค.",
"เม.ย.",
"พ.ค.",
"มิ.ย.",
"ก.ค.",
"ส.ค.",
"ก.ย.",
"ต.ค.",
"พ.ย.",
"ธ.ค."
],
"quarters-format-abbr": [
"ไตรมาส 1",
"ไตรมาส 2",
"ไตรมาส 3",
"ไตรมาส 4"
],
"quarters-standAlone-wide": [
"ไตรมาส 1",
"ไตรมาส 2",
"ไตรมาส 3",
"ไตรมาส 4"
],
"dateFormatItem-Gy": "G y",
"dateFormatItem-M": "L",
"days-standAlone-wide": [
"วันอาทิตย์",
"วันจันทร์",
"วันอังคาร",
"วันพุธ",
"วันพฤหัสบดี",
"วันศุกร์",
"วันเสาร์"
],
"dateFormatItem-MMMMd": "d MMMM",
"timeFormat-medium": "HH:mm:ss",
"field-sun-relative+0": "อาทิตย์นี้",
"dateFormatItem-Hm": "HH:mm",
"field-sun-relative+1": "อาทิตย์หน้า",
"quarters-standAlone-abbr": [
"ไตรมาส 1",
"ไตรมาส 2",
"ไตรมาส 3",
"ไตรมาส 4"
],
"eraAbbr": [
"ปีก่อน ค.ศ.",
"ค.ศ."
],
"field-minute": "นาที",
"field-dayperiod": "ช่วงวัน",
"days-standAlone-abbr": [
"อา.",
"จ.",
"อ.",
"พ.",
"พฤ.",
"ศ.",
"ส."
],
"dateFormatItem-d": "d",
"dateFormatItem-ms": "mm:ss",
"quarters-format-narrow": [
"1",
"2",
"3",
"4"
],
"field-day-relative+-1": "เมื่อวาน",
"dateFormatItem-h": "h a",
"dateTimeFormat-long": "{1} {0}",
"field-day-relative+-2": "เมื่อวานซืน",
"dateFormatItem-MMMd": "d MMM",
"dateFormatItem-MEd": "E d/M",
"dateTimeFormat-full": "{1} {0}",
"field-fri-relative+0": "ศุกร์นี้",
"dateFormatItem-yMMMM": "MMMM G y",
"field-fri-relative+1": "ศุกร์หน้า",
"field-day": "วัน",
"days-format-wide": [
"วันอาทิตย์",
"วันจันทร์",
"วันอังคาร",
"วันพุธ",
"วันพฤหัสบดี",
"วันศุกร์",
"วันเสาร์"
],
"field-zone": "เขตเวลา",
"dateFormatItem-y": "y",
"months-standAlone-narrow": [
"ม.ค.",
"ก.พ.",
"มี.ค.",
"เม.ย.",
"พ.ค.",
"มิ.ย.",
"ก.ค.",
"ส.ค.",
"ก.ย.",
"ต.ค.",
"พ.ย.",
"ธ.ค."
],
"field-year-relative+-1": "ปีที่แล้ว",
"field-month-relative+-1": "เดือนที่แล้ว",
"dateFormatItem-hm": "h:mm a",
"days-format-abbr": [
"อา.",
"จ.",
"อ.",
"พ.",
"พฤ.",
"ศ.",
"ส."
],
"dateFormatItem-yMMMd": "d MMM y",
"eraNames": [
"ปีก่อนคริสต์ศักราช",
"คริสต์ศักราช"
],
"days-format-narrow": [
"อา",
"จ",
"อ",
"พ",
"พฤ",
"ศ",
"ส"
],
"days-standAlone-narrow": [
"อา",
"จ",
"อ",
"พ",
"พฤ",
"ศ",
"ส"
],
"dateFormatItem-MMM": "LLL",
"field-month": "เดือน",
"field-tue-relative+0": "อังคารนี้",
"field-tue-relative+1": "อังคารหน้า",
"dayPeriods-format-wide-am": "ก่อนเที่ยง",
"dateFormatItem-MMMMEd": "E d MMMM",
"dateFormatItem-EHm": "E HH:mm",
"field-mon-relative+0": "จันทร์นี้",
"field-mon-relative+1": "จันทร์หน้า",
"dateFormat-short": "d/M/yy",
"dateFormatItem-EHms": "E HH:mm:ss",
"dateFormatItem-Ehms": "E h:mm:ss a",
"field-second": "วินาที",
"field-sat-relative+-1": "เสาร์ที่แล้ว",
"dateFormatItem-yMMMEd": "E d MMM y",
"field-sun-relative+-1": "อาทิตย์ที่แล้ว",
"field-month-relative+0": "เดือนนี้",
"field-month-relative+1": "เดือนหน้า",
"dateFormatItem-Ed": "E d",
"dateTimeFormats-appendItem-Timezone": "{0} {1}",
"field-week": "สัปดาห์",
"dateFormat-medium": "d MMM y",
"field-year-relative+0": "ปีนี้",
"field-week-relative+-1": "สัปดาห์ที่แล้ว",
"field-year-relative+1": "ปีหน้า",
"dateFormatItem-mmss": "mm:ss",
"dateTimeFormat-short": "{1} {0}",
"dateFormatItem-Hms": "HH:mm:ss",
"dateFormatItem-hms": "h:mm:ss a",
"dateFormatItem-GyMMM": "MMM G y",
"field-mon-relative+-1": "จันทร์ที่แล้ว",
"field-week-relative+0": "สัปดาห์นี้",
"field-week-relative+1": "สัปดาห์หน้า"
}
//end v1.x content
); |
module.exports = function(gatewayd) {
// ADD PLUGINS HERE, SUCH AS SETUP WIZARD
const WizardPlugin = require('gatewayd-setup-wizard-plugin');
var wizardPlugin = new WizardPlugin({
gatewayd: gatewayd
});
gatewayd.server.use('/', wizardPlugin.router);
}
|
/*global define*/
define({
"_widgetLabel": "グリッド オーバーレイ",
"description": "座標グリッド オーバーレイを表示するカスタム Web AppBuilder ウィジェットです。"
}); |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define(factory) :
(factory());
}(this, (function () { 'use strict';
var foo = 42;
assert.equal( foo, 42 );
}))); |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* The resource limits.
*
*/
class ResourceLimits {
/**
* Create a ResourceLimits.
* @member {number} [memoryInGB] The memory limit in GB of this container
* instance.
* @member {number} [cpu] The CPU limit of this container instance.
*/
constructor() {
}
/**
* Defines the metadata of ResourceLimits
*
* @returns {object} metadata of ResourceLimits
*
*/
mapper() {
return {
required: false,
serializedName: 'ResourceLimits',
type: {
name: 'Composite',
className: 'ResourceLimits',
modelProperties: {
memoryInGB: {
required: false,
serializedName: 'memoryInGB',
type: {
name: 'Number'
}
},
cpu: {
required: false,
serializedName: 'cpu',
type: {
name: 'Number'
}
}
}
}
};
}
}
module.exports = ResourceLimits;
|
#!/usr/bin/env node
/*!
* Module dependencies.
*/
var CLI = require('../lib/cli'),
argv = require('optimist').boolean('d')
.boolean('device')
.boolean('e')
.boolean('emulator')
.boolean('V')
.boolean('verbose')
.boolean('v')
.boolean('version')
.boolean('h')
.boolean('help')
.argv;
/*!
* Run the command-line client.
*/
var cli = new CLI().argv(argv);
|
const {app, ipcMain, webContents, BrowserWindow} = require('electron')
const {getAllWebContents} = process.atomBinding('web_contents')
const renderProcessPreferences = process.atomBinding('render_process_preferences').forAllWebContents()
const {Buffer} = require('buffer')
const fs = require('fs')
const path = require('path')
const url = require('url')
// TODO(zcbenz): Remove this when we have Object.values().
const objectValues = function (object) {
return Object.keys(object).map(function (key) { return object[key] })
}
// Mapping between extensionId(hostname) and manifest.
const manifestMap = {} // extensionId => manifest
const manifestNameMap = {} // name => manifest
const generateExtensionIdFromName = function (name) {
return name.replace(/[\W_]+/g, '-').toLowerCase()
}
const isWindowOrWebView = function (webContents) {
const type = webContents.getType()
return type === 'window' || type === 'webview'
}
// Create or get manifest object from |srcDirectory|.
const getManifestFromPath = function (srcDirectory) {
let manifest
let manifestContent
try {
manifestContent = fs.readFileSync(path.join(srcDirectory, 'manifest.json'))
} catch (readError) {
console.warn(`Reading ${path.join(srcDirectory, 'manifest.json')} failed.`)
console.warn(readError.stack || readError)
throw readError
}
try {
manifest = JSON.parse(manifestContent)
} catch (parseError) {
console.warn(`Parsing ${path.join(srcDirectory, 'manifest.json')} failed.`)
console.warn(parseError.stack || parseError)
throw parseError
}
if (!manifestNameMap[manifest.name]) {
const extensionId = generateExtensionIdFromName(manifest.name)
manifestMap[extensionId] = manifestNameMap[manifest.name] = manifest
Object.assign(manifest, {
srcDirectory: srcDirectory,
extensionId: extensionId,
// We can not use 'file://' directly because all resources in the extension
// will be treated as relative to the root in Chrome.
startPage: url.format({
protocol: 'chrome-extension',
slashes: true,
hostname: extensionId,
pathname: manifest.devtools_page
})
})
return manifest
} else if (manifest && manifest.name) {
console.warn(`Attempted to load extension "${manifest.name}" that has already been loaded.`)
}
}
// Manage the background pages.
const backgroundPages = {}
const startBackgroundPages = function (manifest) {
if (backgroundPages[manifest.extensionId] || !manifest.background) return
let html
let name
if (manifest.background.page) {
name = manifest.background.page
html = fs.readFileSync(path.join(manifest.srcDirectory, manifest.background.page))
} else {
name = '_generated_background_page.html'
const scripts = manifest.background.scripts.map((name) => {
return `<script src="${name}"></script>`
}).join('')
html = new Buffer(`<html><body>${scripts}</body></html>`)
}
const contents = webContents.create({
partition: 'persist:__chrome_extension',
isBackgroundPage: true,
commandLineSwitches: ['--background-page']
})
backgroundPages[manifest.extensionId] = { html: html, webContents: contents, name: name }
contents.loadURL(url.format({
protocol: 'chrome-extension',
slashes: true,
hostname: manifest.extensionId,
pathname: name
}))
}
const removeBackgroundPages = function (manifest) {
if (!backgroundPages[manifest.extensionId]) return
backgroundPages[manifest.extensionId].webContents.destroy()
delete backgroundPages[manifest.extensionId]
}
const sendToBackgroundPages = function (...args) {
for (const page of objectValues(backgroundPages)) {
page.webContents.sendToAll(...args)
}
}
// Dispatch web contents events to Chrome APIs
const hookWebContentsEvents = function (webContents) {
const tabId = webContents.id
sendToBackgroundPages('CHROME_TABS_ONCREATED')
webContents.on('will-navigate', (event, url) => {
sendToBackgroundPages('CHROME_WEBNAVIGATION_ONBEFORENAVIGATE', {
frameId: 0,
parentFrameId: -1,
processId: webContents.getProcessId(),
tabId: tabId,
timeStamp: Date.now(),
url: url
})
})
webContents.on('did-navigate', (event, url) => {
sendToBackgroundPages('CHROME_WEBNAVIGATION_ONCOMPLETED', {
frameId: 0,
parentFrameId: -1,
processId: webContents.getProcessId(),
tabId: tabId,
timeStamp: Date.now(),
url: url
})
})
webContents.once('destroyed', () => {
sendToBackgroundPages('CHROME_TABS_ONREMOVED', tabId)
})
}
// Handle the chrome.* API messages.
let nextId = 0
ipcMain.on('CHROME_RUNTIME_CONNECT', function (event, extensionId, connectInfo) {
const page = backgroundPages[extensionId]
if (!page) {
console.error(`Connect to unknown extension ${extensionId}`)
return
}
const portId = ++nextId
event.returnValue = {tabId: page.webContents.id, portId: portId}
event.sender.once('render-view-deleted', () => {
if (page.webContents.isDestroyed()) return
page.webContents.sendToAll(`CHROME_PORT_DISCONNECT_${portId}`)
})
page.webContents.sendToAll(`CHROME_RUNTIME_ONCONNECT_${extensionId}`, event.sender.id, portId, connectInfo)
})
ipcMain.on('CHROME_I18N_MANIFEST', function (event, extensionId) {
event.returnValue = manifestMap[extensionId]
})
ipcMain.on('CHROME_RUNTIME_SENDMESSAGE', function (event, extensionId, message) {
const page = backgroundPages[extensionId]
if (!page) {
console.error(`Connect to unknown extension ${extensionId}`)
return
}
page.webContents.sendToAll(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, event.sender.id, message)
})
ipcMain.on('CHROME_TABS_SEND_MESSAGE', function (event, tabId, extensionId, isBackgroundPage, message) {
const contents = webContents.fromId(tabId)
if (!contents) {
console.error(`Sending message to unknown tab ${tabId}`)
return
}
const senderTabId = isBackgroundPage ? null : event.sender.id
contents.sendToAll(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, senderTabId, message)
})
ipcMain.on('CHROME_TABS_EXECUTESCRIPT', function (event, requestId, tabId, extensionId, details) {
const contents = webContents.fromId(tabId)
if (!contents) {
console.error(`Sending message to unknown tab ${tabId}`)
return
}
let code, url
if (details.file) {
const manifest = manifestMap[extensionId]
code = String(fs.readFileSync(path.join(manifest.srcDirectory, details.file)))
url = `chrome-extension://${extensionId}${details.file}`
} else {
code = details.code
url = `chrome-extension://${extensionId}/${String(Math.random()).substr(2, 8)}.js`
}
contents.send('CHROME_TABS_EXECUTESCRIPT', event.sender.id, requestId, extensionId, url, code)
})
// Transfer the content scripts to renderer.
const contentScripts = {}
const injectContentScripts = function (manifest) {
if (contentScripts[manifest.name] || !manifest.content_scripts) return
const readArrayOfFiles = function (relativePath) {
return {
url: `chrome-extension://${manifest.extensionId}/${relativePath}`,
code: String(fs.readFileSync(path.join(manifest.srcDirectory, relativePath)))
}
}
const contentScriptToEntry = function (script) {
return {
matches: script.matches,
js: script.js.map(readArrayOfFiles),
runAt: script.run_at || 'document_idle'
}
}
try {
const entry = {
extensionId: manifest.extensionId,
contentScripts: manifest.content_scripts.map(contentScriptToEntry)
}
contentScripts[manifest.name] = renderProcessPreferences.addEntry(entry)
} catch (e) {
console.error('Failed to read content scripts', e)
}
}
const removeContentScripts = function (manifest) {
if (!contentScripts[manifest.name]) return
renderProcessPreferences.removeEntry(contentScripts[manifest.name])
delete contentScripts[manifest.name]
}
// Transfer the |manifest| to a format that can be recognized by the
// |DevToolsAPI.addExtensions|.
const manifestToExtensionInfo = function (manifest) {
return {
startPage: manifest.startPage,
srcDirectory: manifest.srcDirectory,
name: manifest.name,
exposeExperimentalAPIs: true
}
}
// Load the extensions for the window.
const loadExtension = function (manifest) {
startBackgroundPages(manifest)
injectContentScripts(manifest)
}
const loadDevToolsExtensions = function (win, manifests) {
if (!win.devToolsWebContents) return
manifests.forEach(loadExtension)
const extensionInfoArray = manifests.map(manifestToExtensionInfo)
win.devToolsWebContents.executeJavaScript(`DevToolsAPI.addExtensions(${JSON.stringify(extensionInfoArray)})`)
}
app.on('web-contents-created', function (event, webContents) {
if (!isWindowOrWebView(webContents)) return
hookWebContentsEvents(webContents)
webContents.on('devtools-opened', function () {
loadDevToolsExtensions(webContents, objectValues(manifestMap))
})
})
// The chrome-extension: can map a extension URL request to real file path.
const chromeExtensionHandler = function (request, callback) {
const parsed = url.parse(request.url)
if (!parsed.hostname || !parsed.path) return callback()
const manifest = manifestMap[parsed.hostname]
if (!manifest) return callback()
const page = backgroundPages[parsed.hostname]
if (page && parsed.path === `/${page.name}`) {
return callback({
mimeType: 'text/html',
data: page.html
})
}
fs.readFile(path.join(manifest.srcDirectory, parsed.path), function (err, content) {
if (err) {
return callback(-6) // FILE_NOT_FOUND
} else {
return callback(content)
}
})
}
app.on('session-created', function (ses) {
ses.protocol.registerBufferProtocol('chrome-extension', chromeExtensionHandler, function (error) {
if (error) {
console.error(`Unable to register chrome-extension protocol: ${error}`)
}
})
})
// The persistent path of "DevTools Extensions" preference file.
let loadedExtensionsPath = null
app.on('will-quit', function () {
try {
const loadedExtensions = objectValues(manifestMap).map(function (manifest) {
return manifest.srcDirectory
})
if (loadedExtensions.length > 0) {
try {
fs.mkdirSync(path.dirname(loadedExtensionsPath))
} catch (error) {
// Ignore error
}
fs.writeFileSync(loadedExtensionsPath, JSON.stringify(loadedExtensions))
} else {
fs.unlinkSync(loadedExtensionsPath)
}
} catch (error) {
// Ignore error
}
})
// We can not use protocol or BrowserWindow until app is ready.
app.once('ready', function () {
// Load persisted extensions.
loadedExtensionsPath = path.join(app.getPath('userData'), 'DevTools Extensions')
try {
const loadedExtensions = JSON.parse(fs.readFileSync(loadedExtensionsPath))
if (Array.isArray(loadedExtensions)) {
for (const srcDirectory of loadedExtensions) {
// Start background pages and set content scripts.
const manifest = getManifestFromPath(srcDirectory)
loadExtension(manifest)
}
}
} catch (error) {
// Ignore error
}
// The public API to add/remove extensions.
BrowserWindow.addDevToolsExtension = function (srcDirectory) {
const manifest = getManifestFromPath(srcDirectory)
if (manifest) {
loadExtension(manifest)
for (const webContents of getAllWebContents()) {
if (isWindowOrWebView(webContents)) {
loadDevToolsExtensions(webContents, [manifest])
}
}
return manifest.name
}
}
BrowserWindow.removeDevToolsExtension = function (name) {
const manifest = manifestNameMap[name]
if (!manifest) return
removeBackgroundPages(manifest)
removeContentScripts(manifest)
delete manifestMap[manifest.extensionId]
delete manifestNameMap[name]
}
BrowserWindow.getDevToolsExtensions = function () {
const extensions = {}
Object.keys(manifestNameMap).forEach(function (name) {
const manifest = manifestNameMap[name]
extensions[name] = {name: manifest.name, version: manifest.version}
})
return extensions
}
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.